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
Why does this throw the error whereas the other methods return it as `Mono.error`?
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is not supported for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case OCT: return symmetricKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); default: throw new UnsupportedOperationException(String.format("Encrypt Async is not allowed for Key Type: %s", key.kty().toString())); } }
throw new UnsupportedOperationException(String.format("Encrypt Async is not allowed for Key Type: %s", key.kty().toString()));
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing permission/not supported for key with id %s", key.kid()))); } return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); }
class CryptographyAsyncClient { private JsonWebKey key; private CryptographyService service; private String version; private EcKeyCryptographyClient ecKeyCryptographyClient; private RsaKeyCryptographyClient rsaKeyCryptographyClient; private CryptographyServiceClient cryptographyServiceClient; private SymmetricKeyCryptographyClient symmetricKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if(!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); ecKeyCryptographyClient = new EcKeyCryptographyClient(cryptographyServiceClient); rsaKeyCryptographyClient = new RsaKeyCryptographyClient(cryptographyServiceClient); symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(cryptographyServiceClient); } private void initializeCryptoClients() { switch(key.kty()){ case RSA: case RSA_HSM: rsaKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: ecKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKey() { return withContext(context -> getKey(context)); } Mono<Response<Key>> getKey(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case OCT: return symmetricKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Decrypt operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signAsync(algorithm, digest, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signAsync(algorithm, digest, context, key); case OCT: return symmetricKeyCryptographyClient.signAsync(algorithm, digest, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Sign operaiton is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case OCT: return symmetricKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Verify operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case EC: case EC_HSM: return ecKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case OCT: return symmetricKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", this.key.kty().toString()))); } } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case OCT: return symmetricKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signDataAsync(algorithm, data, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signDataAsync(algorithm, data, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } private void unpackAndValidateId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); version = (tokens.length >= 4 ? tokens[3] : null); if(Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if(Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { e.printStackTrace(); } } else { throw new IllegalArgumentException("Key Id is invalid"); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { if (operations.contains(keyOperation)) { return true; } return false; } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if(key == null) { try { this.key = getKey().block().value().keyMaterial(); keyAvailableLocally = this.key.isValid(); } catch (HttpResponseException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: private JsonWebKey key; private final CryptographyService service; private final CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); if (!key.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (key.keyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (key.kty() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if (!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } switch (key.kty()) { case RSA: case RSA_HSM: localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKeyWithResponse() { return withContext(context -> getKeyWithResponse(context)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing the requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Key> getKey() { return getKeyWithResponse().flatMap(FluxUtil::toMono); } Mono<Response<Key>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.wrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.unwrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign-data} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify-data} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); } private void unpackAndValidateId(String keyId) { if (ImplUtils.isNullOrEmpty(keyId)) { throw new IllegalArgumentException("Key Id is invalid"); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); if (Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if (Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { throw new IllegalArgumentException("The key identifier is malformed", e); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null) { try { this.key = getKey().block().keyMaterial(); keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } }
Let's invert this case and just have if -> throw and everything else outside of an if/else block
private void unpackAndValidateId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); version = (tokens.length >= 4 ? tokens[3] : null); if(Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if(Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { e.printStackTrace(); } } else { throw new IllegalArgumentException("Key Id is invalid"); } }
if (keyId != null && keyId.length() > 0) {
private void unpackAndValidateId(String keyId) { if (ImplUtils.isNullOrEmpty(keyId)) { throw new IllegalArgumentException("Key Id is invalid"); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); if (Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if (Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { throw new IllegalArgumentException("The key identifier is malformed", e); } }
class CryptographyAsyncClient { private JsonWebKey key; private CryptographyService service; private String version; private EcKeyCryptographyClient ecKeyCryptographyClient; private RsaKeyCryptographyClient rsaKeyCryptographyClient; private CryptographyServiceClient cryptographyServiceClient; private SymmetricKeyCryptographyClient symmetricKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if(!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); ecKeyCryptographyClient = new EcKeyCryptographyClient(cryptographyServiceClient); rsaKeyCryptographyClient = new RsaKeyCryptographyClient(cryptographyServiceClient); symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(cryptographyServiceClient); } private void initializeCryptoClients() { switch(key.kty()){ case RSA: case RSA_HSM: rsaKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: ecKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKey() { return withContext(context -> getKey(context)); } Mono<Response<Key>> getKey(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is not supported for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case OCT: return symmetricKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); default: throw new UnsupportedOperationException(String.format("Encrypt Async is not allowed for Key Type: %s", key.kty().toString())); } } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case OCT: return symmetricKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Decrypt operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signAsync(algorithm, digest, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signAsync(algorithm, digest, context, key); case OCT: return symmetricKeyCryptographyClient.signAsync(algorithm, digest, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Sign operaiton is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case OCT: return symmetricKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Verify operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case EC: case EC_HSM: return ecKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case OCT: return symmetricKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", this.key.kty().toString()))); } } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case OCT: return symmetricKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signDataAsync(algorithm, data, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signDataAsync(algorithm, data, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { if (operations.contains(keyOperation)) { return true; } return false; } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if(key == null) { try { this.key = getKey().block().value().keyMaterial(); keyAvailableLocally = this.key.isValid(); } catch (HttpResponseException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: private JsonWebKey key; private final CryptographyService service; private final CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); if (!key.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (key.keyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (key.kty() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if (!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } switch (key.kty()) { case RSA: case RSA_HSM: localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKeyWithResponse() { return withContext(context -> getKeyWithResponse(context)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing the requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Key> getKey() { return getKeyWithResponse().flatMap(FluxUtil::toMono); } Mono<Response<Key>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing permission/not supported for key with id %s", key.kid()))); } return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.wrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.unwrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign-data} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify-data} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); } private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null) { try { this.key = getKey().block().keyMaterial(); keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } }
Just return the if case statement
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { if (operations.contains(keyOperation)) { return true; } return false; }
if (operations.contains(keyOperation)) {
private boolean checkKeyPermissions(List<KeyOperation> operations, KeyOperation keyOperation) { return operations.contains(keyOperation); }
class CryptographyAsyncClient { private JsonWebKey key; private CryptographyService service; private String version; private EcKeyCryptographyClient ecKeyCryptographyClient; private RsaKeyCryptographyClient rsaKeyCryptographyClient; private CryptographyServiceClient cryptographyServiceClient; private SymmetricKeyCryptographyClient symmetricKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if(!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); ecKeyCryptographyClient = new EcKeyCryptographyClient(cryptographyServiceClient); rsaKeyCryptographyClient = new RsaKeyCryptographyClient(cryptographyServiceClient); symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(cryptographyServiceClient); } private void initializeCryptoClients() { switch(key.kty()){ case RSA: case RSA_HSM: rsaKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: ecKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: symmetricKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKey() { return withContext(context -> getKey(context)); } Mono<Response<Key>> getKey(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is not supported for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); case OCT: return symmetricKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); default: throw new UnsupportedOperationException(String.format("Encrypt Async is not allowed for Key Type: %s", key.kty().toString())); } } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)){ return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } switch(key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); case OCT: return symmetricKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Decrypt operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signAsync(algorithm, digest, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signAsync(algorithm, digest, context, key); case OCT: return symmetricKeyCryptographyClient.signAsync(algorithm, digest, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Sign operaiton is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); case OCT: return symmetricKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Verify operation is not supported for Key Type: %s", key.kty().toString()))); } } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case EC: case EC_HSM: return ecKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); case OCT: return symmetricKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", this.key.kty().toString()))); } } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)){ return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); case OCT: return symmetricKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)){ return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.signDataAsync(algorithm, data, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.signDataAsync(algorithm, data, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm); boolean keyAvailableLocally = ensureValidKeyAvailable(); if(!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)){ return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } switch(this.key.kty()){ case RSA: case RSA_HSM: return rsaKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); case EC: case EC_HSM: return ecKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); default: return Mono.error(new UnsupportedOperationException(String.format("Encrypt Async is not supported for Key Type: %s", key.kty().toString()))); } } private void unpackAndValidateId(String keyId) { if (keyId != null && keyId.length() > 0) { try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); version = (tokens.length >= 4 ? tokens[3] : null); if(Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if(Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { e.printStackTrace(); } } else { throw new IllegalArgumentException("Key Id is invalid"); } } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if(key == null) { try { this.key = getKey().block().value().keyMaterial(); keyAvailableLocally = this.key.isValid(); } catch (HttpResponseException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } }
class CryptographyAsyncClient { static final String KEY_VAULT_SCOPE = "https: private JsonWebKey key; private final CryptographyService service; private final CryptographyServiceClient cryptographyServiceClient; private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param key the JsonWebKey to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(JsonWebKey key, HttpPipeline pipeline) { Objects.requireNonNull(key); if (!key.isValid()) { throw new IllegalArgumentException("Json Web Key is not valid"); } if (key.keyOps() == null) { throw new IllegalArgumentException("Json Web Key's key operations property is not configured"); } if (key.kty() == null) { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = key; service = RestProxy.create(CryptographyService.class, pipeline); if (!Strings.isNullOrEmpty(key.kid())) { unpackAndValidateId(key.kid()); cryptographyServiceClient = new CryptographyServiceClient(key.kid(), service); } else { cryptographyServiceClient = null; } initializeCryptoClients(); } /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests * * @param kid THe Azure Key vault key identifier to use for cryptography operations. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ CryptographyAsyncClient(String kid, HttpPipeline pipeline) { unpackAndValidateId(kid); service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(kid, service); this.key = null; } private void initializeCryptoClients() { if (localKeyCryptographyClient != null) { return; } switch (key.kty()) { case RSA: case RSA_HSM: localKeyCryptographyClient = new RsaKeyCryptographyClient(key, cryptographyServiceClient); break; case EC: case EC_HSM: localKeyCryptographyClient = new EcKeyCryptographyClient(key, cryptographyServiceClient); break; case OCT: localKeyCryptographyClient = new SymmetricKeyCryptographyClient(key, cryptographyServiceClient); break; default: throw new IllegalArgumentException(String.format("The Json Web Key Type: %s is not supported.", key.kty().toString())); } } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.getKeyWithResponse} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing a {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Key>> getKeyWithResponse() { return withContext(context -> getKeyWithResponse(context)); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the configured key in the client. Subscribes to the call asynchronously and prints out the returned key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Mono} containing the requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Key> getKey() { return getKeyWithResponse().flatMap(FluxUtil::toMono); } Mono<Response<Key>> getKeyWithResponse(Context context) { return cryptographyServiceClient.getKey(context); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return withContext(context -> encrypt(algorithm, plaintext, context, null, null)); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for encrypting the specified {@code plaintext}. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link Mono} containing a {@link EncryptResult} whose {@link EncryptResult */ public Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> encrypt(algorithm, plaintext, context, iv, authenticationData)); } Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.encrypt(algorithm, plaintext, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Encrypt Operation is missing permission/not supported for key with id %s", key.kid()))); } return localKeyCryptographyClient.encryptAsync(algorithm, plaintext, iv, authenticationData, context, key); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return withContext(context -> decrypt(algorithm, cipherText, null, null, null, context)); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return A {@link Mono} containing the decrypted blob. */ public Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return withContext(context -> decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context)); } Mono<DecryptResult> decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null."); Objects.requireNonNull(cipherText, "Cipher text content to be decrypted cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.decrypt(algorithm, cipherText, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.DECRYPT)) { return Mono.error(new UnsupportedOperationException(String.format("Decrypt Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.decryptAsync(algorithm, cipherText, iv, authenticationData, authenticationTag, context, key); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest) { return withContext(context -> sign(algorithm, digest, context)); } Mono<SignResult> sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.sign(algorithm, digest, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.signAsync(algorithm, digest, context, key); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return A {@link Mono} containing a {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return withContext(context -> verify(algorithm, digest, signature, context)); } Mono<VerifyResult> verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(digest, "Digest content cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verify(algorithm, digest, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", key.kid()))); } return localKeyCryptographyClient.verifyAsync(algorithm, digest, signature, context, key); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.wrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return A {@link Mono} containing a {@link KeyWrapResult} whose {@link KeyWrapResult */ public Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return withContext(context -> wrapKey(algorithm, key, context)); } Mono<KeyWrapResult> wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(key, "Key content to be wrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.wrapKey(algorithm, key, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Wrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.wrapKeyAsync(algorithm, key, context, this.key); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for unwrapping the specified encrypted key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.unwrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return A {@link Mono} containing a the unwrapped key content. */ public Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return withContext(context -> unwrapKey(algorithm, encryptedKey, context)); } Mono<KeyUnwrapResult> unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { Objects.requireNonNull(algorithm, "Key Wrap algorithm cannot be null."); Objects.requireNonNull(encryptedKey, "Encrypted key content to be unwrapped cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.unwrapKey(algorithm, encryptedKey, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.WRAP_KEY)) { return Mono.error(new UnsupportedOperationException(String.format("Unwrap Key Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.unwrapKeyAsync(algorithm, encryptedKey, context, key); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to sign the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.sign-data} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link Mono} containing a {@link SignResult} whose {@link SignResult */ public Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data) { return withContext(context -> signData(algorithm, data, context)); } Mono<SignResult> signData(SignatureAlgorithm algorithm, byte[] data, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data to be signed cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.signData(algorithm, data, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.SIGN)) { return Mono.error(new UnsupportedOperationException(String.format("Sign Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.signDataAsync(algorithm, data, context, key); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.async.cryptographyclient.verify-data} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return withContext(context -> verifyData(algorithm, data, signature, context)); } Mono<VerifyResult> verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { Objects.requireNonNull(algorithm, "Signature algorithm cannot be null."); Objects.requireNonNull(data, "Data cannot be null."); Objects.requireNonNull(signature, "Signature to be verified cannot be null."); boolean keyAvailableLocally = ensureValidKeyAvailable(); if (!keyAvailableLocally) { return cryptographyServiceClient.verifyData(algorithm, data, signature, context); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.VERIFY)) { return Mono.error(new UnsupportedOperationException(String.format("Verify Operation is not allowed for key with id %s", this.key.kid()))); } return localKeyCryptographyClient.verifyDataAsync(algorithm, data, signature, context, key); } private void unpackAndValidateId(String keyId) { if (ImplUtils.isNullOrEmpty(keyId)) { throw new IllegalArgumentException("Key Id is invalid"); } try { URL url = new URL(keyId); String[] tokens = url.getPath().split("/"); String endpoint = url.getProtocol() + ": String keyName = (tokens.length >= 3 ? tokens[2] : null); String version = (tokens.length >= 4 ? tokens[3] : null); if (Strings.isNullOrEmpty(endpoint)) { throw new IllegalArgumentException("Key endpoint in key id is invalid"); } else if (Strings.isNullOrEmpty(keyName)) { throw new IllegalArgumentException("Key name in key id is invalid"); } else if (Strings.isNullOrEmpty(version)) { throw new IllegalArgumentException("Key version in key id is invalid"); } } catch (MalformedURLException e) { throw new IllegalArgumentException("The key identifier is malformed", e); } } private boolean ensureValidKeyAvailable() { boolean keyAvailableLocally = true; if (this.key == null) { try { this.key = getKey().block().keyMaterial(); keyAvailableLocally = this.key.isValid(); initializeCryptoClients(); } catch (HttpResponseException | NullPointerException e) { logger.info("Failed to retrieve key from key vault"); keyAvailableLocally = false; } } return keyAvailableLocally; } CryptographyServiceClient getCryptographyServiceClient() { return cryptographyServiceClient; } }
this can call the method on L290
public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return client.wrapKey(algorithm, key, Context.NONE).block(); }
return client.wrapKey(algorithm, key, Context.NONE).block();
public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) { return wrapKey(algorithm, key, Context.NONE); }
class CryptographyClient { private CryptographyAsyncClient client; /** * Creates a KeyClient that uses {@code pipeline} to service requests * * @param client The {@link CryptographyAsyncClient} that the client routes its request through. */ CryptographyClient(CryptographyAsyncClient client) { this.client = client; } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return The requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Key getKey() { return getKeyWithResponse(Context.NONE).value(); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Key> getKeyWithResponse(Context context) { return client.getKeyWithResponse(context).block(); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return encrypt(algorithm, plaintext, iv, authenticationData, Context.NONE); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return A {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData, Context context) { return client.encrypt(algorithm, plaintext, context, iv, authenticationData).block(); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @return The {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(algorithm, plaintext, null, null, Context.NONE); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, Context.NONE); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { return client.decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context).block(); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(algorithm, cipherText, null, null, null, Context.NONE); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link SignResult} whose {@link SignResult */ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { return client.sign(algorithm, digest, context).block(); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link SignResult} whose {@link SignResult */ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest) { return client.sign(algorithm, digest, Context.NONE).block(); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return verify(algorithm, digest, signature, Context.NONE); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { return client.verify(algorithm, digest, signature, context).block(); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return The {@link KeyWrapResult} whose {@link KeyWrapResult */ /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return The {@link KeyWrapResult} whose {@link KeyWrapResult */ public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { return client.wrapKey(algorithm, key, context).block(); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return The unwrapped key content. */ public KeyUnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return unwrapKey(algorithm, encryptedKey, Context.NONE); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @return The unwrapped key content. */ public KeyUnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { return client.unwrapKey(algorithm, encryptedKey, context).block(); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link SignResult} whose {@link SignResult */ public SignResult signData(SignatureAlgorithm algorithm, byte[] data) { return signData(algorithm, data, Context.NONE); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for signing. * @return A {@link SignResult} whose {@link SignResult */ public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { return client.signData(algorithm, data, context).block(); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return verifyData(algorithm, data, signature, Context.NONE); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { return client.verifyData(algorithm, data, signature, context).block(); } CryptographyServiceClient getServiceClient() { return client.getCryptographyServiceClient(); } }
class CryptographyClient { private final CryptographyAsyncClient client; /** * Creates a KeyClient that uses {@code pipeline} to service requests * * @param client The {@link CryptographyAsyncClient} that the client routes its request through. */ CryptographyClient(CryptographyAsyncClient client) { this.client = client; } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the key configured in the client. Prints out the returned key details.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKey} * * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return The requested {@link Key key}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Key getKey() { return getKeyWithResponse(Context.NONE).value(); } /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires the {@code keys/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets the key configured in the client. Prints out the returned key details.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.getKeyWithResponse * * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException when the configured key doesn't exist in the key vault. * @return A {@link Response} whose {@link Response */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<Key> getKeyWithResponse(Context context) { return client.getKeyWithResponse(context).block(); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Prints out the encrypted content details.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return encrypt(algorithm, plaintext, iv, authenticationData, Context.NONE); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @param iv The initialization vector * @param authenticationData The authentication data * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return A {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData, Context context) { return client.encrypt(algorithm, plaintext, context, iv, authenticationData).block(); } /** * Encrypts an arbitrary sequence of bytes using the configured key. Note that the encrypt operation only supports a * single block of data, the size of which is dependent on the target key and the encryption algorithm to be used. The encrypt * operation is supported for both symmetric keys and asymmetric keys. In case of asymmetric keys public portion of the key is used * for encryption. This operation requires the keys/encrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Encrypts the content. Subscribes to the call asynchronously and prints out the encrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.encrypt * * @param algorithm The algorithm to be used for encryption. * @param plaintext The content to be encrypted. * @throws ResourceNotFoundException if the key cannot be found for encryption. * @throws NullPointerException if {@code algorithm} or {@code plainText} is null. * @return The {@link EncryptResult} whose {@link EncryptResult */ public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext) { return encrypt(algorithm, plaintext, null, null, Context.NONE); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag) { return decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, Context.NONE); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @param iv The initialization vector. * @param authenticationData The authentication data. * @param authenticationTag The authentication tag. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context) { return client.decrypt(algorithm, cipherText, iv, authenticationData, authenticationTag, context).block(); } /** * Decrypts a single block of encrypted data using the configured key and specified algorithm. Note that only a single block of data may be * decrypted, the size of this block is dependent on the target key and the algorithm to be used. The decrypt operation * is supported for both asymmetric and symmetric keys. This operation requires the keys/decrypt permission. * * <p>The {@link EncryptionAlgorithm encryption algorithm} indicates the type of algorithm to use for decrypting the specified encrypted content. Possible values * for assymetric keys include: {@link EncryptionAlgorithm * Possible values for symmetric keys include: {@link EncryptionAlgorithm * {@link EncryptionAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Decrypts the encrypted content. Subscribes to the call asynchronously and prints out the decrypted content details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.decrypt * * @param algorithm The algorithm to be used for decryption. * @param cipherText The content to be decrypted. * @throws ResourceNotFoundException if the key cannot be found for decryption. * @throws NullPointerException if {@code algorithm} or {@code cipherText} is null. * @return The decrypted blob. */ public DecryptResult decrypt(EncryptionAlgorithm algorithm, byte[] cipherText) { return decrypt(algorithm, cipherText, null, null, null, Context.NONE); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.sign-Context} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link SignResult} whose {@link SignResult */ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest, Context context) { return client.sign(algorithm, digest, context).block(); } /** * Creates a signature from a digest using the configured key. The sign operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Sings the digest. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.sign} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code digest} is null. * @return A {@link SignResult} whose {@link SignResult */ public SignResult sign(SignatureAlgorithm algorithm, byte[] digest) { return client.sign(algorithm, digest, Context.NONE).block(); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.verify} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature was created. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature) { return verify(algorithm, digest, signature, Context.NONE); } /** * Verifies a signature using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the specified digest. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.verify-Context} * * @param algorithm The algorithm to use for signing. * @param digest The content from which signature is to be created. * @param signature The signature to be verified. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code digest} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verify(SignatureAlgorithm algorithm, byte[] digest, byte[] signature, Context context) { return client.verify(algorithm, digest, signature, context).block(); } /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.wrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return The {@link KeyWrapResult} whose {@link KeyWrapResult */ /** * Wraps a symmetric key using the configured key. The wrap operation supports wrapping a symmetric key with both * symmetric and asymmetric keys. This operation requires the keys/wrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values include: * {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Wraps the key content. Subscribes to the call asynchronously and prints out the wrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.wrap-key-Context} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param key The key content to be wrapped * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code key} is null. * @return The {@link KeyWrapResult} whose {@link KeyWrapResult */ public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key, Context context) { return client.wrapKey(algorithm, key, context).block(); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.unwrap-key} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return The unwrapped key content. */ public KeyUnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey) { return unwrapKey(algorithm, encryptedKey, Context.NONE); } /** * Unwraps a symmetric key using the configured key that was initially used for wrapping that key. This operation is the reverse of the wrap operation. * The unwrap operation supports asymmetric and symmetric keys to unwrap. This operation requires the keys/unwrapKey permission. * * <p>The {@link KeyWrapAlgorithm wrap algorithm} indicates the type of algorithm to use for wrapping the specified key content. Possible values for asymmetric keys include: * {@link KeyWrapAlgorithm * Possible values for symmetric keys include: {@link KeyWrapAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Unwraps the key content. Subscribes to the call asynchronously and prints out the unwrapped key details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.unwrap-key-Context} * * @param algorithm The encryption algorithm to use for wrapping the key. * @param encryptedKey The encrypted key content to unwrap. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for wrap operation. * @throws NullPointerException if {@code algorithm} or {@code encryptedKey} is null. * @return The unwrapped key content. */ public KeyUnwrapResult unwrapKey(KeyWrapAlgorithm algorithm, byte[] encryptedKey, Context context) { return client.unwrapKey(algorithm, encryptedKey, context).block(); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.sign-data} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link SignResult} whose {@link SignResult */ public SignResult signData(SignatureAlgorithm algorithm, byte[] data) { return signData(algorithm, data, Context.NONE); } /** * Creates a signature from the raw data using the configured key. The sign data operation supports both asymmetric and * symmetric keys. This operation requires the keys/sign permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to create the signature from the digest. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Signs the raw data. Subscribes to the call asynchronously and prints out the signature details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.sign-data-Context} * * @param algorithm The algorithm to use for signing. * @param data The content from which signature is to be created. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for signing. * @throws NullPointerException if {@code algorithm} or {@code data} is null. * @return A {@link SignResult} whose {@link SignResult */ public SignResult signData(SignatureAlgorithm algorithm, byte[] data, Context context) { return client.signData(algorithm, data, context).block(); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.verify-data} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature) { return verifyData(algorithm, data, signature, Context.NONE); } /** * Verifies a signature against the raw data using the configured key. The verify operation supports both symmetric keys and asymmetric keys. * In case of asymmetric keys public portion of the key is used to verify the signature . This operation requires the keys/verify permission. * * <p>The {@link SignatureAlgorithm signature algorithm} indicates the type of algorithm to use to verify the signature. Possible values include: * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * {@link SignatureAlgorithm * * <p><strong>Code Samples</strong></p> * <p>Verifies the signature against the raw data. Subscribes to the call asynchronously and prints out the verification details when a response has been received.</p> * {@codesnippet com.azure.security.keyvault.keys.cryptography.cryptographyclient.verify-data-Context} * * @param algorithm The algorithm to use for signing. * @param data The raw content against which signature is to be verified. * @param signature The signature to be verified. * @param context Additional context that is passed through the Http pipeline during the service call. * @throws ResourceNotFoundException if the key cannot be found for verifying. * @throws NullPointerException if {@code algorithm}, {@code data} or {@code signature} is null. * @return The {@link Boolean} indicating the signature verification result. */ public VerifyResult verifyData(SignatureAlgorithm algorithm, byte[] data, byte[] signature, Context context) { return client.verifyData(algorithm, data, signature, context).block(); } CryptographyServiceClient getServiceClient() { return client.getCryptographyServiceClient(); } }
blob name is also optionally set in endpoint so it could have been null there.
private AzureBlobStorageImpl constructImpl() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); /* Implicit and explicit root container access are functionally equivalent, but explicit references are easier to read and debug. */ if (ImplUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } checkValidEncryptionParameters(); HttpPipeline pipeline = super.getPipeline(); if (pipeline == null) { pipeline = buildPipeline(); } return new AzureBlobStorageBuilder() .url(String.format("%s/%s/%s", endpoint, containerName, blobName)) .pipeline(pipeline) .build(); }
Objects.requireNonNull(blobName, "'blobName' cannot be null.");
private AzureBlobStorageImpl constructImpl() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); /* Implicit and explicit root container access are functionally equivalent, but explicit references are easier to read and debug. */ if (ImplUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } checkValidEncryptionParameters(); HttpPipeline pipeline = super.getPipeline(); if (pipeline == null) { pipeline = buildPipeline(); } return new AzureBlobStorageBuilder() .url(String.format("%s/%s/%s", endpoint, containerName, blobName)) .pipeline(pipeline) .build(); }
class EncryptedBlobClientBuilder extends BaseBlobClientBuilder<EncryptedBlobClientBuilder> { private final ClientLogger logger = new ClientLogger(EncryptedBlobClientBuilder.class); private String containerName; private String blobName; private String snapshot; private AsyncKeyEncryptionKey keyWrapper; private AsyncKeyEncryptionKeyResolver keyResolver; private KeyWrapAlgorithm keyWrapAlgorithm; /** * Creates a new instance of the EncryptedBlobClientBuilder */ public EncryptedBlobClientBuilder() { } /** * Creates an {@code EncryptedBlockBlobAsyncClient} from a {@code BlockBlobAsyncClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlockBlobAsyncClient * * @param client The client to convert. * @return The encrypted client. */ public EncryptedBlockBlobAsyncClient buildEncryptedBlockBlobAsyncClient(BlockBlobAsyncClient client) { checkValidEncryptionParameters(); AzureBlobStorageImpl impl = new AzureBlobStorageBuilder() .url(client.getBlobUrl()) .pipeline(addDecryptionPolicy(client.getHttpPipeline(), client.getHttpPipeline().getHttpClient())) .build(); return new EncryptedBlockBlobAsyncClient(impl, client.getSnapshotId(), client.getAccountName(), this.keyWrapper, this.keyWrapAlgorithm); } /** * Creates an {@code EncryptedBlockBlobClient} from a {@code BlockBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlockBlobClient * * @param client The client to convert. * @return The encrypted client. */ public EncryptedBlockBlobClient buildEncryptedBlockBlobClient(BlockBlobClient client) { checkValidEncryptionParameters(); AzureBlobStorageImpl impl = new AzureBlobStorageBuilder() .url(client.getBlobUrl()) .pipeline(addDecryptionPolicy(client.getHttpPipeline(), client.getHttpPipeline().getHttpClient())) .build(); return new EncryptedBlockBlobClient(new EncryptedBlockBlobAsyncClient(impl, client.getSnapshotId(), client.getAccountName(), this.keyWrapper, this.keyWrapAlgorithm)); } /** * Creates a {@link EncryptedBlockBlobClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlockBlobAsyncClient} * * @return a {@link EncryptedBlockBlobClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. */ public EncryptedBlockBlobClient buildEncryptedBlockBlobClient() { return new EncryptedBlockBlobClient(buildEncryptedBlockBlobAsyncClient()); } /** * Creates a {@link EncryptedBlockBlobAsyncClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlockBlobClient} * * @return a {@link EncryptedBlockBlobAsyncClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. */ public EncryptedBlockBlobAsyncClient buildEncryptedBlockBlobAsyncClient() { return new EncryptedBlockBlobAsyncClient(constructImpl(), snapshot, accountName, keyWrapper, keyWrapAlgorithm); } /** * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name) * @param endpoint URL of the service * @return the updated BlobClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public EncryptedBlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobUrlParts parts = BlobUrlParts.parse(url); this.accountName = parts.getAccountName(); this.endpoint = parts.getScheme() + ": this.containerName = parts.getBlobContainerName(); this.blobName = parts.getBlobName(); this.snapshot = parts.getSnapshot(); String sasToken = parts.getSasQueryParameters().encode(); if (ImplUtils.isNullOrEmpty(sasToken)) { super.sasToken(sasToken); } } catch (MalformedURLException ex) { throw logger.logExceptionAsError( new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.")); } return this; } @Override protected void addOptionalEncryptionPolicy(List<HttpPipelinePolicy> policies) { BlobDecryptionPolicy decryptionPolicy = new BlobDecryptionPolicy(keyWrapper, keyResolver); policies.add(decryptionPolicy); } /** * Sets the name of the container this client is connecting to. * @param containerName the name of the container * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder containerName(String containerName) { this.containerName = containerName; return this; } /** * Sets the name of the blob this client is connecting to. * * @param blobName the name of the blob * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code blobName} is {@code null} */ public EncryptedBlobClientBuilder blobName(String blobName) { this.blobName = Objects.requireNonNull(blobName); return this; } /** * Sets the snapshot of the blob this client is connecting to. * * @param snapshot the snapshot identifier for the blob * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Sets the customer provided key for a Storage Builder. This will not work for an Encrypted Client * since they are not compatible functions. * * @param key The customer provided key * @return the updated EncryptedBlobClientBuilder object * @throws UnsupportedOperationException Since customer provided key and client side encryption * are different functions */ @Override public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey key) { throw logger.logExceptionAsError(new UnsupportedOperationException("Customer Provided Key " + "and Encryption are not compatible")); } /** * Sets the encryption key parameters for the client * * @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key * @param keyWrapAlgorithm The {@link KeyWrapAlgorithm} used to wrap the key. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, KeyWrapAlgorithm keyWrapAlgorithm) { this.keyWrapper = key; this.keyWrapAlgorithm = keyWrapAlgorithm; return this; } /** * Sets the encryption parameters for this client * * @param keyResolver The key resolver used to select the correct key for decrypting existing blobs. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } private void checkValidEncryptionParameters() { if (this.keyWrapper == null && this.keyResolver == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null")); } if (this.keyWrapper != null && this.keyWrapAlgorithm == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Wrap Algorithm must be specified with " + "the Key.")); } } /** * Gets the {@link UserAgentPolicy user agent policy} that is used to set the User-Agent header for each request. * * @return the {@code UserAgentPolicy} that will be used in the {@link HttpPipeline}. */ protected final UserAgentPolicy getUserAgentPolicy() { return new UserAgentPolicy(BlobCryptographyConfiguration.NAME, BlobCryptographyConfiguration.VERSION, super.getConfiguration()); } @Override protected Class<EncryptedBlobClientBuilder> getClazz() { return EncryptedBlobClientBuilder.class; } private HttpPipeline addDecryptionPolicy(HttpPipeline originalPipeline, HttpClient client) { HttpPipelinePolicy[] policies = new HttpPipelinePolicy[originalPipeline.getPolicyCount() + 1]; policies[0] = new BlobDecryptionPolicy(keyWrapper, keyResolver); for (int i = 0; i < originalPipeline.getPolicyCount(); i++) { policies[i + 1] = originalPipeline.getPolicy(i); } return new HttpPipelineBuilder() .httpClient(client) .policies(policies) .build(); } }
class EncryptedBlobClientBuilder extends BaseBlobClientBuilder<EncryptedBlobClientBuilder> { private final ClientLogger logger = new ClientLogger(EncryptedBlobClientBuilder.class); private String containerName; private String blobName; private String snapshot; private AsyncKeyEncryptionKey keyWrapper; private AsyncKeyEncryptionKeyResolver keyResolver; private String keyWrapAlgorithm; /** * Creates a new instance of the EncryptedBlobClientBuilder */ public EncryptedBlobClientBuilder() { } /** * Creates a {@link EncryptedBlobClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobAsyncClient} * * @return a {@link EncryptedBlobClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. */ public EncryptedBlobClient buildEncryptedBlobClient() { return new EncryptedBlobClient(buildEncryptedBlobAsyncClient()); } /** * Creates a {@link EncryptedBlobAsyncClient} based on options set in the Builder. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.cryptography.EncryptedBlobClientBuilder.buildEncryptedBlobClient} * * @return a {@link EncryptedBlobAsyncClient} created from the configurations in this builder. * @throws NullPointerException If {@code endpoint}, {@code containerName}, or {@code blobName} is {@code null}. */ public EncryptedBlobAsyncClient buildEncryptedBlobAsyncClient() { return new EncryptedBlobAsyncClient(constructImpl(), snapshot, accountName, keyWrapper, keyWrapAlgorithm); } /** * Sets the service endpoint, additionally parses it for information (SAS token, container name, blob name) * @param endpoint URL of the service * @return the updated BlobClientBuilder object * @throws IllegalArgumentException If {@code endpoint} is {@code null} or is a malformed URL. */ @Override public EncryptedBlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobUrlParts parts = BlobUrlParts.parse(url); this.accountName = parts.getAccountName(); this.endpoint = parts.getScheme() + ": this.containerName = parts.getBlobContainerName(); this.blobName = parts.getBlobName(); this.snapshot = parts.getSnapshot(); String sasToken = parts.getSasQueryParameters().encode(); if (ImplUtils.isNullOrEmpty(sasToken)) { super.sasToken(sasToken); } } catch (MalformedURLException ex) { throw logger.logExceptionAsError( new IllegalArgumentException("The Azure Storage Blob endpoint url is malformed.")); } return this; } @Override protected void addOptionalEncryptionPolicy(List<HttpPipelinePolicy> policies) { BlobDecryptionPolicy decryptionPolicy = new BlobDecryptionPolicy(keyWrapper, keyResolver); policies.add(decryptionPolicy); } /** * Sets the name of the container this client is connecting to. * @param containerName the name of the container * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder containerName(String containerName) { this.containerName = containerName; return this; } /** * Sets the name of the blob this client is connecting to. * * @param blobName the name of the blob * @return the updated EncryptedBlobClientBuilder object * @throws NullPointerException If {@code blobName} is {@code null} */ public EncryptedBlobClientBuilder blobName(String blobName) { this.blobName = blobName; return this; } /** * Sets the snapshot of the blob this client is connecting to. * * @param snapshot the snapshot identifier for the blob * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder snapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Sets the customer provided key for a Storage Builder. This will not work for an Encrypted Client * since they are not compatible functions. * * @param key The customer provided key * @return the updated EncryptedBlobClientBuilder object * @throws UnsupportedOperationException Since customer provided key and client side encryption * are different functions */ @Override public EncryptedBlobClientBuilder customerProvidedKey(CustomerProvidedKey key) { throw logger.logExceptionAsError(new UnsupportedOperationException("Customer Provided Key " + "and Encryption are not compatible")); } /** * Sets the encryption key parameters for the client * * @param key An object of type {@link AsyncKeyEncryptionKey} that is used to wrap/unwrap the content encryption key * @param keyWrapAlgorithm The {@link String} used to wrap the key. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder key(AsyncKeyEncryptionKey key, String keyWrapAlgorithm) { this.keyWrapper = key; this.keyWrapAlgorithm = keyWrapAlgorithm; return this; } /** * Sets the encryption parameters for this client * * @param keyResolver The key resolver used to select the correct key for decrypting existing blobs. * @return the updated EncryptedBlobClientBuilder object */ public EncryptedBlobClientBuilder keyResolver(AsyncKeyEncryptionKeyResolver keyResolver) { this.keyResolver = keyResolver; return this; } private void checkValidEncryptionParameters() { if (this.keyWrapper == null && this.keyResolver == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Key and KeyResolver cannot both be null")); } if (this.keyWrapper != null && this.keyWrapAlgorithm == null) { throw logger.logExceptionAsError(new IllegalArgumentException("Key Wrap Algorithm must be specified with " + "the Key.")); } } /** * Gets the {@link UserAgentPolicy user agent policy} that is used to set the User-Agent header for each request. * * @return the {@code UserAgentPolicy} that will be used in the {@link HttpPipeline}. */ protected UserAgentPolicy getUserAgentPolicy() { return new UserAgentPolicy(BlobCryptographyConfiguration.NAME, BlobCryptographyConfiguration.VERSION, super.getConfiguration()); } @Override protected Class<EncryptedBlobClientBuilder> getClazz() { return EncryptedBlobClientBuilder.class; } }
This is actually by design. The guidelines state throw a NPE when null is unexpected, but null is a valid value here, it just means that there's nothing to parse. We use that in decrypt blob to indicate skipping the decryption step and go right to trimming. --- In reply to: [332684738](https://github.com/Azure/azure-sdk-for-java/pull/5528#discussion_r332684738) [](ancestors = 332684738)
private EncryptionData getAndValidateEncryptionData(String encryptedDataString) { if (encryptedDataString == null) { throw logger.logExceptionAsError(new IllegalStateException(CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB)); } ObjectMapper objectMapper = new ObjectMapper(); try { EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class); if (encryptionData == null) { throw logger.logExceptionAsError(new IllegalStateException( CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB)); } Objects.requireNonNull(encryptionData.contentEncryptionIV()); Objects.requireNonNull(encryptionData.wrappedContentKey().getEncryptedKey()); if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1.equals(encryptionData.encryptionAgent().getProtocol())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT, "Invalid Encryption Agent. This version of the client library does not understand the " + "Encryption Agent set on the blob message: %s", encryptionData.encryptionAgent()))); } return encryptionData; } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } }
if (encryptedDataString == null) {
private EncryptionData getAndValidateEncryptionData(String encryptedDataString) { if (encryptedDataString == null) { return null; } ObjectMapper objectMapper = new ObjectMapper(); try { EncryptionData encryptionData = objectMapper.readValue(encryptedDataString, EncryptionData.class); if (encryptionData == null) { return encryptionData; } Objects.requireNonNull(encryptionData.getContentEncryptionIV(), "contentEncryptionIV in encryptionData " + "cannot be null"); Objects.requireNonNull(encryptionData.getWrappedContentKey().getEncryptedKey(), "encryptedKey in " + "encryptionData.wrappedContentKey cannot be null"); if (!CryptographyConstants.ENCRYPTION_PROTOCOL_V1 .equals(encryptionData.getEncryptionAgent().getProtocol())) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.ROOT, "Invalid Encryption Agent. This version of the client library does not understand the " + "Encryption Agent set on the blob message: %s", encryptionData.getEncryptionAgent()))); } return encryptionData; } catch (IOException e) { throw logger.logExceptionAsError(new RuntimeException(e)); } }
class with the specified key and resolver. * <p> * If the generated policy is intended to be used for encryption, users are expected to provide a key at the * minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is * intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key * resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on * the key and use it. * * @param key An object of type {@link AsyncKeyEncryptionKey}
class with the specified key and resolver. * <p> * If the generated policy is intended to be used for encryption, users are expected to provide a key at the * minimum. The absence of key will cause an exception to be thrown during encryption. If the generated policy is * intended to be used for decryption, users can provide a keyResolver. The client library will - 1. Invoke the key * resolver if specified to get the key. 2. If resolver is not specified but a key is specified, match the key id on * the key and use it. * * @param key An object of type {@link AsyncKeyEncryptionKey}
You can do an assert fail here instead with a message.
static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertTrue(false); } assertEquals(expected.getKey(), actual.getKey()); assertEquals(expected.getLabel(), actual.getLabel()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getETag(), actual.getETag()); assertEquals(expected.getLastModified(), actual.getLastModified()); assertEquals(expected.getContentType(), actual.getContentType()); final Map<String, String> expectedTags = expected.getTags(); final Map<String, String> actualTags = actual.getTags(); boolean expectedIsNullOrEmpty = ImplUtils.isNullOrEmpty(expectedTags); boolean actualIsNullOrEmpty = ImplUtils.isNullOrEmpty(actualTags); if (expectedIsNullOrEmpty) { assertTrue(actualIsNullOrEmpty); } else { assertEquals(expectedTags, actualTags); assertTrue(true); } }
assertTrue(false);
static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertFalse("One of input settings is null", true); } equals(expected, actual); }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; } }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void setReadOnly(); @Test public abstract void clearReadOnly(); @Test public abstract void setReadOnlyWithConfigurationSetting(); @Test public abstract void clearReadOnlyWithConfigurationSetting(); void lockUnlockRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting lockConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(lockConfiguration); } @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ static boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ static boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; } }
can you do the following instead of this? It's hard to follow... especially with that assertTRue(true) down there. ```java assertEquals(expectedIsNullOrEmpty, actualIsNullOrEmpty); assertEquals(expectedTags, actualTags); ```
static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertTrue(false); } assertEquals(expected.getKey(), actual.getKey()); assertEquals(expected.getLabel(), actual.getLabel()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getETag(), actual.getETag()); assertEquals(expected.getLastModified(), actual.getLastModified()); assertEquals(expected.getContentType(), actual.getContentType()); final Map<String, String> expectedTags = expected.getTags(); final Map<String, String> actualTags = actual.getTags(); boolean expectedIsNullOrEmpty = ImplUtils.isNullOrEmpty(expectedTags); boolean actualIsNullOrEmpty = ImplUtils.isNullOrEmpty(actualTags); if (expectedIsNullOrEmpty) { assertTrue(actualIsNullOrEmpty); } else { assertEquals(expectedTags, actualTags); assertTrue(true); } }
if (expectedIsNullOrEmpty) {
static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertFalse("One of input settings is null", true); } equals(expected, actual); }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; } }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void setReadOnly(); @Test public abstract void clearReadOnly(); @Test public abstract void setReadOnlyWithConfigurationSetting(); @Test public abstract void clearReadOnlyWithConfigurationSetting(); void lockUnlockRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting lockConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(lockConfiguration); } @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ static boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ static boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; } }
Is this going to perform an object reference comparison rather than the contents?
boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; }
return Objects.equals(o1.getTags(), o2.getTags());
boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertTrue(false); } assertEquals(expected.getKey(), actual.getKey()); assertEquals(expected.getLabel(), actual.getLabel()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getETag(), actual.getETag()); assertEquals(expected.getLastModified(), actual.getLastModified()); assertEquals(expected.getContentType(), actual.getContentType()); final Map<String, String> expectedTags = expected.getTags(); final Map<String, String> actualTags = actual.getTags(); boolean expectedIsNullOrEmpty = ImplUtils.isNullOrEmpty(expectedTags); boolean actualIsNullOrEmpty = ImplUtils.isNullOrEmpty(actualTags); if (expectedIsNullOrEmpty) { assertTrue(actualIsNullOrEmpty); } else { assertEquals(expectedTags, actualTags); assertTrue(true); } } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; } }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void setReadOnly(); @Test public abstract void clearReadOnly(); @Test public abstract void setReadOnlyWithConfigurationSetting(); @Test public abstract void clearReadOnlyWithConfigurationSetting(); void lockUnlockRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting lockConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(lockConfiguration); } @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertFalse("One of input settings is null", true); } equals(expected, actual); } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ static /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ static boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; } }
What if the contents aren't ordered in the same way? Will that affect this equality?
boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; }
for (int i = 0; i < size; i++) {
boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertTrue(false); } assertEquals(expected.getKey(), actual.getKey()); assertEquals(expected.getLabel(), actual.getLabel()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getETag(), actual.getETag()); assertEquals(expected.getLastModified(), actual.getLastModified()); assertEquals(expected.getContentType(), actual.getContentType()); final Map<String, String> expectedTags = expected.getTags(); final Map<String, String> actualTags = actual.getTags(); boolean expectedIsNullOrEmpty = ImplUtils.isNullOrEmpty(expectedTags); boolean actualIsNullOrEmpty = ImplUtils.isNullOrEmpty(actualTags); if (expectedIsNullOrEmpty) { assertTrue(actualIsNullOrEmpty); } else { assertEquals(expectedTags, actualTags); assertTrue(true); } } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void setReadOnly(); @Test public abstract void clearReadOnly(); @Test public abstract void setReadOnlyWithConfigurationSetting(); @Test public abstract void clearReadOnlyWithConfigurationSetting(); void lockUnlockRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting lockConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(lockConfiguration); } @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertFalse("One of input settings is null", true); } equals(expected, actual); } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ static boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ static }
It is list, so i think the order matters.
boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; }
for (int i = 0; i < size; i++) {
boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertTrue(false); } assertEquals(expected.getKey(), actual.getKey()); assertEquals(expected.getLabel(), actual.getLabel()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getETag(), actual.getETag()); assertEquals(expected.getLastModified(), actual.getLastModified()); assertEquals(expected.getContentType(), actual.getContentType()); final Map<String, String> expectedTags = expected.getTags(); final Map<String, String> actualTags = actual.getTags(); boolean expectedIsNullOrEmpty = ImplUtils.isNullOrEmpty(expectedTags); boolean actualIsNullOrEmpty = ImplUtils.isNullOrEmpty(actualTags); if (expectedIsNullOrEmpty) { assertTrue(actualIsNullOrEmpty); } else { assertEquals(expectedTags, actualTags); assertTrue(true); } } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void setReadOnly(); @Test public abstract void clearReadOnly(); @Test public abstract void setReadOnlyWithConfigurationSetting(); @Test public abstract void clearReadOnlyWithConfigurationSetting(); void lockUnlockRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting lockConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(lockConfiguration); } @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertFalse("One of input settings is null", true); } equals(expected, actual); } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ static boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ static }
Does the REST API guarantee an order that the configuration settings are returned in?
boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; }
for (int i = 0; i < size; i++) {
boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertTrue(false); } assertEquals(expected.getKey(), actual.getKey()); assertEquals(expected.getLabel(), actual.getLabel()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getETag(), actual.getETag()); assertEquals(expected.getLastModified(), actual.getLastModified()); assertEquals(expected.getContentType(), actual.getContentType()); final Map<String, String> expectedTags = expected.getTags(); final Map<String, String> actualTags = actual.getTags(); boolean expectedIsNullOrEmpty = ImplUtils.isNullOrEmpty(expectedTags); boolean actualIsNullOrEmpty = ImplUtils.isNullOrEmpty(actualTags); if (expectedIsNullOrEmpty) { assertTrue(actualIsNullOrEmpty); } else { assertEquals(expectedTags, actualTags); assertTrue(true); } } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void setReadOnly(); @Test public abstract void clearReadOnly(); @Test public abstract void setReadOnlyWithConfigurationSetting(); @Test public abstract void clearReadOnlyWithConfigurationSetting(); void lockUnlockRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting lockConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(lockConfiguration); } @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertFalse("One of input settings is null", true); } equals(expected, actual); } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ static boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ static }
Not sure what the REST API guaranteed applying to this method. But I can explain what I think of. This equal method is a helper function that could be one of many equals() method users want to define how is equality of two settings. It just could be one of them.
boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; }
for (int i = 0; i < size; i++) {
boolean equalsArray(List<ConfigurationSetting> settings1, List<ConfigurationSetting> settings2) { if (settings1 == settings2) { return true; } if (settings1 == null || settings2 == null) { return false; } if (settings1.size() != settings2.size()) { return false; } final int size = settings1.size(); for (int i = 0; i < size; i++) { if (!equals(settings1.get(i), settings2.get(i))) { return false; } } return true; }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertTrue(false); } assertEquals(expected.getKey(), actual.getKey()); assertEquals(expected.getLabel(), actual.getLabel()); assertEquals(expected.getValue(), actual.getValue()); assertEquals(expected.getETag(), actual.getETag()); assertEquals(expected.getLastModified(), actual.getLastModified()); assertEquals(expected.getContentType(), actual.getContentType()); final Map<String, String> expectedTags = expected.getTags(); final Map<String, String> actualTags = actual.getTags(); boolean expectedIsNullOrEmpty = ImplUtils.isNullOrEmpty(expectedTags); boolean actualIsNullOrEmpty = ImplUtils.isNullOrEmpty(actualTags); if (expectedIsNullOrEmpty) { assertTrue(actualIsNullOrEmpty); } else { assertEquals(expectedTags, actualTags); assertTrue(true); } } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ }
class ConfigurationClientTestBase extends TestBase { private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING"; private static final String KEY_PREFIX = "key"; private static final String LABEL_PREFIX = "label"; private static final int PREFIX_LENGTH = 8; private static final int RESOURCE_LENGTH = 16; private static String connectionString; private final ClientLogger logger = new ClientLogger(ConfigurationClientTestBase.class); String keyPrefix; String labelPrefix; @Rule public TestName testName = new TestName(); @Override public String getTestName() { return testName.getMethodName(); } void beforeTestSetup() { keyPrefix = testResourceNamer.randomName(KEY_PREFIX, PREFIX_LENGTH); labelPrefix = testResourceNamer.randomName(LABEL_PREFIX, PREFIX_LENGTH); } <T> T clientSetup(Function<ConfigurationClientCredentials, T> clientBuilder) { if (ImplUtils.isNullOrEmpty(connectionString)) { connectionString = interceptorManager.isPlaybackMode() ? "Endpoint=http: : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING); } Objects.requireNonNull(connectionString, "AZURE_APPCONFIG_CONNECTION_STRING expected to be set."); T client; try { client = clientBuilder.apply(new ConfigurationClientCredentials(connectionString)); } catch (InvalidKeyException | NoSuchAlgorithmException e) { logger.error("Could not create an configuration client credentials.", e); fail(); client = null; } return Objects.requireNonNull(client); } String getKey() { return testResourceNamer.randomName(keyPrefix, RESOURCE_LENGTH); } String getLabel() { return testResourceNamer.randomName(labelPrefix, RESOURCE_LENGTH); } @Test public abstract void addSetting(); void addSettingRunner(Consumer<ConfigurationSetting> testRunner) { final Map<String, String> tags = new HashMap<>(); tags.put("MyTag", "TagValue"); tags.put("AnotherTag", "AnotherTagValue"); final ConfigurationSetting newConfiguration = new ConfigurationSetting() .setKey(getKey()) .setValue("myNewValue") .setTags(tags) .setContentType("text"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void addSettingEmptyKey(); @Test public abstract void addSettingEmptyValue(); void addSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void addSettingNullKey(); @Test public abstract void addExistingSetting(); void addExistingSettingRunner(Consumer<ConfigurationSetting> testRunner) { final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(getKey()).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel(getLabel())); } @Test public abstract void setSetting(); void setSettingRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting setConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdatedValue"); testRunner.accept(setConfiguration, updateConfiguration); testRunner.accept(setConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingIfEtag(); void setSettingIfEtagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(key).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void setSettingEmptyKey(); @Test public abstract void setSettingEmptyValue(); void setSettingEmptyValueRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); ConfigurationSetting setting = new ConfigurationSetting().setKey(key); ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key + "-1").setValue(""); testRunner.accept(setting); testRunner.accept(setting2); } @Test public abstract void setSettingNullKey(); @Test public abstract void getSetting(); void getSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); testRunner.accept(newConfiguration); testRunner.accept(newConfiguration.setLabel("myLabel")); } @Test public abstract void getSettingNotFound(); @Test public abstract void deleteSetting(); void deleteSettingRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting deletableConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(deletableConfiguration); testRunner.accept(deletableConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNotFound(); @Test public abstract void deleteSettingWithETag(); void deleteSettingWithETagRunner(BiConsumer<ConfigurationSetting, ConfigurationSetting> testRunner) { String key = getKey(); String label = getLabel(); final ConfigurationSetting newConfiguration = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting updateConfiguration = new ConfigurationSetting().setKey(newConfiguration.getKey()).setValue("myUpdateValue"); testRunner.accept(newConfiguration, updateConfiguration); testRunner.accept(newConfiguration.setLabel(label), updateConfiguration.setLabel(label)); } @Test public abstract void deleteSettingNullKey(); @Test public abstract void setReadOnly(); @Test public abstract void clearReadOnly(); @Test public abstract void setReadOnlyWithConfigurationSetting(); @Test public abstract void clearReadOnlyWithConfigurationSetting(); void lockUnlockRunner(Consumer<ConfigurationSetting> testRunner) { String key = getKey(); final ConfigurationSetting lockConfiguration = new ConfigurationSetting().setKey(key).setValue("myValue"); testRunner.accept(lockConfiguration); } @Test public abstract void listWithKeyAndLabel(); @Test public abstract void listWithMultipleKeys(); void listWithMultipleKeysRunner(String key, String key2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); testRunner.apply(setting, setting2).forEach(actual -> expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual)))); assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listWithMultipleLabels(); void listWithMultipleLabelsRunner(String key, String label, String label2, BiFunction<ConfigurationSetting, ConfigurationSetting, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(Arrays.asList(setting, setting2)); for (ConfigurationSetting actual : testRunner.apply(setting, setting2)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listSettingsSelectFields(); void listSettingsSelectFieldsRunner(BiFunction<List<ConfigurationSetting>, SettingSelector, Iterable<ConfigurationSetting>> testRunner) { final String label = "my-first-mylabel"; final String label2 = "my-second-mylabel"; final int numberToCreate = 8; final Map<String, String> tags = new HashMap<>(); tags.put("tag1", "value1"); tags.put("tag2", "value2"); final SettingSelector selector = new SettingSelector() .setLabels("*-second*") .setKeys(keyPrefix + "-fetch-*") .setFields(SettingFields.KEY, SettingFields.ETAG, SettingFields.CONTENT_TYPE, SettingFields.TAGS); List<ConfigurationSetting> settings = new ArrayList<>(numberToCreate); for (int value = 0; value < numberToCreate; value++) { String key = value % 2 == 0 ? keyPrefix + "-" + value : keyPrefix + "-fetch-" + value; String lbl = value / 4 == 0 ? label : label2; settings.add(new ConfigurationSetting().setKey(key).setValue("myValue2").setLabel(lbl).setTags(tags)); } for (ConfigurationSetting setting : testRunner.apply(settings, selector)) { assertNotNull(setting.getETag()); assertNotNull(setting.getKey()); assertTrue(setting.getKey().contains(keyPrefix)); assertNotNull(setting.getTags()); assertEquals(tags.size(), setting.getTags().size()); assertNull(setting.getLastModified()); assertNull(setting.getContentType()); assertNull(setting.getLabel()); } } @Test public abstract void listSettingsAcceptDateTime(); @Test public abstract void listRevisions(); static void validateListRevisions(ConfigurationSetting expected, ConfigurationSetting actual) { assertEquals(expected.getKey(), actual.getKey()); assertNotNull(actual.getETag()); assertNull(actual.getValue()); assertNull(actual.getLastModified()); } @Test public abstract void listRevisionsWithMultipleKeys(); void listRevisionsWithMultipleKeysRunner(String key, String key2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value"); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key2).setValue("value"); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithMultipleLabels(); void listRevisionsWithMultipleLabelsRunner(String key, String label, String label2, Function<List<ConfigurationSetting>, Iterable<ConfigurationSetting>> testRunner) { final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label); final ConfigurationSetting settingUpdate = new ConfigurationSetting().setKey(setting.getKey()).setLabel(setting.getLabel()).setValue("updatedValue"); final ConfigurationSetting setting2 = new ConfigurationSetting().setKey(key).setValue("value").setLabel(label2); final ConfigurationSetting setting2Update = new ConfigurationSetting().setKey(setting2.getKey()).setLabel(setting2.getLabel()).setValue("updatedValue"); final List<ConfigurationSetting> testInput = Arrays.asList(setting, settingUpdate, setting2, setting2Update); final Set<ConfigurationSetting> expectedSelection = new HashSet<>(testInput); for (ConfigurationSetting actual : testRunner.apply(testInput)) { expectedSelection.removeIf(expected -> equals(expected, cleanResponse(expected, actual))); } assertTrue(expectedSelection.isEmpty()); } @Test public abstract void listRevisionsWithRange(); @Test @Ignore("alzimmermsft to investigate") public abstract void listRevisionsInvalidRange(); @Test public abstract void listRevisionsAcceptDateTime(); @Test public abstract void listRevisionsWithPagination(); @Test public abstract void listSettingsWithPagination(); @Test public abstract void listRevisionsWithPaginationAndRepeatStream(); @Test public abstract void listRevisionsWithPaginationAndRepeatIterator(); @Ignore("Getting a configuration setting only when the value has changed is not a common scenario.") @Test public abstract void getSettingWhenValueNotUpdated(); @Ignore("This test exists to clean up resources missed due to 429s.") @Test public abstract void deleteAllSettings(); /** * Helper method to verify that the RestResponse matches what was expected. This method assumes a response status of 200. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned by the service, the body should contain a ConfigurationSetting */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response) { assertConfigurationEquals(expected, response, 200); } /** * Helper method to verify that the RestResponse matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param response RestResponse returned from the service, the body should contain a ConfigurationSetting * @param expectedStatusCode Expected HTTP status code returned by the service */ static void assertConfigurationEquals(ConfigurationSetting expected, Response<ConfigurationSetting> response, final int expectedStatusCode) { assertNotNull(response); assertEquals(expectedStatusCode, response.getStatusCode()); assertConfigurationEquals(expected, response.getValue()); } /** * Helper method to verify that the returned ConfigurationSetting matches what was expected. * * @param expected ConfigurationSetting expected to be returned by the service * @param actual ConfigurationSetting contained in the RestResponse body */ static void assertConfigurationEquals(ConfigurationSetting expected, ConfigurationSetting actual) { if (expected != null && actual != null) { actual = cleanResponse(expected, actual); } else if (expected == actual) { return; } else if (expected == null || actual == null) { assertFalse("One of input settings is null", true); } equals(expected, actual); } /** * The ConfigurationSetting has some fields that are only manipulated by the service, * this helper method cleans those fields on the setting returned by the service so tests are able to pass. * @param expected ConfigurationSetting expected to be returned by the service. * @param actual ConfigurationSetting returned by the service. */ private static ConfigurationSetting cleanResponse(ConfigurationSetting expected, ConfigurationSetting actual) { ConfigurationSetting cleanedActual = new ConfigurationSetting() .setKey(actual.getKey()) .setLabel(actual.getLabel()) .setValue(actual.getValue()) .setTags(actual.getTags()) .setContentType(actual.getContentType()) .setETag(expected.getETag()); try { Field lastModified = ConfigurationSetting.class.getDeclaredField("lastModified"); lastModified.setAccessible(true); lastModified.set(actual, expected.getLastModified()); } catch (NoSuchFieldException | IllegalAccessException ex) { } if (ConfigurationSetting.NO_LABEL.equals(expected.getLabel()) && actual.getLabel() == null) { cleanedActual.setLabel(ConfigurationSetting.NO_LABEL); } return cleanedActual; } static void assertRestException(Runnable exceptionThrower, int expectedStatusCode) { assertRestException(exceptionThrower, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Runnable exceptionThrower, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { try { exceptionThrower.run(); fail(); } catch (Throwable ex) { assertRestException(ex, expectedExceptionType, expectedStatusCode); } } /** * Helper method to verify the error was a HttpResponseException and it has a specific HTTP response code. * * @param exception Expected error thrown during the test * @param expectedStatusCode Expected HTTP status code contained in the error response */ static void assertRestException(Throwable exception, int expectedStatusCode) { assertRestException(exception, HttpResponseException.class, expectedStatusCode); } static void assertRestException(Throwable exception, Class<? extends HttpResponseException> expectedExceptionType, int expectedStatusCode) { assertEquals(expectedExceptionType, exception.getClass()); assertEquals(expectedStatusCode, ((HttpResponseException) exception).getResponse().getStatusCode()); } /** * Helper method to verify that a command throws an IllegalArgumentException. * * @param exceptionThrower Command that should throw the exception */ static <T> void assertRunnableThrowsException(Runnable exceptionThrower, Class<T> exception) { try { exceptionThrower.run(); fail(); } catch (Exception ex) { assertEquals(exception, ex.getClass()); } } /** * Helper method to verify that two configuration setting are equal. Users can defined their equal method. * * @param o1 ConfigurationSetting object 1 * @param o2 ConfigurationSetting object 2 * @return boolean value that defines if two ConfigurationSettings are equal */ static boolean equals(ConfigurationSetting o1, ConfigurationSetting o2) { if (o1 == o2) { return true; } if (!Objects.equals(o1.getKey(), o2.getKey()) || !Objects.equals(o1.getLabel(), o2.getLabel()) || !Objects.equals(o1.getValue(), o2.getValue()) || !Objects.equals(o1.getETag(), o2.getETag()) || !Objects.equals(o1.getLastModified(), o2.getLastModified()) || !Objects.equals(o1.isLocked(), o2.isLocked()) || !Objects.equals(o1.getContentType(), o2.getContentType()) || ImplUtils.isNullOrEmpty(o1.getTags()) != ImplUtils.isNullOrEmpty(o2.getTags())) { return false; } if (!ImplUtils.isNullOrEmpty(o1.getTags())) { return Objects.equals(o1.getTags(), o2.getTags()); } return true; } /** * A helper method to verify that two lists of ConfigurationSetting are equal each other. * * @param settings1 List of ConfigurationSetting * @param settings2 Another List of ConfigurationSetting * @return boolean value that defines if two ConfigurationSetting lists are equal */ static }
Why are we calling `getProperties` here? Just call `getValue` on the call above.
public BlobProperties downloadToFile(String filePath) { downloadToFileWithResponse(filePath, null, null, null, null, false, null, Context.NONE); return getProperties(); }
return getProperties();
public BlobProperties downloadToFile(String filePath) { return downloadToFileWithResponse(filePath, null, null, null, null, false, null, Context.NONE).getValue(); }
class BlobClientBase { private final ClientLogger logger = new ClientLogger(BlobClientBase.class); private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this.client = client; } /** * Creates a new {@link BlobClientBase} linked to the {@code snapshot} of this blob resource. * * @param snapshot the identifier for a specific snapshot of this blob * @return a {@link BlobClientBase} used to interact with the specific snapshot. */ public BlobClientBase getSnapshotClient(String snapshot) { return new BlobClientBase(client.getSnapshotClient(snapshot)); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public URL getBlobUrl() { return client.getBlobUrl(); } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return client.getContainerName(); } /** * Get the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getBlobName} * * @return The name of the blob. */ public final String getBlobName() { return client.getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return client.getHttpPipeline(); } /** * Gets the {@link CpkInfo} used to encrypt this blob's content on the server. * * @return the customer provided key used for encryption. */ public CpkInfo getCustomerProvidedKey() { return client.getCustomerProvidedKey(); } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return this.client.getSnapshotId(); } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return this.client.isSnapshot(); } /** * Opens a blob input stream to download the blob. * <p> * * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws StorageException If a storage service error occurred. */ public final BlobInputStream openInputStream() { return openInputStream(new BlobRange(0), null); } /** * Opens a blob input stream to download the specified range of the blob. * <p> * * @param range {@link BlobRange} * @param accessConditions An {@link BlobAccessConditions} object that represents the access conditions for the * blob. * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws StorageException If a storage service error occurred. */ public final BlobInputStream openInputStream(BlobRange range, BlobAccessConditions accessConditions) { return new BlobInputStream(client, range.getOffset(), range.getCount(), accessConditions); } /** * Gets if the container this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.exists} * * @return true if the container exists, false if it doesn't */ public Boolean exists() { return existsWithResponse(null, Context.NONE).getValue(); } /** * Gets if the container this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return true if the container exists, false if it doesn't */ public Response<Boolean> existsWithResponse(Duration timeout, Context context) { Mono<Response<Boolean>> response = client.existsWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.startCopyFromURL * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @return The copy ID for the long running operation. */ public String startCopyFromURL(URL sourceURL) { return startCopyFromURLWithResponse(sourceURL, null, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.startCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata {@link Metadata} * @param tier {@link AccessTier} for the destination blob. * @param priority {@link RehydratePriority} for rehydrating the blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. */ public Response<String> startCopyFromURLWithResponse(URL sourceURL, Metadata metadata, AccessTier tier, RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Duration timeout, Context context) { Mono<Response<String>> response = client .startCopyFromURLWithResponse(sourceURL, metadata, tier, priority, sourceModifiedAccessConditions, destAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromURL * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. Returned as the {@code copyId} field on the {@link * BlobStartCopyFromURLHeaders} object. */ public void abortCopyFromURL(String copyId) { abortCopyFromURLWithResponse(copyId, null, null, Context.NONE); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. Returned as the {@code copyId} field on the {@link * BlobStartCopyFromURLHeaders} object. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.copyFromURL * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. * @return The copy ID for the long running operation. */ public String copyFromURL(URL copySource) { return copyFromURLWithResponse(copySource, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.copyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata {@link Metadata} * @param tier {@link AccessTier} for the destination blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. */ public Response<String> copyFromURLWithResponse(URL copySource, Metadata metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Duration timeout, Context context) { Mono<Response<String>> response = client .copyFromURLWithResponse(copySource, metadata, tier, sourceModifiedAccessConditions, destAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Downloads the entire blob into an output stream. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.download * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @throws UncheckedIOException If an I/O error occurs. */ public void download(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. */ public Response<Void> downloadWithResponse(OutputStream stream, BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Utility.assertNotNull("stream", stream); Mono<Response<Void>> download = client .downloadWithResponse(range, options, accessConditions, rangeGetContentMD5, context) .flatMapMany(res -> res.getValue() .doOnNext(bf -> { try { stream.write(FluxUtil.byteBufferToArray(bf)); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } }).map(bf -> res)) .last() .map(response -> new SimpleResponse<>(response, null)); return Utility.blockWithOptionalTimeout(download, timeout); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.BlobClient.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @return The properties of the download blob. * @throws UncheckedIOException If an I/O error occurs */ /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra * call, provide the {@link BlobRange} parameter.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.BlobClient.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param blockSize the size of a chunk to download at a time, in bytes * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The response of download blob properties. * @throws UncheckedIOException If an I/O error occurs */ public Response<BlobProperties> downloadToFileWithResponse(String filePath, BlobRange range, Integer blockSize, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Mono<Response<BlobProperties>> download = client.downloadToFileWithResponse(filePath, range, blockSize, options, accessConditions, rangeGetContentMD5, context); return Utility.blockWithOptionalTimeout(download, timeout); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.delete} * * <p>For more information, see the * <a href="https: */ public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The blob properties and metadata. */ public Response<BlobProperties> getPropertiesWithResponse(BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<BlobProperties>> response = client.getPropertiesWithResponse(accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHTTPHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} */ public void setHTTPHeaders(BlobHTTPHeaders headers) { setHTTPHeadersWithResponse(headers, null, null, Context.NONE); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHTTPHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .setHTTPHeadersWithResponse(headers, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} */ public void setMetadata(Metadata metadata) { setMetadataWithResponse(metadata, null, null, Context.NONE); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setMetadataWithResponse(Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setMetadataWithResponse(metadata, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshot} * * <p>For more information, see the * <a href="https: * * @return A response containing a {@link BlobClient} which is used to interact with the created snapshot, use * {@link BlobClient */ public BlobClientBase createSnapshot() { return createSnapshotWithResponse(null, null, null, Context.NONE).getValue(); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing a {@link BlobClient} which is used to interact with the created snapshot, use * {@link BlobClient */ public Response<BlobClientBase> createSnapshotWithResponse(Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<BlobClientBase>> response = client .createSnapshotWithResponse(metadata, accessConditions, context) .map(rb -> new SimpleResponse<>(rb, new BlobClientBase(rb.getValue()))); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ public void setTier(AccessTier tier) { setTierWithResponse(tier, null, null, null, Context.NONE); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTierWithResponse * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @param priority Optional priority to set for re-hydrating blobs. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setTierWithResponse(AccessTier tier, RehydratePriority priority, LeaseAccessConditions leaseAccessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setTierWithResponse(tier, priority, leaseAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undelete} * * <p>For more information, see the * <a href="https: */ public void undelete() { undeleteWithResponse(null, Context.NONE); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Mono<Response<Void>> response = client.undeleteWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ public StorageAccountInfo getAccountInfo() { return getAccountInfoWithResponse(null, Context.NONE).getValue(); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The sku name and account kind. */ public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Mono<Response<StorageAccountInfo>> response = client.getAccountInfoWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange); } /** * Generates a user delegation SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSAS * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); } /** * Generates a SAS token with the specified parameters * * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @return A string that represents the SAS token */ public String generateSAS(OffsetDateTime expiryTime, BlobSASPermission permissions) { return this.client.generateSAS(permissions, expiryTime); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @return A string that represents the SAS token */ public String generateSAS(String identifier) { return this.client.generateSAS(identifier); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.client.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange); } /** * Generates a SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateSAS * * <p>For more information, see the * <a href="https: * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { return this.client.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); } }
class BlobClientBase { private final ClientLogger logger = new ClientLogger(BlobClientBase.class); private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this.client = client; } /** * Creates a new {@link BlobClientBase} linked to the {@code snapshot} of this blob resource. * * @param snapshot the identifier for a specific snapshot of this blob * @return a {@link BlobClientBase} used to interact with the specific snapshot. */ public BlobClientBase getSnapshotClient(String snapshot) { return new BlobClientBase(client.getSnapshotClient(snapshot)); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public URL getBlobUrl() { return client.getBlobUrl(); } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return client.getContainerName(); } /** * Get the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getBlobName} * * @return The name of the blob. */ public final String getBlobName() { return client.getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return client.getHttpPipeline(); } /** * Gets the {@link CpkInfo} used to encrypt this blob's content on the server. * * @return the customer provided key used for encryption. */ public CpkInfo getCustomerProvidedKey() { return client.getCustomerProvidedKey(); } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return this.client.getSnapshotId(); } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return this.client.isSnapshot(); } /** * Opens a blob input stream to download the blob. * <p> * * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws StorageException If a storage service error occurred. */ public final BlobInputStream openInputStream() { return openInputStream(new BlobRange(0), null); } /** * Opens a blob input stream to download the specified range of the blob. * <p> * * @param range {@link BlobRange} * @param accessConditions An {@link BlobAccessConditions} object that represents the access conditions for the * blob. * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws StorageException If a storage service error occurred. */ public final BlobInputStream openInputStream(BlobRange range, BlobAccessConditions accessConditions) { return new BlobInputStream(client, range.getOffset(), range.getCount(), accessConditions); } /** * Gets if the container this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.exists} * * @return true if the container exists, false if it doesn't */ public Boolean exists() { return existsWithResponse(null, Context.NONE).getValue(); } /** * Gets if the container this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return true if the container exists, false if it doesn't */ public Response<Boolean> existsWithResponse(Duration timeout, Context context) { Mono<Response<Boolean>> response = client.existsWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.startCopyFromURL * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @return The copy ID for the long running operation. */ public String startCopyFromURL(URL sourceURL) { return startCopyFromURLWithResponse(sourceURL, null, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.startCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata {@link Metadata} * @param tier {@link AccessTier} for the destination blob. * @param priority {@link RehydratePriority} for rehydrating the blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. */ public Response<String> startCopyFromURLWithResponse(URL sourceURL, Metadata metadata, AccessTier tier, RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Duration timeout, Context context) { Mono<Response<String>> response = client .startCopyFromURLWithResponse(sourceURL, metadata, tier, priority, sourceModifiedAccessConditions, destAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromURL * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. Returned as the {@code copyId} field on the {@link * BlobStartCopyFromURLHeaders} object. */ public void abortCopyFromURL(String copyId) { abortCopyFromURLWithResponse(copyId, null, null, Context.NONE); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. Returned as the {@code copyId} field on the {@link * BlobStartCopyFromURLHeaders} object. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.copyFromURL * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. * @return The copy ID for the long running operation. */ public String copyFromURL(URL copySource) { return copyFromURLWithResponse(copySource, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.copyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata {@link Metadata} * @param tier {@link AccessTier} for the destination blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. */ public Response<String> copyFromURLWithResponse(URL copySource, Metadata metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Duration timeout, Context context) { Mono<Response<String>> response = client .copyFromURLWithResponse(copySource, metadata, tier, sourceModifiedAccessConditions, destAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Downloads the entire blob into an output stream. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.download * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @throws UncheckedIOException If an I/O error occurs. */ public void download(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. */ public Response<Void> downloadWithResponse(OutputStream stream, BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Utility.assertNotNull("stream", stream); Mono<Response<Void>> download = client .downloadWithResponse(range, options, accessConditions, rangeGetContentMD5, context) .flatMapMany(res -> res.getValue() .doOnNext(bf -> { try { stream.write(FluxUtil.byteBufferToArray(bf)); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } }).map(bf -> res)) .last() .map(response -> new SimpleResponse<>(response, null)); return Utility.blockWithOptionalTimeout(download, timeout); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @return The properties of the download blob. * @throws UncheckedIOException If an I/O error occurs */ /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra * call, provide the {@link BlobRange} parameter.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param blockSize the size of a chunk to download at a time, in bytes * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The response of download blob properties. * @throws UncheckedIOException If an I/O error occurs. */ public Response<BlobProperties> downloadToFileWithResponse(String filePath, BlobRange range, Integer blockSize, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Mono<Response<BlobProperties>> download = client.downloadToFileWithResponse(filePath, range, blockSize, options, accessConditions, rangeGetContentMD5, context); return Utility.blockWithOptionalTimeout(download, timeout); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.delete} * * <p>For more information, see the * <a href="https: */ public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The blob properties and metadata. */ public Response<BlobProperties> getPropertiesWithResponse(BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<BlobProperties>> response = client.getPropertiesWithResponse(accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHTTPHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} */ public void setHTTPHeaders(BlobHTTPHeaders headers) { setHTTPHeadersWithResponse(headers, null, null, Context.NONE); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHTTPHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .setHTTPHeadersWithResponse(headers, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} */ public void setMetadata(Metadata metadata) { setMetadataWithResponse(metadata, null, null, Context.NONE); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setMetadataWithResponse(Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setMetadataWithResponse(metadata, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshot} * * <p>For more information, see the * <a href="https: * * @return A response containing a {@link BlobClient} which is used to interact with the created snapshot, use * {@link BlobClient */ public BlobClientBase createSnapshot() { return createSnapshotWithResponse(null, null, null, Context.NONE).getValue(); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing a {@link BlobClient} which is used to interact with the created snapshot, use * {@link BlobClient */ public Response<BlobClientBase> createSnapshotWithResponse(Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<BlobClientBase>> response = client .createSnapshotWithResponse(metadata, accessConditions, context) .map(rb -> new SimpleResponse<>(rb, new BlobClientBase(rb.getValue()))); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ public void setTier(AccessTier tier) { setTierWithResponse(tier, null, null, null, Context.NONE); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTierWithResponse * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @param priority Optional priority to set for re-hydrating blobs. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setTierWithResponse(AccessTier tier, RehydratePriority priority, LeaseAccessConditions leaseAccessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setTierWithResponse(tier, priority, leaseAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undelete} * * <p>For more information, see the * <a href="https: */ public void undelete() { undeleteWithResponse(null, Context.NONE); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Mono<Response<Void>> response = client.undeleteWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ public StorageAccountInfo getAccountInfo() { return getAccountInfoWithResponse(null, Context.NONE).getValue(); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The sku name and account kind. */ public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Mono<Response<StorageAccountInfo>> response = client.getAccountInfoWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange); } /** * Generates a user delegation SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSAS * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); } /** * Generates a SAS token with the specified parameters * * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @return A string that represents the SAS token */ public String generateSAS(OffsetDateTime expiryTime, BlobSASPermission permissions) { return this.client.generateSAS(permissions, expiryTime); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @return A string that represents the SAS token */ public String generateSAS(String identifier) { return this.client.generateSAS(identifier); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.client.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange); } /** * Generates a SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateSAS * * <p>For more information, see the * <a href="https: * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { return this.client.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); } }
Make changes to the method. My mainline merge messed them a little. Only call the maxOverload now.
public BlobProperties downloadToFile(String filePath) { downloadToFileWithResponse(filePath, null, null, null, null, false, null, Context.NONE); return getProperties(); }
return getProperties();
public BlobProperties downloadToFile(String filePath) { return downloadToFileWithResponse(filePath, null, null, null, null, false, null, Context.NONE).getValue(); }
class BlobClientBase { private final ClientLogger logger = new ClientLogger(BlobClientBase.class); private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this.client = client; } /** * Creates a new {@link BlobClientBase} linked to the {@code snapshot} of this blob resource. * * @param snapshot the identifier for a specific snapshot of this blob * @return a {@link BlobClientBase} used to interact with the specific snapshot. */ public BlobClientBase getSnapshotClient(String snapshot) { return new BlobClientBase(client.getSnapshotClient(snapshot)); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public URL getBlobUrl() { return client.getBlobUrl(); } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return client.getContainerName(); } /** * Get the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getBlobName} * * @return The name of the blob. */ public final String getBlobName() { return client.getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return client.getHttpPipeline(); } /** * Gets the {@link CpkInfo} used to encrypt this blob's content on the server. * * @return the customer provided key used for encryption. */ public CpkInfo getCustomerProvidedKey() { return client.getCustomerProvidedKey(); } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return this.client.getSnapshotId(); } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return this.client.isSnapshot(); } /** * Opens a blob input stream to download the blob. * <p> * * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws StorageException If a storage service error occurred. */ public final BlobInputStream openInputStream() { return openInputStream(new BlobRange(0), null); } /** * Opens a blob input stream to download the specified range of the blob. * <p> * * @param range {@link BlobRange} * @param accessConditions An {@link BlobAccessConditions} object that represents the access conditions for the * blob. * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws StorageException If a storage service error occurred. */ public final BlobInputStream openInputStream(BlobRange range, BlobAccessConditions accessConditions) { return new BlobInputStream(client, range.getOffset(), range.getCount(), accessConditions); } /** * Gets if the container this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.exists} * * @return true if the container exists, false if it doesn't */ public Boolean exists() { return existsWithResponse(null, Context.NONE).getValue(); } /** * Gets if the container this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return true if the container exists, false if it doesn't */ public Response<Boolean> existsWithResponse(Duration timeout, Context context) { Mono<Response<Boolean>> response = client.existsWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.startCopyFromURL * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @return The copy ID for the long running operation. */ public String startCopyFromURL(URL sourceURL) { return startCopyFromURLWithResponse(sourceURL, null, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.startCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata {@link Metadata} * @param tier {@link AccessTier} for the destination blob. * @param priority {@link RehydratePriority} for rehydrating the blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. */ public Response<String> startCopyFromURLWithResponse(URL sourceURL, Metadata metadata, AccessTier tier, RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Duration timeout, Context context) { Mono<Response<String>> response = client .startCopyFromURLWithResponse(sourceURL, metadata, tier, priority, sourceModifiedAccessConditions, destAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromURL * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. Returned as the {@code copyId} field on the {@link * BlobStartCopyFromURLHeaders} object. */ public void abortCopyFromURL(String copyId) { abortCopyFromURLWithResponse(copyId, null, null, Context.NONE); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. Returned as the {@code copyId} field on the {@link * BlobStartCopyFromURLHeaders} object. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.copyFromURL * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. * @return The copy ID for the long running operation. */ public String copyFromURL(URL copySource) { return copyFromURLWithResponse(copySource, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.copyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata {@link Metadata} * @param tier {@link AccessTier} for the destination blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. */ public Response<String> copyFromURLWithResponse(URL copySource, Metadata metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Duration timeout, Context context) { Mono<Response<String>> response = client .copyFromURLWithResponse(copySource, metadata, tier, sourceModifiedAccessConditions, destAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Downloads the entire blob into an output stream. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.download * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @throws UncheckedIOException If an I/O error occurs. */ public void download(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. */ public Response<Void> downloadWithResponse(OutputStream stream, BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Utility.assertNotNull("stream", stream); Mono<Response<Void>> download = client .downloadWithResponse(range, options, accessConditions, rangeGetContentMD5, context) .flatMapMany(res -> res.getValue() .doOnNext(bf -> { try { stream.write(FluxUtil.byteBufferToArray(bf)); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } }).map(bf -> res)) .last() .map(response -> new SimpleResponse<>(response, null)); return Utility.blockWithOptionalTimeout(download, timeout); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.BlobClient.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @return The properties of the download blob. * @throws UncheckedIOException If an I/O error occurs */ /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra * call, provide the {@link BlobRange} parameter.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.BlobClient.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param blockSize the size of a chunk to download at a time, in bytes * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The response of download blob properties. * @throws UncheckedIOException If an I/O error occurs */ public Response<BlobProperties> downloadToFileWithResponse(String filePath, BlobRange range, Integer blockSize, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Mono<Response<BlobProperties>> download = client.downloadToFileWithResponse(filePath, range, blockSize, options, accessConditions, rangeGetContentMD5, context); return Utility.blockWithOptionalTimeout(download, timeout); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.delete} * * <p>For more information, see the * <a href="https: */ public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The blob properties and metadata. */ public Response<BlobProperties> getPropertiesWithResponse(BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<BlobProperties>> response = client.getPropertiesWithResponse(accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHTTPHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} */ public void setHTTPHeaders(BlobHTTPHeaders headers) { setHTTPHeadersWithResponse(headers, null, null, Context.NONE); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHTTPHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .setHTTPHeadersWithResponse(headers, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} */ public void setMetadata(Metadata metadata) { setMetadataWithResponse(metadata, null, null, Context.NONE); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setMetadataWithResponse(Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setMetadataWithResponse(metadata, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshot} * * <p>For more information, see the * <a href="https: * * @return A response containing a {@link BlobClient} which is used to interact with the created snapshot, use * {@link BlobClient */ public BlobClientBase createSnapshot() { return createSnapshotWithResponse(null, null, null, Context.NONE).getValue(); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing a {@link BlobClient} which is used to interact with the created snapshot, use * {@link BlobClient */ public Response<BlobClientBase> createSnapshotWithResponse(Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<BlobClientBase>> response = client .createSnapshotWithResponse(metadata, accessConditions, context) .map(rb -> new SimpleResponse<>(rb, new BlobClientBase(rb.getValue()))); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ public void setTier(AccessTier tier) { setTierWithResponse(tier, null, null, null, Context.NONE); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTierWithResponse * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @param priority Optional priority to set for re-hydrating blobs. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setTierWithResponse(AccessTier tier, RehydratePriority priority, LeaseAccessConditions leaseAccessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setTierWithResponse(tier, priority, leaseAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undelete} * * <p>For more information, see the * <a href="https: */ public void undelete() { undeleteWithResponse(null, Context.NONE); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Mono<Response<Void>> response = client.undeleteWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ public StorageAccountInfo getAccountInfo() { return getAccountInfoWithResponse(null, Context.NONE).getValue(); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The sku name and account kind. */ public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Mono<Response<StorageAccountInfo>> response = client.getAccountInfoWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange); } /** * Generates a user delegation SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSAS * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); } /** * Generates a SAS token with the specified parameters * * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @return A string that represents the SAS token */ public String generateSAS(OffsetDateTime expiryTime, BlobSASPermission permissions) { return this.client.generateSAS(permissions, expiryTime); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @return A string that represents the SAS token */ public String generateSAS(String identifier) { return this.client.generateSAS(identifier); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.client.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange); } /** * Generates a SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateSAS * * <p>For more information, see the * <a href="https: * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { return this.client.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); } }
class BlobClientBase { private final ClientLogger logger = new ClientLogger(BlobClientBase.class); private final BlobAsyncClientBase client; /** * Constructor used by {@link SpecializedBlobClientBuilder}. * * @param client the async blob client */ protected BlobClientBase(BlobAsyncClientBase client) { this.client = client; } /** * Creates a new {@link BlobClientBase} linked to the {@code snapshot} of this blob resource. * * @param snapshot the identifier for a specific snapshot of this blob * @return a {@link BlobClientBase} used to interact with the specific snapshot. */ public BlobClientBase getSnapshotClient(String snapshot) { return new BlobClientBase(client.getSnapshotClient(snapshot)); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ public URL getBlobUrl() { return client.getBlobUrl(); } /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return client.getContainerName(); } /** * Get the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getBlobName} * * @return The name of the blob. */ public final String getBlobName() { return client.getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return client.getHttpPipeline(); } /** * Gets the {@link CpkInfo} used to encrypt this blob's content on the server. * * @return the customer provided key used for encryption. */ public CpkInfo getCustomerProvidedKey() { return client.getCustomerProvidedKey(); } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return this.client.getSnapshotId(); } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return this.client.isSnapshot(); } /** * Opens a blob input stream to download the blob. * <p> * * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws StorageException If a storage service error occurred. */ public final BlobInputStream openInputStream() { return openInputStream(new BlobRange(0), null); } /** * Opens a blob input stream to download the specified range of the blob. * <p> * * @param range {@link BlobRange} * @param accessConditions An {@link BlobAccessConditions} object that represents the access conditions for the * blob. * @return An <code>InputStream</code> object that represents the stream to use for reading from the blob. * @throws StorageException If a storage service error occurred. */ public final BlobInputStream openInputStream(BlobRange range, BlobAccessConditions accessConditions) { return new BlobInputStream(client, range.getOffset(), range.getCount(), accessConditions); } /** * Gets if the container this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.exists} * * @return true if the container exists, false if it doesn't */ public Boolean exists() { return existsWithResponse(null, Context.NONE).getValue(); } /** * Gets if the container this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.existsWithResponse * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return true if the container exists, false if it doesn't */ public Response<Boolean> existsWithResponse(Duration timeout, Context context) { Mono<Response<Boolean>> response = client.existsWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.startCopyFromURL * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @return The copy ID for the long running operation. */ public String startCopyFromURL(URL sourceURL) { return startCopyFromURLWithResponse(sourceURL, null, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.startCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata {@link Metadata} * @param tier {@link AccessTier} for the destination blob. * @param priority {@link RehydratePriority} for rehydrating the blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. */ public Response<String> startCopyFromURLWithResponse(URL sourceURL, Metadata metadata, AccessTier tier, RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Duration timeout, Context context) { Mono<Response<String>> response = client .startCopyFromURLWithResponse(sourceURL, metadata, tier, priority, sourceModifiedAccessConditions, destAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromURL * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. Returned as the {@code copyId} field on the {@link * BlobStartCopyFromURLHeaders} object. */ public void abortCopyFromURL(String copyId) { abortCopyFromURLWithResponse(copyId, null, null, Context.NONE); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.abortCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. Returned as the {@code copyId} field on the {@link * BlobStartCopyFromURLHeaders} object. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.copyFromURL * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. * @return The copy ID for the long running operation. */ public String copyFromURL(URL copySource) { return copyFromURLWithResponse(copySource, null, null, null, null, null, Context.NONE).getValue(); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.copyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata {@link Metadata} * @param tier {@link AccessTier} for the destination blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The copy ID for the long running operation. */ public Response<String> copyFromURLWithResponse(URL copySource, Metadata metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Duration timeout, Context context) { Mono<Response<String>> response = client .copyFromURLWithResponse(copySource, metadata, tier, sourceModifiedAccessConditions, destAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Downloads the entire blob into an output stream. Uploading data must be done from the {@link BlockBlobClient}, * {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.download * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @throws UncheckedIOException If an I/O error occurs. */ public void download(OutputStream stream) { downloadWithResponse(stream, null, null, null, false, null, Context.NONE); } /** * Downloads a range of bytes from a blob into an output stream. Uploading data must be done from the {@link * BlockBlobClient}, {@link PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadWithResponse * * <p>For more information, see the * <a href="https: * * @param stream A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. * @throws UncheckedIOException If an I/O error occurs. */ public Response<Void> downloadWithResponse(OutputStream stream, BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Utility.assertNotNull("stream", stream); Mono<Response<Void>> download = client .downloadWithResponse(range, options, accessConditions, rangeGetContentMD5, context) .flatMapMany(res -> res.getValue() .doOnNext(bf -> { try { stream.write(FluxUtil.byteBufferToArray(bf)); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } }).map(bf -> res)) .last() .map(response -> new SimpleResponse<>(response, null)); return Utility.blockWithOptionalTimeout(download, timeout); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @return The properties of the download blob. * @throws UncheckedIOException If an I/O error occurs */ /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra * call, provide the {@link BlobRange} parameter.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param blockSize the size of a chunk to download at a time, in bytes * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The response of download blob properties. * @throws UncheckedIOException If an I/O error occurs. */ public Response<BlobProperties> downloadToFileWithResponse(String filePath, BlobRange range, Integer blockSize, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Duration timeout, Context context) { Mono<Response<BlobProperties>> download = client.downloadToFileWithResponse(filePath, range, blockSize, options, accessConditions, rangeGetContentMD5, context); return Utility.blockWithOptionalTimeout(download, timeout); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.delete} * * <p>For more information, see the * <a href="https: */ public void delete() { deleteWithResponse(null, null, null, Context.NONE); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.deleteWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return The blob properties and metadata. */ public BlobProperties getProperties() { return getPropertiesWithResponse(null, null, Context.NONE).getValue(); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The blob properties and metadata. */ public Response<BlobProperties> getPropertiesWithResponse(BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<BlobProperties>> response = client.getPropertiesWithResponse(accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHTTPHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} */ public void setHTTPHeaders(BlobHTTPHeaders headers) { setHTTPHeadersWithResponse(headers, null, null, Context.NONE); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setHTTPHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client .setHTTPHeadersWithResponse(headers, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} */ public void setMetadata(Metadata metadata) { setMetadataWithResponse(metadata, null, null, Context.NONE); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setMetadataWithResponse(Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setMetadataWithResponse(metadata, accessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshot} * * <p>For more information, see the * <a href="https: * * @return A response containing a {@link BlobClient} which is used to interact with the created snapshot, use * {@link BlobClient */ public BlobClientBase createSnapshot() { return createSnapshotWithResponse(null, null, null, Context.NONE).getValue(); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata {@link Metadata} * @param accessConditions {@link BlobAccessConditions} * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing a {@link BlobClient} which is used to interact with the created snapshot, use * {@link BlobClient */ public Response<BlobClientBase> createSnapshotWithResponse(Metadata metadata, BlobAccessConditions accessConditions, Duration timeout, Context context) { Mono<Response<BlobClientBase>> response = client .createSnapshotWithResponse(metadata, accessConditions, context) .map(rb -> new SimpleResponse<>(rb, new BlobClientBase(rb.getValue()))); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. */ public void setTier(AccessTier tier) { setTierWithResponse(tier, null, null, null, Context.NONE); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.setTierWithResponse * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @param priority Optional priority to set for re-hydrating blobs. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> setTierWithResponse(AccessTier tier, RehydratePriority priority, LeaseAccessConditions leaseAccessConditions, Duration timeout, Context context) { Mono<Response<Void>> response = client.setTierWithResponse(tier, priority, leaseAccessConditions, context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undelete} * * <p>For more information, see the * <a href="https: */ public void undelete() { undeleteWithResponse(null, Context.NONE); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.undeleteWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return A response containing status code and HTTP headers. */ public Response<Void> undeleteWithResponse(Duration timeout, Context context) { Mono<Response<Void>> response = client.undeleteWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return The sku name and account kind. */ public StorageAccountInfo getAccountInfo() { return getAccountInfoWithResponse(null, Context.NONE).getValue(); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.getAccountInfoWithResponse * * <p>For more information, see the * <a href="https: * * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. * @param context Additional context that is passed through the Http pipeline during the service call. * @return The sku name and account kind. */ public Response<StorageAccountInfo> getAccountInfoWithResponse(Duration timeout, Context context) { Mono<Response<StorageAccountInfo>> response = client.getAccountInfoWithResponse(context); return Utility.blockWithOptionalTimeout(response, timeout); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange); } /** * Generates a user delegation SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateUserDelegationSAS * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { return this.client.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); } /** * Generates a SAS token with the specified parameters * * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @return A string that represents the SAS token */ public String generateSAS(OffsetDateTime expiryTime, BlobSASPermission permissions) { return this.client.generateSAS(permissions, expiryTime); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @return A string that represents the SAS token */ public String generateSAS(String identifier) { return this.client.generateSAS(identifier); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.client.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange); } /** * Generates a SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.generateSAS * * <p>For more information, see the * <a href="https: * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { return this.client.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); } }
Why a flatmap here? Can't you just map it?
public Mono<ConfigurationSetting> setReadOnly(String key, String label) { return withContext(context -> setReadOnly( new ConfigurationSetting().setKey(key).setLabel(label), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); }
.flatMap(response -> Mono.justOrEmpty(response.getValue()));
public Mono<ConfigurationSetting> setReadOnly(String key, String label) { return withContext(context -> setReadOnly( new ConfigurationSetting().setKey(key).setLabel(label), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); }
class ConfigurationAsyncClient { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class); private static final String ETAG_ANY = "*"; private static final String RANGE_QUERY = "items=%s"; private final String serviceEndpoint; private final ConfigurationService service; /** * Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}. * Each service call goes through the {@code pipeline}. * * @param serviceEndpoint URL for the App Configuration service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ ConfigurationAsyncClient(URL serviceEndpoint, HttpPipeline pipeline) { this.service = RestProxy.create(ConfigurationService.class, pipeline); this.serviceEndpoint = serviceEndpoint.toString(); } /** * Adds a configuration value in the service if that key does not exist. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param key The key of the configuration setting to add. * @param value The value associated with this configuration setting key. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If a ConfigurationSetting with the same key exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(String key, String value) { return withContext( context -> addSetting(new ConfigurationSetting().setKey(key).setValue(value), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param setting The setting to add to the configuration service. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse * * @param setting The setting to add to the configuration service. * @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs * or the key is an invalid value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)); } Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service .setKey( serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null, getETagValue(ETAG_ANY), context) .doOnRequest(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue())) .onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper) .doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error)); } /** * Creates or updates a configuration value in the service with the given key. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting * * @param key The key of the configuration setting to create or update. * @param value The value of this configuration setting. * @return The {@link ConfigurationSetting} that was created or updated, if the key is an invalid value (which will * also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the setting exists and is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setSetting(String key, String value) { return withContext( context -> setSetting(new ConfigurationSetting().setKey(key).setValue(value), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. * * If {@link ConfigurationSetting * setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting * * @param setting The configuration setting to create or update. * @return The {@link ConfigurationSetting} that was created or updated, if the key is an invalid value, the setting * is locked, or an etag was provided but does not match the service's current etag value (which will also throw * HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If the {@link ConfigurationSetting * wildcard character, and the current configuration value's etag does not match, or the setting exists and is * locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setSetting(ConfigurationSetting setting) { return withContext(context -> setSetting(setting, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. * * If {@link ConfigurationSetting * setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse * * @param setting The configuration setting to create or update. * @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an * invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value * (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If the {@link ConfigurationSetting * wildcard character, and the current configuration value's etag does not match, or the setting exists and is * locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> setSetting(setting, context)); } Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, getETagValue(setting.getETag()), null, context) .doOnRequest(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error)); } /** * Updates an existing configuration value in the service with the given key. The setting must already exist. * * <strong>Code Samples</strong></p> * * <p>Update a setting with the key "prodDBConnection" to have the value "updated_db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.updateSetting * * @param key The key of the configuration setting to update. * @param value The updated value of this configuration setting. * @return The {@link ConfigurationSetting} that was updated, if the configuration value does not exist, is locked, * or the key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If a ConfigurationSetting with the key does not exist or the configuration value is * locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> updateSetting(String key, String value) { return withContext( context -> updateSetting(new ConfigurationSetting().setKey(key).setValue(value), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Updates an existing configuration value in the service. The setting must already exist. Partial updates are not * supported, the entire configuration value is replaced. * * If {@link ConfigurationSetting * matches. * * <p><strong>Code Samples</strong></p> * * <p>Update the setting with the key-label pair "prodDBConnection"-"westUS" to have the value * "updated_db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.updateSetting * * @param setting The setting to add or update in the service. * @return The {@link ConfigurationSetting} that was updated, if the configuration value does not exist, is locked, * or the key is an invalid value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label does not exist, the * setting is locked, or {@link ConfigurationSetting * value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> updateSetting(ConfigurationSetting setting) { return withContext(context -> updateSetting(setting, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Updates an existing configuration value in the service. The setting must already exist. Partial updates are not * supported, the entire configuration value is replaced. * * If {@link ConfigurationSetting * matches. * * <p><strong>Code Samples</strong></p> * * <p>Update the setting with the key-label pair "prodDBConnection"-"westUS" to have the value * "updated_db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.updateSettingWithResponse * * @param setting The setting to add or update in the service. * @return A REST response containing the {@link ConfigurationSetting} that was updated, if the configuration value * does not exist, is locked, or the key is an invalid value (which will also throw HttpResponseException described * below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label does not exist, the * setting is locked, or {@link ConfigurationSetting * value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> updateSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> updateSetting(setting, context)); } Mono<Response<ConfigurationSetting>> updateSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); String etag = setting.getETag() == null ? ETAG_ANY : setting.getETag(); return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, getETagValue(etag), null, context) .doOnRequest(ignoredValue -> logger.info("Updating ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Updated ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to update ConfigurationSetting - {}", setting, error)); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key) { return withContext( context -> getSetting(new ConfigurationSetting().setKey(key), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Attempts to get the ConfigurationSetting given the {@code key}, optional {@code label}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param setting The setting to retrieve based on its key and optional label combination. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist. * @throws HttpResponseException If the {@code} key is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(ConfigurationSetting setting) { return withContext(context -> getSetting(setting, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Attempts to get the ConfigurationSetting given the {@code key}, optional {@code label}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse * * @param setting The setting to retrieve based on its key and optional label combination. * @return A REST response containing the {@link ConfigurationSetting} stored in the service, if the configuration * value does not exist or the key is an invalid value (which will also throw HttpResponseException described * below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist. * @throws HttpResponseException If the {@code} key is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> getSetting(setting, context)); } Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error)); } /** * Deletes the ConfigurationSetting with a matching {@code key}. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting * * @param key The key of the setting to delete. * @return The deleted ConfigurationSetting or {@code null} if it didn't exist. {@code null} is also returned if the * {@code key} is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> deleteSetting(String key) { return withContext( context -> deleteSetting(new ConfigurationSetting().setKey(key), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the {@link ConfigurationSetting} with a matching key, along with the given label and etag. * * If {@link ConfigurationSetting * the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the * ConfigurationSetting yet. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting * * @param setting The ConfigurationSetting to delete. * @return The deleted ConfigurationSetting or {@code null} if didn't exist. {@code null} is also returned if the * {@code key} is an invalid value or {@link ConfigurationSetting * current etag (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws NullPointerException When {@code setting} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws ResourceNotFoundException If {@link ConfigurationSetting * character, and does not match the current etag value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> deleteSetting(ConfigurationSetting setting) { return withContext(context -> deleteSetting(setting, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the {@link ConfigurationSetting} with a matching key, along with the given label and etag. * * If {@link ConfigurationSetting * the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the * ConfigurationSetting yet. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse * * @param setting The ConfigurationSetting to delete. * @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null} * is also returned if the {@code key} is an invalid value or {@link ConfigurationSetting * does not match the current etag (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws NullPointerException When {@code setting} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws ResourceNotFoundException If {@link ConfigurationSetting * character, and does not match the current etag value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> deleteSetting(setting, context)); } Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnRequest(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error)); } /** * Lock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> setReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnRequest(ignoredValue -> logger.info("Setting read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.info("Failed to set read only ConfigurationSetting - {}", setting, error)); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> clearReadOnly(String key, String label) { return withContext(context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> clearReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnRequest(ignoredValue -> logger.info("Clearing read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.info("Failed to clear read only ConfigurationSetting - {}", setting, error)); } /** * Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all * the {@link ConfigurationSetting configuration settings} are fetched with their current values. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all settings that use the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings} * * @param options Optional. Options to filter configuration setting results from the service. * @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux * contains all of the current settings in the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettings(SettingSelector options) { return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(options, context)), continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken))); } PagedFlux<ConfigurationSetting> listSettings(SettingSelector options, Context context) { return new PagedFlux<>(() -> listFirstPageSettings(options, context), continuationToken -> listNextPageSettings(context, continuationToken)); } private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } return service.listKeyValues(serviceEndpoint, continuationToken, context) .doOnRequest(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken, error)); } private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector options, Context context) { if (options == null) { return service.listKeyValues(serviceEndpoint, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings")) .doOnSuccess(response -> logger.info("Listed all ConfigurationSettings")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error)); } String fields = ImplUtils.arrayToString(options.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(options.getKeys(), key -> key); String labels = ImplUtils.arrayToString(options.getLabels(), label -> label); return service.listKeyValues(serviceEndpoint, keys, labels, fields, options.getAcceptDateTime(), context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", options)) .doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", options)) .doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", options, error)); } /** * Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided * in descending order from their {@link ConfigurationSetting * after a period of time. The service maintains change history for up to 7 days. * * If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code options}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions} * * @param selector Optional. Used to filter configuration setting revisions from the service. * @return Revisions of the ConfigurationSetting */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) { return new PagedFlux<>(() -> withContext(context -> listSettingRevisionsFirstPage(selector, context)), continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context))); } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) { Mono<PagedResponse<ConfigurationSetting>> result; if (selector != null) { String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key); String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label); String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null; result = service.listKeyValueRevisions( serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector)) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector)) .doOnError( error -> logger.warning("Failed to list ConfigurationSetting revisions - {}", selector, error)); } else { result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions")) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error)); } return result; } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnRequest(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result; } PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new PagedFlux<>(() -> listSettingRevisionsFirstPage(selector, context), continuationToken -> listSettingRevisionsNextPage(continuationToken, context)); } private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnRequest(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context)); } private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings( PagedResponse<ConfigurationSetting> page, Context context) { return ImplUtils.extractAndFetch(page, context, this::listSettings); } /* * Azure Configuration service requires that the etag value is surrounded in quotation marks. * * @param etag The etag to get the value for. If null is pass in, an empty string is returned. * @return The etag surrounded by quotations. (ex. "etag") */ private static String getETagValue(String etag) { return etag == null ? "" : "\"" + etag + "\""; } /* * Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL. */ private static void validateSetting(ConfigurationSetting setting) { Objects.requireNonNull(setting); if (setting.getKey() == null) { throw new IllegalArgumentException("Parameter 'key' is required and cannot be null."); } } /* * Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since * add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return * this status when the configuration doesn't exist. * * @param throwable Error response from the service. * * @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException, * otherwise the throwable is returned unmodified. */ private static Throwable addSettingExceptionMapper(Throwable throwable) { if (!(throwable instanceof ResourceNotFoundException)) { return throwable; } ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable; return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse()); } }
class ConfigurationAsyncClient { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class); private static final String ETAG_ANY = "*"; private static final String RANGE_QUERY = "items=%s"; private final String serviceEndpoint; private final ConfigurationService service; /** * Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}. * Each service call goes through the {@code pipeline}. * * @param serviceEndpoint URL for the App Configuration service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ ConfigurationAsyncClient(URL serviceEndpoint, HttpPipeline pipeline) { this.service = RestProxy.create(ConfigurationService.class, pipeline); this.serviceEndpoint = serviceEndpoint.toString(); } /** * Adds a configuration value in the service if that key does not exist. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add, or optionally, null if a setting with * label is desired. * @param value The value associated with this configuration setting key. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If a ConfigurationSetting with the same key exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(String key, String label, String value) { return withContext( context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param setting The setting to add to the configuration service. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse * * @param setting The setting to add to the configuration service. * @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs * or the key is an invalid value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)); } Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null, getETagValue(ETAG_ANY), context) .doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue())) .onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper) .doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error)); } /** * Creates or updates a configuration value in the service with the given key. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting * * @param key The key of the configuration setting to create or update. * @param label The label of the configuration setting to create or update, or optionally, null if a setting with * label is desired. * @param value The value of this configuration setting. * @return The {@link ConfigurationSetting} that was created or updated, if the key is an invalid value (which will * also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the setting exists and is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setSetting(String key, String label, String value) { return withContext(context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. * * If {@link ConfigurationSetting * setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse * * @param setting The configuration setting to create or update. * @param ifUnchanged A boolean indicates if using setting's ETag as If-Match's value. * @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an * invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value * (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If the {@link ConfigurationSetting * wildcard character, and the current configuration value's etag does not match, or the setting exists and is * locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> setSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error)); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key, String label) { return getSetting(key, label, null); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional, and the * {@code asOfDateTime} as optional. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @param asOfDateTime Datetime used to retrieve the state of the configuration at that time. If null the current * state will be retrieved asOfDateTime is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) { return withContext(context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime, false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Attempts to get the ConfigurationSetting given the {@code key}, optional {@code label}, optional * {@code asOfDateTime} * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse * * @param setting The setting to retrieve based on its key and optional label combination. * @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with * asOfDateTime is desired. * @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting * If-None-Match header. * @return A REST response containing the {@link ConfigurationSetting} stored in the service, if the configuration * value does not exist or the key is an invalid value (which will also throw HttpResponseException described * below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist. * @throws HttpResponseException If the {@code} key is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean ifChanged) { return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context)); } Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean onlyIfChanged, Context context) { validateSetting(setting); final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null; return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error)); } /** * Deletes the ConfigurationSetting with a matching {@code key}. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting * * @param key The key of the setting to delete. * @param label The label of the configuration setting to delete, or optionally, null if a setting with * label is desired. * @return The deleted ConfigurationSetting or {@code null} if it didn't exist. {@code null} is also returned if the * {@code key} is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> deleteSetting(String key, String label) { return withContext( context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the {@link ConfigurationSetting} with a matching key, along with the given label and etag. * * If {@link ConfigurationSetting * the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the * ConfigurationSetting yet. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse * * @param setting The ConfigurationSetting to delete. * @param ifUnchanged A boolean indicator to decide using setting's ETag value as IF-MATCH value. * If false, set IF_MATCH to {@code null}. Otherwise, set the setting's ETag value to IF_MATCH. * @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null} * is also returned if the {@code key} is an invalid value or {@link ConfigurationSetting * does not match the current etag (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws NullPointerException When {@code setting} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws ResourceNotFoundException If {@link ConfigurationSetting * character, and does not match the current etag value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> deleteSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error)); } /** * Lock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly * * @param key The key of the configuration setting to lock. * @param label The label of the configuration setting to lock, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} that was locked, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was unlocked, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> setReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error)); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> clearReadOnly(String key, String label) { return withContext(context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> clearReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error)); } /** * Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all * the {@link ConfigurationSetting configuration settings} are fetched with their current values. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all settings that use the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings} * * @param options Optional. Options to filter configuration setting results from the service. * @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux * contains all of the current settings in the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettings(SettingSelector options) { return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(options, context)), continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken))); } PagedFlux<ConfigurationSetting> listSettings(SettingSelector options, Context context) { return new PagedFlux<>(() -> listFirstPageSettings(options, context), continuationToken -> listNextPageSettings(context, continuationToken)); } private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } return service.listKeyValues(serviceEndpoint, continuationToken, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken, error)); } private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector options, Context context) { if (options == null) { return service.listKeyValues(serviceEndpoint, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings")) .doOnSuccess(response -> logger.info("Listed all ConfigurationSettings")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error)); } String fields = ImplUtils.arrayToString(options.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(options.getKeys(), key -> key); String labels = ImplUtils.arrayToString(options.getLabels(), label -> label); return service.listKeyValues(serviceEndpoint, keys, labels, fields, options.getAcceptDateTime(), context) .doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", options)) .doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", options)) .doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", options, error)); } /** * Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided * in descending order from their {@link ConfigurationSetting * after a period of time. The service maintains change history for up to 7 days. * * If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code options}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions} * * @param selector Optional. Used to filter configuration setting revisions from the service. * @return Revisions of the ConfigurationSetting */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) { return new PagedFlux<>(() -> withContext(context -> listSettingRevisionsFirstPage(selector, context)), continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context))); } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) { Mono<PagedResponse<ConfigurationSetting>> result; if (selector != null) { String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key); String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label); String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null; result = service.listKeyValueRevisions( serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector)) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector)) .doOnError( error -> logger.warning("Failed to list ConfigurationSetting revisions - {}", selector, error)); } else { result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions")) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error)); } return result; } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result; } PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new PagedFlux<>(() -> listSettingRevisionsFirstPage(selector, context), continuationToken -> listSettingRevisionsNextPage(continuationToken, context)); } private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context)); } private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings( PagedResponse<ConfigurationSetting> page, Context context) { return ImplUtils.extractAndFetch(page, context, this::listSettings); } /* * Azure Configuration service requires that the etag value is surrounded in quotation marks. * * @param etag The etag to get the value for. If null is pass in, an empty string is returned. * @return The etag surrounded by quotations. (ex. "etag") */ private static String getETagValue(String etag) { return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\""; } /* * Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL. */ private static void validateSetting(ConfigurationSetting setting) { Objects.requireNonNull(setting); if (setting.getKey() == null) { throw new IllegalArgumentException("Parameter 'key' is required and cannot be null."); } } /* * Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since * add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return * this status when the configuration doesn't exist. * * @param throwable Error response from the service. * * @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException, * otherwise the throwable is returned unmodified. */ private static Throwable addSettingExceptionMapper(Throwable throwable) { if (!(throwable instanceof ResourceNotFoundException)) { return throwable; } ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable; return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse()); } }
This line break is weird. I'd break it after the format string
public void lockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .setReadOnly(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); }
.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue());
public void lockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient.setReadOnlyWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), Context.NONE).getValue(); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key2, value2)); System.out.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); }
class ConfigurationClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created. */ public ConfigurationClient createAsyncConfigurationClientWithPipeline() { try { String connectionString = getConnectionString(); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .pipeline(pipeline) .endpoint("https: .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); return configurationClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created */ public ConfigurationAsyncClient createAsyncConfigurationClient() { try { String connectionString = getConnectionString(); ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); return configurationAsyncClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created */ public ConfigurationClient createSyncConfigurationClient() { try { String connectionString = getConnectionString(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); return configurationClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for using {@link ConfigurationClient */ public void addSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .addSetting("prodDBConnection", "db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .addSetting( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS").setValue("db_connection")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .addSettingWithResponse( new ConfigurationSetting() .setKey("prodDBConnection").setLabel("westUS").setValue("db_connection"), new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void setSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .setSetting("prodDBConnection", "db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); result = configurationClient.setSetting("prodDBConnection", "updated_db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .setSetting( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS").setValue("db_connection")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); resultSetting = configurationClient .setSetting(new ConfigurationSetting() .setKey("prodDBConnection").setLabel("westUS").setValue("updated_db_connection")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS") .setValue("db_connection"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS") .setValue("updated_db_connection"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void getSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.getSetting("prodDBConnection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .getSetting(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .getSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void updateSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.updateSetting("prodDBConnection", "updated_db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .updateSetting( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS") .setValue("updated_db_connection")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .updateSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS") .setValue("updated_db_connection"), new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void deleteSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .deleteSetting("prodDBConnection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .deleteSetting(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .deleteSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ /** * Generates code sample for using {@link ConfigurationClient */ public void unlockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .setReadOnly(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettings() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); configurationClient.listSettings(settingSelector).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingsContext() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); Context ctx = new Context(key2, value2); configurationClient.listSettings(settingSelector, ctx).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().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(value -> { System.out.printf("Response value is %d %n", value); }); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingRevisionsContext() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); Context ctx = new Context(key2, value2); configurationClient.listSettingRevisions(settingSelector, ctx).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Implementation not provided for this method * * @return {@code null} */ private String getConnectionString() { return null; } }
class ConfigurationClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created. */ public ConfigurationClient createAsyncConfigurationClientWithPipeline() { try { String connectionString = getConnectionString(); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .pipeline(pipeline) .endpoint("https: .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); return configurationClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created */ public ConfigurationAsyncClient createAsyncConfigurationClient() { try { String connectionString = getConnectionString(); ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); return configurationAsyncClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created */ public ConfigurationClient createSyncConfigurationClient() { try { String connectionString = getConnectionString(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); return configurationClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for using {@link ConfigurationClient */ public void addSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .addSetting("prodDBConnection", "db_connection", null); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .addSettingWithResponse( new ConfigurationSetting() .setKey("prodDBConnection").setLabel("westUS").setValue("db_connection"), new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void setSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .setSetting("prodDBConnection", null, "db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); result = configurationClient.setSetting("prodDBConnection", null, "updated_db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient.setSettingWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS").setValue("db_connection"), false, new Context(key2, value2)); final ConfigurationSetting initSetting = responseSetting.getValue(); System.out.printf("Key: %s, Value: %s", initSetting.getKey(), initSetting.getValue()); responseSetting = configurationClient.setSettingWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS").setValue("updated_db_connection"), false, new Context(key2, value2)); final ConfigurationSetting updatedSetting = responseSetting.getValue(); System.out.printf("Key: %s, Value: %s", updatedSetting.getKey(), updatedSetting.getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void getSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting resultNoDateTime = configurationClient.getSetting("prodDBConnection", null); System.out.printf("Key: %s, Value: %s", resultNoDateTime.getKey(), resultNoDateTime.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting result = configurationClient.getSetting("prodDBConnection", null, null); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .getSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void deleteSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .deleteSetting("prodDBConnection", null); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .deleteSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key2, value2)); System.out.printf( "Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ /** * Generates code sample for using {@link ConfigurationClient */ public void unlockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient.setReadOnlyWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), Context.NONE).getValue(); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key2, value2)); System.out.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettings() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); configurationClient.listSettings(settingSelector).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingsContext() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); Context ctx = new Context(key2, value2); configurationClient.listSettings(settingSelector, ctx).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().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(value -> { System.out.printf("Response value is %d %n", value); }); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingRevisionsContext() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); Context ctx = new Context(key2, value2); configurationClient.listSettingRevisions(settingSelector, ctx).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Implementation not provided for this method * * @return {@code null} */ private String getConnectionString() { return null; } }
Same. This line break is odd.
public void unlockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .setReadOnly(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); }
.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue());
public void unlockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient.setReadOnlyWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), Context.NONE).getValue(); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key2, value2)); System.out.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); }
class ConfigurationClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created. */ public ConfigurationClient createAsyncConfigurationClientWithPipeline() { try { String connectionString = getConnectionString(); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .pipeline(pipeline) .endpoint("https: .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); return configurationClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created */ public ConfigurationAsyncClient createAsyncConfigurationClient() { try { String connectionString = getConnectionString(); ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); return configurationAsyncClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created */ public ConfigurationClient createSyncConfigurationClient() { try { String connectionString = getConnectionString(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); return configurationClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for using {@link ConfigurationClient */ public void addSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .addSetting("prodDBConnection", "db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .addSetting( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS").setValue("db_connection")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .addSettingWithResponse( new ConfigurationSetting() .setKey("prodDBConnection").setLabel("westUS").setValue("db_connection"), new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void setSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .setSetting("prodDBConnection", "db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); result = configurationClient.setSetting("prodDBConnection", "updated_db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .setSetting( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS").setValue("db_connection")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); resultSetting = configurationClient .setSetting(new ConfigurationSetting() .setKey("prodDBConnection").setLabel("westUS").setValue("updated_db_connection")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS") .setValue("db_connection"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS") .setValue("updated_db_connection"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void getSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.getSetting("prodDBConnection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .getSetting(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .getSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void updateSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.updateSetting("prodDBConnection", "updated_db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .updateSetting( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS") .setValue("updated_db_connection")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .updateSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS") .setValue("updated_db_connection"), new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void deleteSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .deleteSetting("prodDBConnection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .deleteSetting(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .deleteSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void lockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient .setReadOnly(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS")); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), new Context(key2, value2)); System.out .printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ /** * Generates code sample for using {@link ConfigurationClient */ public void listSettings() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); configurationClient.listSettings(settingSelector).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingsContext() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); Context ctx = new Context(key2, value2); configurationClient.listSettings(settingSelector, ctx).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().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(value -> { System.out.printf("Response value is %d %n", value); }); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingRevisionsContext() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); Context ctx = new Context(key2, value2); configurationClient.listSettingRevisions(settingSelector, ctx).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Implementation not provided for this method * * @return {@code null} */ private String getConnectionString() { return null; } }
class ConfigurationClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created. */ public ConfigurationClient createAsyncConfigurationClientWithPipeline() { try { String connectionString = getConnectionString(); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(/* add policies */) .build(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .pipeline(pipeline) .endpoint("https: .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); return configurationClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created */ public ConfigurationAsyncClient createAsyncConfigurationClient() { try { String connectionString = getConnectionString(); ConfigurationAsyncClient configurationAsyncClient = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); return configurationAsyncClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for creating a {@link ConfigurationClient} * * @return An instance of {@link ConfigurationClient} * @throws IllegalStateException If configuration credentials cannot be created */ public ConfigurationClient createSyncConfigurationClient() { try { String connectionString = getConnectionString(); ConfigurationClient configurationClient = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildClient(); return configurationClient; } catch (GeneralSecurityException ex) { throw new IllegalStateException("Failed to create configuration client credentials", ex); } } /** * Generates code sample for using {@link ConfigurationClient */ public void addSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .addSetting("prodDBConnection", "db_connection", null); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /* Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .addSettingWithResponse( new ConfigurationSetting() .setKey("prodDBConnection").setLabel("westUS").setValue("db_connection"), new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void setSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .setSetting("prodDBConnection", null, "db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); result = configurationClient.setSetting("prodDBConnection", null, "updated_db_connection"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient.setSettingWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS").setValue("db_connection"), false, new Context(key2, value2)); final ConfigurationSetting initSetting = responseSetting.getValue(); System.out.printf("Key: %s, Value: %s", initSetting.getKey(), initSetting.getValue()); responseSetting = configurationClient.setSettingWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS").setValue("updated_db_connection"), false, new Context(key2, value2)); final ConfigurationSetting updatedSetting = responseSetting.getValue(); System.out.printf("Key: %s, Value: %s", updatedSetting.getKey(), updatedSetting.getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void getSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting resultNoDateTime = configurationClient.getSetting("prodDBConnection", null); System.out.printf("Key: %s, Value: %s", resultNoDateTime.getKey(), resultNoDateTime.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting result = configurationClient.getSetting("prodDBConnection", null, null); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseResultSetting = configurationClient .getSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key1, value1)); System.out.printf("Key: %s, Value: %s", responseResultSetting.getValue().getKey(), responseResultSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void deleteSetting() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient .deleteSetting("prodDBConnection", null); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .deleteSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key2, value2)); System.out.printf( "Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ public void lockSettingsCodeSnippet() { ConfigurationClient configurationClient = createSyncConfigurationClient(); ConfigurationSetting result = configurationClient.setReadOnly("prodDBConnection", "westUS"); System.out.printf("Key: %s, Value: %s", result.getKey(), result.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ ConfigurationSetting resultSetting = configurationClient.setReadOnlyWithResponse( new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), Context.NONE).getValue(); System.out.printf("Key: %s, Value: %s", resultSetting.getKey(), resultSetting.getValue()); /** * Generates code sample for using {@link ConfigurationClient */ Response<ConfigurationSetting> responseSetting = configurationClient .setSettingWithResponse(new ConfigurationSetting().setKey("prodDBConnection").setLabel("westUS"), false, new Context(key2, value2)); System.out.printf("Key: %s, Value: %s", responseSetting.getValue().getKey(), responseSetting.getValue().getValue()); } /** * Generates code sample for using {@link ConfigurationClient */ /** * Generates code sample for using {@link ConfigurationClient */ public void listSettings() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); configurationClient.listSettings(settingSelector).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingsContext() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); Context ctx = new Context(key2, value2); configurationClient.listSettings(settingSelector, ctx).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().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(value -> { System.out.printf("Response value is %d %n", value); }); }); } /** * Generates code sample for using {@link ConfigurationClient */ public void listSettingRevisionsContext() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().setKeys("prodDBConnection"); Context ctx = new Context(key2, value2); configurationClient.listSettingRevisions(settingSelector, ctx).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.getKey(), setting.getValue()); }); } /** * Implementation not provided for this method * * @return {@code null} */ private String getConnectionString() { return null; } }
You can use a ternary operator.
protected void afterTest() { logger.info("Cleaning up created key values."); client.listSettings(new SettingSelector().setKeys(keyPrefix + "*")) .flatMap(configurationSetting -> { Mono<Response<ConfigurationSetting>> unlock; if (configurationSetting.isLocked()) { unlock = client.clearReadOnlyWithResponse(configurationSetting); } else { unlock = Mono.empty(); } logger.info("Deleting key:label [{}:{}]. isLocked? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isLocked()); return unlock.then(client.deleteSetting(configurationSetting)); }) .blockLast(); logger.info("Finished cleaning up values."); }
unlock = client.clearReadOnlyWithResponse(configurationSetting);
protected void afterTest() { logger.info("Cleaning up created key values."); client.listSettings(new SettingSelector().setKeys(keyPrefix + "*")) .flatMap(configurationSetting -> { logger.info("Deleting key:label [{}:{}]. isLocked? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isLocked()); Mono<Response<ConfigurationSetting>> unlock = configurationSetting.isLocked() ? client.clearReadOnlyWithResponse(configurationSetting) : Mono.empty(); return unlock.then(client.deleteSettingWithResponse(configurationSetting, false)); }) .blockLast(); logger.info("Finished cleaning up values."); }
class ConfigurationAsyncClientTest extends ConfigurationClientTestBase { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class); private ConfigurationAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); if (interceptorManager.isPlaybackMode()) { client = clientSetup(credentials -> new ConfigurationClientBuilder() .credential(credentials) .httpClient(interceptorManager.getPlaybackClient()) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .buildAsyncClient()); } else { client = clientSetup(credentials -> new ConfigurationClientBuilder() .credential(credentials) .httpClient(new NettyAsyncHttpClientBuilder().wiretap(true).build()) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()) .buildAsyncClient()); } } @Override /** * Tests that a configuration is able to be added, these are differentiate from each other using a key or key-label identifier. */ public void addSetting() { addSettingRunner((expected) -> StepVerifier.create(client.addSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot add a configuration setting when the key is an empty string. */ public void addSettingEmptyKey() { StepVerifier.create(client.addSetting("", "A value")) .verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD)); } /** * Tests that we can add configuration settings when value is not null or an empty string. */ public void addSettingEmptyValue() { addSettingEmptyValueRunner((setting) -> { StepVerifier.create(client.addSetting(setting.getKey(), setting.getValue())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.getSetting(setting.getKey())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); }); } /** * Verifies that an exception is thrown when null key is passed. */ public void addSettingNullKey() { assertRunnableThrowsException(() -> client.addSetting(null, "A Value").block(), IllegalArgumentException.class); assertRunnableThrowsException(() -> client.addSetting(null).block(), NullPointerException.class); } /** * Tests that a configuration cannot be added twice with the same key. This should return a 412 error. */ public void addExistingSetting() { addExistingSettingRunner((expected) -> StepVerifier.create(client.addSetting(expected).then(client.addSetting(expected))) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_PRECON_FAILED))); } /** * Tests that a configuration is able to be added or updated with set. * When the configuration is locked updates cannot happen, this will result in a 409. */ public void setSetting() { setSettingRunner((expected, update) -> StepVerifier.create(client.setSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete()); } /** * Tests that when an etag is passed to set it will only set if the current representation of the setting has the * etag. If the set etag doesn't match anything the update won't happen, this will result in a 412. This will * prevent set from doing an add as well. */ public void setSettingIfEtag() { setSettingIfEtagRunner((initial, update) -> { StepVerifier.create(client.setSetting(initial.setETag("badEtag"))) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED)); final String etag = client.addSetting(initial).block().getETag(); StepVerifier.create(client.setSetting(update.setETag(etag))) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); StepVerifier.create(client.setSetting(initial)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED)); StepVerifier.create(client.getSetting(update)) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); }); } /** * Tests that we cannot set a configuration setting when the key is an empty string. */ public void setSettingEmptyKey() { StepVerifier.create(client.setSetting("", "A value")) .verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD)); } /** * Tests that we can set configuration settings when value is not null or an empty string. * Value is not a required property. */ public void setSettingEmptyValue() { setSettingEmptyValueRunner((setting) -> { StepVerifier.create(client.setSetting(setting.getKey(), setting.getValue())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.getSetting(setting.getKey())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); }); } /** * Verifies that an exception is thrown when null key is passed. */ public void setSettingNullKey() { assertRunnableThrowsException(() -> client.setSetting(null, "A Value").block(), IllegalArgumentException.class); assertRunnableThrowsException(() -> client.setSetting(null).block(), NullPointerException.class); } /** * Tests that update cannot be done to a non-existent configuration, this will result in a 412. * Unlike set update isn't able to create the configuration. */ public void updateNoExistingSetting() { updateNoExistingSettingRunner((expected) -> StepVerifier.create(client.updateSetting(expected)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED))); } /** * Tests that a configuration is able to be updated when it exists. * When the configuration is locked updates cannot happen, this will result in a 409. */ public void updateSetting() { updateSettingRunner((initial, update) -> StepVerifier.create(client.addSetting(initial)) .assertNext(response -> assertConfigurationEquals(initial, response)) .verifyComplete()); } /** * Tests that a configuration is able to be updated when it exists with the convenience overload. * When the configuration is locked updates cannot happen, this will result in a 409. */ public void updateSettingOverload() { updateSettingOverloadRunner((original, updated) -> { StepVerifier.create(client.addSetting(original.getKey(), original.getValue())) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.updateSetting(updated.getKey(), updated.getValue())) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); }); } /** * Verifies that an exception is thrown when null key is passed. */ public void updateSettingNullKey() { assertRunnableThrowsException(() -> client.updateSetting(null, "A Value").block(), IllegalArgumentException.class); assertRunnableThrowsException(() -> client.updateSetting(null).block(), NullPointerException.class); } /** * Tests that when an etag is passed to update it will only update if the current representation of the setting has the etag. * If the update etag doesn't match anything the update won't happen, this will result in a 412. */ public void updateSettingIfEtag() { updateSettingIfEtagRunner(settings -> { final ConfigurationSetting initial = settings.get(0); final ConfigurationSetting update = settings.get(1); final ConfigurationSetting last = settings.get(2); final String initialEtag = client.addSetting(initial).block().getETag(); final String updateEtag = client.updateSetting(update).block().getETag(); StepVerifier.create(client.updateSetting(new ConfigurationSetting().setKey(last.getKey()).setLabel(last.getLabel()).setValue(last.getValue()).setETag(initialEtag))) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED)); StepVerifier.create(client.getSetting(update)) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); StepVerifier.create(client.updateSetting(new ConfigurationSetting().setKey(last.getKey()).setLabel(last.getLabel()).setValue(last.getValue()).setETag(updateEtag))) .assertNext(response -> assertConfigurationEquals(last, response)) .verifyComplete(); StepVerifier.create(client.getSetting(last)) .assertNext(response -> assertConfigurationEquals(last, response)) .verifyComplete(); StepVerifier.create(client.updateSetting(new ConfigurationSetting().setKey(initial.getKey()).setLabel(initial.getLabel()).setValue(initial.getValue()).setETag(updateEtag))) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED)); }); } /** * Tests that a configuration is able to be retrieved when it exists, whether or not it is locked. */ public void getSetting() { getSettingRunner((expected) -> StepVerifier.create(client.addSetting(expected).then(client.getSetting(expected))) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete()); } /** * Tests that attempting to retrieve a non-existent configuration doesn't work, this will result in a 404. */ public void getSettingNotFound() { final String key = getKey(); final ConfigurationSetting neverRetrievedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverRetreivedValue"); final ConfigurationSetting nonExistentLabel = new ConfigurationSetting().setKey(key).setLabel("myNonExistentLabel"); StepVerifier.create(client.addSetting(neverRetrievedConfiguration)) .assertNext(response -> assertConfigurationEquals(neverRetrievedConfiguration, response)) .verifyComplete(); StepVerifier.create(client.getSetting("myNonExistentKey")) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); StepVerifier.create(client.getSetting(nonExistentLabel)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that configurations are able to be deleted when they exist. * After the configuration has been deleted attempting to get it will result in a 404, the same as if the * configuration never existed. */ public void deleteSetting() { deleteSettingRunner((expected) -> { StepVerifier.create(client.addSetting(expected).then(client.getSetting(expected))) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.deleteSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.getSetting(expected)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); }); } /** * Tests that attempting to delete a non-existent configuration will return a 204. */ public void deleteSettingNotFound() { final String key = getKey(); final ConfigurationSetting neverDeletedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverDeletedValue"); StepVerifier.create(client.addSetting(neverDeletedConfiguration)) .assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(new ConfigurationSetting().setKey("myNonExistentKey"))) .assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(new ConfigurationSetting().setKey(neverDeletedConfiguration.getKey()).setLabel("myNonExistentLabel"))) .assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT)) .verifyComplete(); StepVerifier.create(client.getSetting(neverDeletedConfiguration.getKey())) .assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response)) .verifyComplete(); } /** * Tests that when an etag is passed to delete it will only delete if the current representation of the setting has the etag. * If the delete etag doesn't match anything the delete won't happen, this will result in a 412. */ public void deleteSettingWithETag() { deleteSettingWithETagRunner((initial, update) -> { final ConfigurationSetting initiallyAddedConfig = client.addSetting(initial).block(); final ConfigurationSetting updatedConfig = client.updateSetting(update).block(); StepVerifier.create(client.getSetting(initial)) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); StepVerifier.create(client.deleteSetting(initiallyAddedConfig)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED)); StepVerifier.create(client.deleteSetting(updatedConfig)) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); StepVerifier.create(client.getSetting(initial)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); }); } /** * Test the API will not make a delete call without having a key passed, an IllegalArgumentException should be thrown. */ public void deleteSettingNullKey() { assertRunnableThrowsException(() -> client.deleteSetting((String) null).block(), IllegalArgumentException.class); assertRunnableThrowsException(() -> client.deleteSetting((ConfigurationSetting) null).block(), NullPointerException.class); } /** * Tests assert that the setting can not be deleted after lock the setting. */ public void setReadOnly() { final String key = getKey(); final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("myValue"); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.setReadOnly(setting.getKey(), setting.getLabel())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.getSetting(setting.getKey())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.deleteSetting(setting)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, 409)); } /** * Tests assert that the setting can be deleted after unlock the setting. */ public void clearReadOnly() { final String key = getKey(); final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("myValue"); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.setReadOnly(setting.getKey(), setting.getLabel())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.deleteSetting(setting)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, 409)); StepVerifier.create(client.clearReadOnly(setting.getKey(), setting.getLabel())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.deleteSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); } /** * Tests assert that the setting can not be deleted after lock the setting. */ public void setReadOnlyWithConfigurationSetting() { final String key = getKey(); final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("myValue"); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.setReadOnlyWithResponse(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.getSetting(setting.getKey())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.deleteSetting(setting)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, 409)); } /** * Tests assert that the setting can be deleted after unlock the setting. */ public void clearReadOnlyWithConfigurationSetting() { final String key = getKey(); final ConfigurationSetting setting = new ConfigurationSetting().setKey(key).setValue("myValue"); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.setReadOnlyWithResponse(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.deleteSetting(setting)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, 409)); StepVerifier.create(client.clearReadOnlyWithResponse(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.deleteSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); } /** * Verifies that a ConfigurationSetting can be added with a label, and that we can fetch that ConfigurationSetting * from the service when filtering by either its label or just its key. */ public void listWithKeyAndLabel() { final String value = "myValue"; final String key = testResourceNamer.randomName(keyPrefix, 16); final String label = testResourceNamer.randomName("lbl", 8); final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue(value).setLabel(label); StepVerifier.create(client.setSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().setKeys(key).setLabels(label))) .assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().setKeys(key))) .assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting)) .verifyComplete(); } /** * Verifies that ConfigurationSettings can be added and that we can fetch those ConfigurationSettings from the * service when filtering by their keys. */ public void listWithMultipleKeys() { String key = getKey(); String key2 = getKey(); listWithMultipleKeysRunner(key, key2, (setting, setting2) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.addSetting(setting2)) .assertNext(response -> assertConfigurationEquals(setting2, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().setKeys(key, key2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); } /** * Verifies that ConfigurationSettings can be added with different labels and that we can fetch those ConfigurationSettings * from the service when filtering by their labels. */ public void listWithMultipleLabels() { String key = getKey(); String label = getLabel(); String label2 = getLabel(); listWithMultipleLabelsRunner(key, label, label2, (setting, setting2) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.addSetting(setting2)) .assertNext(response -> assertConfigurationEquals(setting2, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().setKeys(key).setLabels(label, label2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); } /** * Verifies that we can select filter results by key, label, and select fields using SettingSelector. */ public void listSettingsSelectFields() { listSettingsSelectFieldsRunner((settings, selector) -> { final List<Mono<Response<ConfigurationSetting>>> settingsBeingAdded = new ArrayList<>(); for (ConfigurationSetting setting : settings) { settingsBeingAdded.add(client.setSettingWithResponse(setting)); } Flux.merge(settingsBeingAdded).blockLast(); List<ConfigurationSetting> settingsReturned = new ArrayList<>(); StepVerifier.create(client.listSettings(selector)) .assertNext(settingsReturned::add) .assertNext(settingsReturned::add) .verifyComplete(); return settingsReturned; }); } /** * Verifies that we can get a ConfigurationSetting at the provided accept datetime */ public void listSettingsAcceptDateTime() { final String keyName = testResourceNamer.randomName(keyPrefix, 16); final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue"); final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue"); final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); StepVerifier.create(client.setSetting(original)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.setSetting(updated).delayElement(Duration.ofSeconds(2))) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); StepVerifier.create(client.setSetting(updated2)) .assertNext(response -> assertConfigurationEquals(updated2, response)) .verifyComplete(); List<ConfigurationSetting> revisions = client.listSettingRevisions(new SettingSelector().setKeys(keyName)).collectList().block(); assertNotNull(revisions); assertEquals(3, revisions.size()); SettingSelector options = new SettingSelector().setKeys(keyName).setAcceptDatetime(revisions.get(1).getLastModified()); StepVerifier.create(client.listSettings(options)) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); } /** * Verifies that we can get all of the revisions for this ConfigurationSetting. Then verifies that we can select * specific fields. */ public void listRevisions() { final String keyName = testResourceNamer.randomName(keyPrefix, 16); final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue"); final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue"); final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); StepVerifier.create(client.setSetting(original)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.setSetting(updated)) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); StepVerifier.create(client.setSetting(updated2)) .assertNext(response -> assertConfigurationEquals(updated2, response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(keyName))) .assertNext(response -> assertConfigurationEquals(updated2, response)) .assertNext(response -> assertConfigurationEquals(updated, response)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(keyName).setFields(SettingFields.KEY, SettingFields.ETAG))) .assertNext(response -> validateListRevisions(updated2, response)) .assertNext(response -> validateListRevisions(updated, response)) .assertNext(response -> validateListRevisions(original, response)) .verifyComplete(); } /** * Verifies that we can get all the revisions for all settings with the specified keys. */ public void listRevisionsWithMultipleKeys() { String key = getKey(); String key2 = getKey(); listRevisionsWithMultipleKeysRunner(key, key2, (testInput) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(testInput.get(0))) .assertNext(response -> assertConfigurationEquals(testInput.get(0), response)) .verifyComplete(); StepVerifier.create(client.updateSetting(testInput.get(1))) .assertNext(response -> assertConfigurationEquals(testInput.get(1), response)) .verifyComplete(); StepVerifier.create(client.addSetting(testInput.get(2))) .assertNext(response -> assertConfigurationEquals(testInput.get(2), response)) .verifyComplete(); StepVerifier.create(client.updateSetting(testInput.get(3))) .assertNext(response -> assertConfigurationEquals(testInput.get(3), response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(key, key2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); } /** * Verifies that we can get all revisions for all settings with the specified labels. */ public void listRevisionsWithMultipleLabels() { String key = getKey(); String label = getLabel(); String label2 = getLabel(); listRevisionsWithMultipleLabelsRunner(key, label, label2, (testInput) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(testInput.get(0))) .assertNext(response -> assertConfigurationEquals(testInput.get(0), response)) .verifyComplete(); StepVerifier.create(client.updateSetting(testInput.get(1))) .assertNext(response -> assertConfigurationEquals(testInput.get(1), response)) .verifyComplete(); StepVerifier.create(client.addSetting(testInput.get(2))) .assertNext(response -> assertConfigurationEquals(testInput.get(2), response)) .verifyComplete(); StepVerifier.create(client.updateSetting(testInput.get(3))) .assertNext(response -> assertConfigurationEquals(testInput.get(3), response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(key).setLabels(label, label2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); } /** * Verifies that the range header for revision selections returns the expected values. */ public void listRevisionsWithRange() { final String key = getKey(); final ConfigurationSetting original = new ConfigurationSetting().setKey(key).setValue("myValue"); final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue"); final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); StepVerifier.create(client.addSetting(original)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.updateSetting(updated)) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); StepVerifier.create(client.updateSetting(updated2)) .assertNext(response -> assertConfigurationEquals(updated2, response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(key).setRange(new Range(1, 2)))) .assertNext(response -> assertConfigurationEquals(updated, response)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); } /** * Verifies that an exception will be thrown from the service if it cannot satisfy the range request. */ public void listRevisionsInvalidRange() { final String key = getKey(); final ConfigurationSetting original = new ConfigurationSetting().setKey(key).setValue("myValue"); StepVerifier.create(client.addSetting(original)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(key).setRange(new Range(0, 10)))) .verifyErrorSatisfies(exception -> assertRestException(exception, 416)); } /** * Verifies that we can get a subset of revisions based on the "acceptDateTime" */ public void listRevisionsAcceptDateTime() { final String keyName = testResourceNamer.randomName(keyPrefix, 16); final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue"); final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue"); final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); StepVerifier.create(client.setSetting(original)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.setSetting(updated).delayElement(Duration.ofSeconds(2))) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); StepVerifier.create(client.setSetting(updated2)) .assertNext(response -> assertConfigurationEquals(updated2, response)) .verifyComplete(); List<ConfigurationSetting> revisions = client.listSettingRevisions(new SettingSelector().setKeys(keyName)).collectList().block(); assertNotNull(revisions); assertEquals(3, revisions.size()); SettingSelector options = new SettingSelector().setKeys(keyName).setAcceptDatetime(revisions.get(1).getLastModified()); StepVerifier.create(client.listSettingRevisions(options)) .assertNext(response -> assertConfigurationEquals(updated, response)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); } /** * Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination * (ie. where 'nextLink' has a URL pointing to the next page of results.) */ public void listRevisionsWithPagination() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); for (int value = 0; value < numberExpected; value++) { settings.add(new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix)); } List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (ConfigurationSetting setting : settings) { results.add(client.setSettingWithResponse(setting)); } SettingSelector filter = new SettingSelector().setKeys(keyPrefix).setLabels(labelPrefix); Flux.merge(results).blockLast(); StepVerifier.create(client.listSettingRevisions(filter)) .expectNextCount(numberExpected) .verifyComplete(); } /** * Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times. * (ie. where 'nextLink' has a URL pointing to the next page of results.) */ public void listRevisionsWithPaginationAndRepeatStream() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (int value = 0; value < numberExpected; value++) { ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix); settings.add(setting); results.add(client.setSettingWithResponse(setting)); } SettingSelector filter = new SettingSelector().setKeys(keyPrefix).setLabels(labelPrefix); Flux.merge(results).blockLast(); List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>(); List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>(); PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listSettingRevisions(filter); configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList1.size()); configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList2.size()); } /** * Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times. * (ie. where 'nextLink' has a URL pointing to the next page of results.) */ public void listRevisionsWithPaginationAndRepeatIterator() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (int value = 0; value < numberExpected; value++) { ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix); settings.add(setting); results.add(client.setSettingWithResponse(setting)); } SettingSelector filter = new SettingSelector().setKeys(keyPrefix).setLabels(labelPrefix); Flux.merge(results).blockLast(); List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>(); List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>(); PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listSettingRevisions(filter); configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList1.size()); configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList2.size()); } /** * Verifies that, given a ton of existing settings, we can list the ConfigurationSettings using pagination * (ie. where 'nextLink' has a URL pointing to the next page of results. */ public void listSettingsWithPagination() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); for (int value = 0; value < numberExpected; value++) { settings.add(new ConfigurationSetting().setKey(keyPrefix + "-" + value).setValue("myValue").setLabel(labelPrefix)); } List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (ConfigurationSetting setting : settings) { results.add(client.setSettingWithResponse(setting)); } SettingSelector filter = new SettingSelector().setKeys(keyPrefix + "-*").setLabels(labelPrefix); Flux.merge(results).blockLast(); StepVerifier.create(client.listSettings(filter)) .expectNextCount(numberExpected) .verifyComplete(); } /** * Verifies the conditional "GET" scenario where the setting has yet to be updated, resulting in a 304. This GET * scenario will return a setting when the etag provided does not match the one of the current setting. */ public void getSettingWhenValueNotUpdated() { final String key = testResourceNamer.randomName(keyPrefix, 16); final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue("myValue"); final ConfigurationSetting newExpected = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting block = client.addSetting(expected).single().block(); assertNotNull(block); assertConfigurationEquals(expected, block); StepVerifier.create(client.setSetting(newExpected)) .assertNext(response -> assertConfigurationEquals(newExpected, response)) .verifyComplete(); } public void deleteAllSettings() { client.listSettings(new SettingSelector().setKeys("*")) .flatMap(configurationSetting -> { logger.info("Deleting key:label [{}:{}]. isLocked? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isLocked()); return client.deleteSetting(configurationSetting); }).blockLast(); } }
class ConfigurationAsyncClientTest extends ConfigurationClientTestBase { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class); private static final String NO_LABEL = null; private ConfigurationAsyncClient client; @Override protected void beforeTest() { beforeTestSetup(); if (interceptorManager.isPlaybackMode()) { client = clientSetup(credentials -> new ConfigurationClientBuilder() .credential(credentials) .httpClient(interceptorManager.getPlaybackClient()) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .buildAsyncClient()); } else { client = clientSetup(credentials -> new ConfigurationClientBuilder() .credential(credentials) .httpClient(new NettyAsyncHttpClientBuilder().wiretap(true).build()) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .addPolicy(interceptorManager.getRecordPolicy()) .addPolicy(new RetryPolicy()) .buildAsyncClient()); } } @Override /** * Tests that a configuration is able to be added, these are differentiate from each other using a key or key-label identifier. */ public void addSetting() { addSettingRunner((expected) -> StepVerifier.create(client.addSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete()); } /** * Tests that we cannot add a configuration setting when the key is an empty string. */ public void addSettingEmptyKey() { StepVerifier.create(client.addSetting("", null, "A value")) .verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD)); } /** * Tests that we can add configuration settings when value is not null or an empty string. */ public void addSettingEmptyValue() { addSettingEmptyValueRunner((setting) -> { StepVerifier.create(client.addSetting(setting.getKey(), setting.getLabel(), setting.getValue())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.getSetting(setting.getKey(), setting.getLabel(), null)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); }); } /** * Verifies that an exception is thrown when null key is passed. */ public void addSettingNullKey() { assertRunnableThrowsException(() -> client.addSetting(null, null, "A Value").block(), IllegalArgumentException.class); assertRunnableThrowsException(() -> client.addSetting(null).block(), NullPointerException.class); } /** * Tests that a configuration cannot be added twice with the same key. This should return a 412 error. */ public void addExistingSetting() { addExistingSettingRunner((expected) -> StepVerifier.create(client.addSetting(expected).then(client.addSetting(expected))) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, HttpURLConnection.HTTP_PRECON_FAILED))); } /** * Tests that a configuration is able to be added or updated with set. * When the configuration is locked updates cannot happen, this will result in a 409. */ public void setSetting() { setSettingRunner((expected, update) -> StepVerifier.create(client.setSettingWithResponse(expected, false)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete()); } /** * Tests that when an etag is passed to set it will only set if the current representation of the setting has the * etag. If the set etag doesn't match anything the update won't happen, this will result in a 412. This will * prevent set from doing an add as well. */ public void setSettingIfEtag() { setSettingIfEtagRunner((initial, update) -> { StepVerifier.create(client.setSettingWithResponse(initial.setETag("badEtag"), true)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED)); final String etag = client.addSetting(initial).block().getETag(); StepVerifier.create(client.setSettingWithResponse(update.setETag(etag), true)) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(initial, true)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED)); StepVerifier.create(client.getSettingWithResponse(update, null, false)) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); }); } /** * Tests that we cannot set a configuration setting when the key is an empty string. */ public void setSettingEmptyKey() { StepVerifier.create(client.setSetting("", NO_LABEL, "A value")) .verifyErrorSatisfies(ex -> assertRestException(ex, HttpURLConnection.HTTP_BAD_METHOD)); } /** * Tests that we can set configuration settings when value is not null or an empty string. * Value is not a required property. */ public void setSettingEmptyValue() { setSettingEmptyValueRunner((setting) -> { StepVerifier.create(client.setSetting(setting.getKey(), NO_LABEL, setting.getValue())) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.getSetting(setting.getKey(), setting.getLabel(), null)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); }); } /** * Verifies that an exception is thrown when null key is passed. */ public void setSettingNullKey() { assertRunnableThrowsException(() -> client.setSetting(null, NO_LABEL, "A Value").block(), IllegalArgumentException.class); assertRunnableThrowsException(() -> client.setSettingWithResponse(null, false).block(), NullPointerException.class); } /** * Tests that a configuration is able to be retrieved when it exists, whether or not it is locked. */ public void getSetting() { getSettingRunner((expected) -> StepVerifier.create(client.addSetting(expected).then(client.getSettingWithResponse(expected, null, false))) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete()); } /** * Tests that attempting to retrieve a non-existent configuration doesn't work, this will result in a 404. */ public void getSettingNotFound() { final String key = getKey(); final ConfigurationSetting neverRetrievedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverRetreivedValue"); final ConfigurationSetting nonExistentLabel = new ConfigurationSetting().setKey(key).setLabel("myNonExistentLabel"); StepVerifier.create(client.addSetting(neverRetrievedConfiguration)) .assertNext(response -> assertConfigurationEquals(neverRetrievedConfiguration, response)) .verifyComplete(); StepVerifier.create(client.getSetting("myNonExistentKey", null, null)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); StepVerifier.create(client.getSettingWithResponse(nonExistentLabel, null, false)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); } /** * Tests that configurations are able to be deleted when they exist. * After the configuration has been deleted attempting to get it will result in a 404, the same as if the * configuration never existed. */ public void deleteSetting() { deleteSettingRunner((expected) -> { StepVerifier.create(client.addSetting(expected).then(client.getSettingWithResponse(expected, null, false))) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(expected, false)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.getSettingWithResponse(expected, null, false)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); }); } /** * Tests that attempting to delete a non-existent configuration will return a 204. */ public void deleteSettingNotFound() { final String key = getKey(); final ConfigurationSetting neverDeletedConfiguration = new ConfigurationSetting().setKey(key).setValue("myNeverDeletedValue"); StepVerifier.create(client.addSetting(neverDeletedConfiguration)) .assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(new ConfigurationSetting().setKey("myNonExistentKey"), false)) .assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(new ConfigurationSetting().setKey(neverDeletedConfiguration.getKey()).setLabel("myNonExistentLabel"), false)) .assertNext(response -> assertConfigurationEquals(null, response, HttpURLConnection.HTTP_NO_CONTENT)) .verifyComplete(); StepVerifier.create(client.getSetting(neverDeletedConfiguration.getKey(), neverDeletedConfiguration.getLabel(), null)) .assertNext(response -> assertConfigurationEquals(neverDeletedConfiguration, response)) .verifyComplete(); } /** * Tests that when an etag is passed to delete it will only delete if the current representation of the setting has the etag. * If the delete etag doesn't match anything the delete won't happen, this will result in a 412. */ public void deleteSettingWithETag() { deleteSettingWithETagRunner((initial, update) -> { final ConfigurationSetting initiallyAddedConfig = client.addSetting(initial).block(); final ConfigurationSetting updatedConfig = client.setSettingWithResponse(update, true).block().getValue(); StepVerifier.create(client.getSettingWithResponse(initial, null, false)) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(initiallyAddedConfig, true)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_PRECON_FAILED)); StepVerifier.create(client.deleteSettingWithResponse(updatedConfig, true)) .assertNext(response -> assertConfigurationEquals(update, response)) .verifyComplete(); StepVerifier.create(client.getSettingWithResponse(initial, null, false)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceNotFoundException.class, HttpURLConnection.HTTP_NOT_FOUND)); }); } /** * Test the API will not make a delete call without having a key passed, an IllegalArgumentException should be thrown. */ public void deleteSettingNullKey() { assertRunnableThrowsException(() -> client.deleteSetting(null, null).block(), IllegalArgumentException.class); assertRunnableThrowsException(() -> client.deleteSettingWithResponse(null, false).block(), NullPointerException.class); } /** * Tests assert that the setting can not be deleted after lock the setting. */ public void setReadOnly() { lockUnlockRunner((expected) -> { StepVerifier.create(client.addSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel())) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(expected, false)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, 409)); }); } /** * Tests assert that the setting can be deleted after unlock the setting. */ public void clearReadOnly() { lockUnlockRunner((expected) -> { StepVerifier.create(client.addSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel())) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(expected, false)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, 409)); StepVerifier.create(client.clearReadOnly(expected.getKey(), expected.getLabel())) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(expected, false)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); }); } /** * Tests assert that the setting can not be deleted after lock the setting. */ public void setReadOnlyWithConfigurationSetting() { lockUnlockRunner((expected) -> { StepVerifier.create(client.addSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.setReadOnlyWithResponse(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(expected, false)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, 409)); }); } /** * Tests assert that the setting can be deleted after unlock the setting. */ public void clearReadOnlyWithConfigurationSetting() { lockUnlockRunner((expected) -> { StepVerifier.create(client.addSetting(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.setReadOnly(expected.getKey(), expected.getLabel())) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(expected, false)) .verifyErrorSatisfies(ex -> assertRestException(ex, ResourceModifiedException.class, 409)); StepVerifier.create(client.clearReadOnlyWithResponse(expected)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.deleteSettingWithResponse(expected, false)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); }); } /** * Verifies that a ConfigurationSetting can be added with a label, and that we can fetch that ConfigurationSetting * from the service when filtering by either its label or just its key. */ public void listWithKeyAndLabel() { final String value = "myValue"; final String key = testResourceNamer.randomName(keyPrefix, 16); final String label = testResourceNamer.randomName("lbl", 8); final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue(value).setLabel(label); StepVerifier.create(client.setSettingWithResponse(expected, false)) .assertNext(response -> assertConfigurationEquals(expected, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().setKeys(key).setLabels(label))) .assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().setKeys(key))) .assertNext(configurationSetting -> assertConfigurationEquals(expected, configurationSetting)) .verifyComplete(); } /** * Verifies that ConfigurationSettings can be added and that we can fetch those ConfigurationSettings from the * service when filtering by their keys. */ public void listWithMultipleKeys() { String key = getKey(); String key2 = getKey(); listWithMultipleKeysRunner(key, key2, (setting, setting2) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.addSetting(setting2)) .assertNext(response -> assertConfigurationEquals(setting2, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().setKeys(key, key2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); } /** * Verifies that ConfigurationSettings can be added with different labels and that we can fetch those ConfigurationSettings * from the service when filtering by their labels. */ public void listWithMultipleLabels() { String key = getKey(); String label = getLabel(); String label2 = getLabel(); listWithMultipleLabelsRunner(key, label, label2, (setting, setting2) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(setting)) .assertNext(response -> assertConfigurationEquals(setting, response)) .verifyComplete(); StepVerifier.create(client.addSetting(setting2)) .assertNext(response -> assertConfigurationEquals(setting2, response)) .verifyComplete(); StepVerifier.create(client.listSettings(new SettingSelector().setKeys(key).setLabels(label, label2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); } /** * Verifies that we can select filter results by key, label, and select fields using SettingSelector. */ public void listSettingsSelectFields() { listSettingsSelectFieldsRunner((settings, selector) -> { final List<Mono<Response<ConfigurationSetting>>> settingsBeingAdded = new ArrayList<>(); for (ConfigurationSetting setting : settings) { settingsBeingAdded.add(client.setSettingWithResponse(setting, false)); } Flux.merge(settingsBeingAdded).blockLast(); List<ConfigurationSetting> settingsReturned = new ArrayList<>(); StepVerifier.create(client.listSettings(selector)) .assertNext(settingsReturned::add) .assertNext(settingsReturned::add) .verifyComplete(); return settingsReturned; }); } /** * Verifies that we can get a ConfigurationSetting at the provided accept datetime */ public void listSettingsAcceptDateTime() { final String keyName = testResourceNamer.randomName(keyPrefix, 16); final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue"); final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue"); final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); StepVerifier.create(client.setSettingWithResponse(original, false)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2))) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(updated2, false)) .assertNext(response -> assertConfigurationEquals(updated2, response)) .verifyComplete(); List<ConfigurationSetting> revisions = client.listSettingRevisions(new SettingSelector().setKeys(keyName)).collectList().block(); assertNotNull(revisions); assertEquals(3, revisions.size()); SettingSelector options = new SettingSelector().setKeys(keyName).setAcceptDatetime(revisions.get(1).getLastModified()); StepVerifier.create(client.listSettings(options)) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); } /** * Verifies that we can get all of the revisions for this ConfigurationSetting. Then verifies that we can select * specific fields. */ public void listRevisions() { final String keyName = testResourceNamer.randomName(keyPrefix, 16); final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue"); final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue"); final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); StepVerifier.create(client.setSettingWithResponse(original, false)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(updated, false)) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(updated2, false)) .assertNext(response -> assertConfigurationEquals(updated2, response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(keyName))) .assertNext(response -> assertConfigurationEquals(updated2, response)) .assertNext(response -> assertConfigurationEquals(updated, response)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(keyName).setFields(SettingFields.KEY, SettingFields.ETAG))) .assertNext(response -> validateListRevisions(updated2, response)) .assertNext(response -> validateListRevisions(updated, response)) .assertNext(response -> validateListRevisions(original, response)) .verifyComplete(); } /** * Verifies that we can get all the revisions for all settings with the specified keys. */ public void listRevisionsWithMultipleKeys() { String key = getKey(); String key2 = getKey(); listRevisionsWithMultipleKeysRunner(key, key2, (testInput) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(testInput.get(0))) .assertNext(response -> assertConfigurationEquals(testInput.get(0), response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(testInput.get(1), false)) .assertNext(response -> assertConfigurationEquals(testInput.get(1), response)) .verifyComplete(); StepVerifier.create(client.addSetting(testInput.get(2))) .assertNext(response -> assertConfigurationEquals(testInput.get(2), response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(testInput.get(3), false)) .assertNext(response -> assertConfigurationEquals(testInput.get(3), response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(key, key2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); } /** * Verifies that we can get all revisions for all settings with the specified labels. */ public void listRevisionsWithMultipleLabels() { String key = getKey(); String label = getLabel(); String label2 = getLabel(); listRevisionsWithMultipleLabelsRunner(key, label, label2, (testInput) -> { List<ConfigurationSetting> selected = new ArrayList<>(); StepVerifier.create(client.addSetting(testInput.get(0))) .assertNext(response -> assertConfigurationEquals(testInput.get(0), response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(testInput.get(1), false)) .assertNext(response -> assertConfigurationEquals(testInput.get(1), response)) .verifyComplete(); StepVerifier.create(client.addSetting(testInput.get(2))) .assertNext(response -> assertConfigurationEquals(testInput.get(2), response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(testInput.get(3), false)) .assertNext(response -> assertConfigurationEquals(testInput.get(3), response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(key).setLabels(label, label2))) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .consumeNextWith(selected::add) .verifyComplete(); return selected; }); } /** * Verifies that the range header for revision selections returns the expected values. */ public void listRevisionsWithRange() { final String key = getKey(); final ConfigurationSetting original = new ConfigurationSetting().setKey(key).setValue("myValue"); final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue"); final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); StepVerifier.create(client.addSetting(original)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(updated, false)) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(updated2, false)) .assertNext(response -> assertConfigurationEquals(updated2, response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(key).setRange(new Range(1, 2)))) .assertNext(response -> assertConfigurationEquals(updated, response)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); } /** * Verifies that an exception will be thrown from the service if it cannot satisfy the range request. */ public void listRevisionsInvalidRange() { final String key = getKey(); final ConfigurationSetting original = new ConfigurationSetting().setKey(key).setValue("myValue"); StepVerifier.create(client.addSetting(original)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.listSettingRevisions(new SettingSelector().setKeys(key).setRange(new Range(0, 10)))) .verifyErrorSatisfies(exception -> assertRestException(exception, 416)); } /** * Verifies that we can get a subset of revisions based on the "acceptDateTime" */ public void listRevisionsAcceptDateTime() { final String keyName = testResourceNamer.randomName(keyPrefix, 16); final ConfigurationSetting original = new ConfigurationSetting().setKey(keyName).setValue("myValue"); final ConfigurationSetting updated = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue"); final ConfigurationSetting updated2 = new ConfigurationSetting().setKey(original.getKey()).setValue("anotherValue2"); StepVerifier.create(client.setSettingWithResponse(original, false)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(updated, false).delayElement(Duration.ofSeconds(2))) .assertNext(response -> assertConfigurationEquals(updated, response)) .verifyComplete(); StepVerifier.create(client.setSettingWithResponse(updated2, false)) .assertNext(response -> assertConfigurationEquals(updated2, response)) .verifyComplete(); List<ConfigurationSetting> revisions = client.listSettingRevisions(new SettingSelector().setKeys(keyName)).collectList().block(); assertNotNull(revisions); assertEquals(3, revisions.size()); SettingSelector options = new SettingSelector().setKeys(keyName).setAcceptDatetime(revisions.get(1).getLastModified()); StepVerifier.create(client.listSettingRevisions(options)) .assertNext(response -> assertConfigurationEquals(updated, response)) .assertNext(response -> assertConfigurationEquals(original, response)) .verifyComplete(); } /** * Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination * (ie. where 'nextLink' has a URL pointing to the next page of results.) */ public void listRevisionsWithPagination() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); for (int value = 0; value < numberExpected; value++) { settings.add(new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix)); } List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (ConfigurationSetting setting : settings) { results.add(client.setSettingWithResponse(setting, false)); } SettingSelector filter = new SettingSelector().setKeys(keyPrefix).setLabels(labelPrefix); Flux.merge(results).blockLast(); StepVerifier.create(client.listSettingRevisions(filter)) .expectNextCount(numberExpected) .verifyComplete(); } /** * Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times. * (ie. where 'nextLink' has a URL pointing to the next page of results.) */ public void listRevisionsWithPaginationAndRepeatStream() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (int value = 0; value < numberExpected; value++) { ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix); settings.add(setting); results.add(client.setSettingWithResponse(setting, false)); } SettingSelector filter = new SettingSelector().setKeys(keyPrefix).setLabels(labelPrefix); Flux.merge(results).blockLast(); List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>(); List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>(); PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listSettingRevisions(filter); configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList1.size()); configurationSettingPagedFlux.toStream().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList2.size()); } /** * Verifies that, given a ton of revisions, we can list the revisions ConfigurationSettings using pagination and stream is invoked multiple times. * (ie. where 'nextLink' has a URL pointing to the next page of results.) */ public void listRevisionsWithPaginationAndRepeatIterator() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (int value = 0; value < numberExpected; value++) { ConfigurationSetting setting = new ConfigurationSetting().setKey(keyPrefix).setValue("myValue" + value).setLabel(labelPrefix); settings.add(setting); results.add(client.setSettingWithResponse(setting, false)); } SettingSelector filter = new SettingSelector().setKeys(keyPrefix).setLabels(labelPrefix); Flux.merge(results).blockLast(); List<ConfigurationSetting> configurationSettingList1 = new ArrayList<>(); List<ConfigurationSetting> configurationSettingList2 = new ArrayList<>(); PagedFlux<ConfigurationSetting> configurationSettingPagedFlux = client.listSettingRevisions(filter); configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList1.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList1.size()); configurationSettingPagedFlux.toIterable().forEach(configurationSetting -> configurationSettingList2.add(configurationSetting)); assertEquals(numberExpected, configurationSettingList2.size()); } /** * Verifies that, given a ton of existing settings, we can list the ConfigurationSettings using pagination * (ie. where 'nextLink' has a URL pointing to the next page of results. */ public void listSettingsWithPagination() { final int numberExpected = 50; List<ConfigurationSetting> settings = new ArrayList<>(numberExpected); for (int value = 0; value < numberExpected; value++) { settings.add(new ConfigurationSetting().setKey(keyPrefix + "-" + value).setValue("myValue").setLabel(labelPrefix)); } List<Mono<Response<ConfigurationSetting>>> results = new ArrayList<>(); for (ConfigurationSetting setting : settings) { results.add(client.setSettingWithResponse(setting, false)); } SettingSelector filter = new SettingSelector().setKeys(keyPrefix + "-*").setLabels(labelPrefix); Flux.merge(results).blockLast(); StepVerifier.create(client.listSettings(filter)) .expectNextCount(numberExpected) .verifyComplete(); } /** * Verifies the conditional "GET" scenario where the setting has yet to be updated, resulting in a 304. This GET * scenario will return a setting when the etag provided does not match the one of the current setting. */ public void getSettingWhenValueNotUpdated() { final String key = testResourceNamer.randomName(keyPrefix, 16); final ConfigurationSetting expected = new ConfigurationSetting().setKey(key).setValue("myValue"); final ConfigurationSetting newExpected = new ConfigurationSetting().setKey(key).setValue("myNewValue"); final ConfigurationSetting block = client.addSetting(expected).single().block(); assertNotNull(block); assertConfigurationEquals(expected, block); StepVerifier.create(client.setSettingWithResponse(newExpected, false)) .assertNext(response -> assertConfigurationEquals(newExpected, response)) .verifyComplete(); } public void deleteAllSettings() { client.listSettings(new SettingSelector().setKeys("*")) .flatMap(configurationSetting -> { logger.info("Deleting key:label [{}:{}]. isLocked? {}", configurationSetting.getKey(), configurationSetting.getLabel(), configurationSetting.isLocked()); return client.deleteSettingWithResponse(configurationSetting, false); }).blockLast(); } }
There is a FluxUtil method to handle pulling a response value out, I believe it is called toMono. Should use that in all the places update.
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) { return withContext(context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime, false, context)).map(response -> response.getValue()); }
false, context)).map(response -> response.getValue());
public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) { return withContext(context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime, false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); }
class ConfigurationAsyncClient { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class); private static final String ETAG_ANY = "*"; private static final String RANGE_QUERY = "items=%s"; private final String serviceEndpoint; private final ConfigurationService service; /** * Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}. * Each service call goes through the {@code pipeline}. * * @param serviceEndpoint URL for the App Configuration service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ ConfigurationAsyncClient(URL serviceEndpoint, HttpPipeline pipeline) { this.service = RestProxy.create(ConfigurationService.class, pipeline); this.serviceEndpoint = serviceEndpoint.toString(); } /** * Adds a configuration value in the service if that key does not exist. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add, or optionally, null if a setting with * label is desired. * @param value The value associated with this configuration setting key. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If a ConfigurationSetting with the same key exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(String key, String label, String value) { return withContext( context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context)) .map(response -> response.getValue()); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param setting The setting to add to the configuration service. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)) .map(response -> response.getValue()); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse * * @param setting The setting to add to the configuration service. * @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs * or the key is an invalid value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)); } Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service .setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null, getETagValue(ETAG_ANY), context) .doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue())) .onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper) .doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error)); } /** * Creates or updates a configuration value in the service with the given key. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting * * @param key The key of the configuration setting to create or update. * @param label The label of the configuration setting to create or update, or optionally, null if a setting with * label is desired. * @param value The value of this configuration setting. * @return The {@link ConfigurationSetting} that was created or updated, if the key is an invalid value (which will * also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the setting exists and is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setSetting(String key, String label, String value) { return withContext( context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), false, context)) .map(response -> response.getValue()); } /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. * * If {@link ConfigurationSetting * setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse * * @param setting The configuration setting to create or update. * @param ifUnchanged A boolean indicates if using setting's ETag as If-Match's value. * @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an * invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value * (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If the {@link ConfigurationSetting * wildcard character, and the current configuration value's etag does not match, or the setting exists and is * locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> setSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error)); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key, String label) { return getSetting(key, label, null); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional, and the * {@code asOfDateTime} as optional. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @param asOfDateTime Datetime used to retrieve the state of the configuration at that time. If null the current * state will be retrieved asOfDateTime is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Attempts to get the ConfigurationSetting given the {@code key}, optional {@code label}, optional * {@code asOfDateTime} * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse * * @param setting The setting to retrieve based on its key and optional label combination. * @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with * asOfDateTime is desired. * @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting * If-None-Match header. * @return A REST response containing the {@link ConfigurationSetting} stored in the service, if the configuration * value does not exist or the key is an invalid value (which will also throw HttpResponseException described * below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist. * @throws HttpResponseException If the {@code} key is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean ifChanged) { return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context)); } Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean onlyIfChanged, Context context) { validateSetting(setting); final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null; return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error)); } /** * Deletes the ConfigurationSetting with a matching {@code key}. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting * * @param key The key of the setting to delete. * @param label The label of the configuration setting to delete, or optionally, null if a setting with * label is desired. * @return The deleted ConfigurationSetting or {@code null} if it didn't exist. {@code null} is also returned if the * {@code key} is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> deleteSetting(String key, String label) { return withContext( context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context)) .map(response -> response.getValue()); } /** * Deletes the {@link ConfigurationSetting} with a matching key, along with the given label and etag. * * If {@link ConfigurationSetting * the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the * ConfigurationSetting yet. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse * * @param setting The ConfigurationSetting to delete. * @param ifUnchanged A boolean indicator to decide using setting's ETag value as IF-MATCH value. * If false, set IF_MATCH to {@code null}. Otherwise, set the setting's ETag value to IF_MATCH. * @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null} * is also returned if the {@code key} is an invalid value or {@link ConfigurationSetting * does not match the current etag (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws NullPointerException When {@code setting} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws ResourceNotFoundException If {@link ConfigurationSetting * character, and does not match the current etag value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> deleteSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error)); } /** * Lock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly * * @param key The key of the configuration setting to lock. * @param label The label of the configuration setting to lock, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} that was locked, if a key collision occurs or the key is an invalid * value(which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setReadOnly(String key, String label) { return withContext(context -> setReadOnly( new ConfigurationSetting().setKey(key).setLabel(label), context)) .map(response -> response.getValue()); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was unlocked, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> setReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error)); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> clearReadOnly(String key, String label) { return withContext(context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context)) .map(response -> response.getValue()); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> clearReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error)); } /** * Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all * the {@link ConfigurationSetting configuration settings} are fetched with their current values. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all settings that use the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings} * * @param options Optional. Options to filter configuration setting results from the service. * @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux * contains all of the current settings in the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettings(SettingSelector options) { return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(options, context)), continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken))); } PagedFlux<ConfigurationSetting> listSettings(SettingSelector options, Context context) { return new PagedFlux<>(() -> listFirstPageSettings(options, context), continuationToken -> listNextPageSettings(context, continuationToken)); } private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } return service.listKeyValues(serviceEndpoint, continuationToken, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken, error)); } private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector options, Context context) { if (options == null) { return service.listKeyValues(serviceEndpoint, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings")) .doOnSuccess(response -> logger.info("Listed all ConfigurationSettings")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error)); } String fields = ImplUtils.arrayToString(options.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(options.getKeys(), key -> key); String labels = ImplUtils.arrayToString(options.getLabels(), label -> label); return service.listKeyValues(serviceEndpoint, keys, labels, fields, options.getAcceptDateTime(), context) .doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", options)) .doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", options)) .doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", options, error)); } /** * Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided * in descending order from their {@link ConfigurationSetting * after a period of time. The service maintains change history for up to 7 days. * * If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code options}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions} * * @param selector Optional. Used to filter configuration setting revisions from the service. * @return Revisions of the ConfigurationSetting */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) { return new PagedFlux<>(() -> withContext(context -> listSettingRevisionsFirstPage(selector, context)), continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context))); } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) { Mono<PagedResponse<ConfigurationSetting>> result; if (selector != null) { String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key); String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label); String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null; result = service.listKeyValueRevisions( serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector)) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector)) .doOnError( error -> logger.warning("Failed to list ConfigurationSetting revisions - {}", selector, error)); } else { result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions")) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error)); } return result; } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result; } PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new PagedFlux<>(() -> listSettingRevisionsFirstPage(selector, context), continuationToken -> listSettingRevisionsNextPage(continuationToken, context)); } private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context)); } private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings( PagedResponse<ConfigurationSetting> page, Context context) { return ImplUtils.extractAndFetch(page, context, this::listSettings); } /* * Azure Configuration service requires that the etag value is surrounded in quotation marks. * * @param etag The etag to get the value for. If null is pass in, an empty string is returned. * @return The etag surrounded by quotations. (ex. "etag") */ private static String getETagValue(String etag) { return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\""; } /* * Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL. */ private static void validateSetting(ConfigurationSetting setting) { Objects.requireNonNull(setting); if (setting.getKey() == null) { throw new IllegalArgumentException("Parameter 'key' is required and cannot be null."); } } /* * Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since * add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return * this status when the configuration doesn't exist. * * @param throwable Error response from the service. * * @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException, * otherwise the throwable is returned unmodified. */ private static Throwable addSettingExceptionMapper(Throwable throwable) { if (!(throwable instanceof ResourceNotFoundException)) { return throwable; } ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable; return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse()); } }
class ConfigurationAsyncClient { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class); private static final String ETAG_ANY = "*"; private static final String RANGE_QUERY = "items=%s"; private final String serviceEndpoint; private final ConfigurationService service; /** * Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}. * Each service call goes through the {@code pipeline}. * * @param serviceEndpoint URL for the App Configuration service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ ConfigurationAsyncClient(URL serviceEndpoint, HttpPipeline pipeline) { this.service = RestProxy.create(ConfigurationService.class, pipeline); this.serviceEndpoint = serviceEndpoint.toString(); } /** * Adds a configuration value in the service if that key does not exist. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add, or optionally, null if a setting with * label is desired. * @param value The value associated with this configuration setting key. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If a ConfigurationSetting with the same key exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(String key, String label, String value) { return withContext( context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param setting The setting to add to the configuration service. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse * * @param setting The setting to add to the configuration service. * @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs * or the key is an invalid value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)); } Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null, getETagValue(ETAG_ANY), context) .doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue())) .onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper) .doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error)); } /** * Creates or updates a configuration value in the service with the given key. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting * * @param key The key of the configuration setting to create or update. * @param label The label of the configuration setting to create or update, or optionally, null if a setting with * label is desired. * @param value The value of this configuration setting. * @return The {@link ConfigurationSetting} that was created or updated, if the key is an invalid value (which will * also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the setting exists and is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setSetting(String key, String label, String value) { return withContext(context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. * * If {@link ConfigurationSetting * setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse * * @param setting The configuration setting to create or update. * @param ifUnchanged A boolean indicates if using setting's ETag as If-Match's value. * @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an * invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value * (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If the {@link ConfigurationSetting * wildcard character, and the current configuration value's etag does not match, or the setting exists and is * locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> setSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error)); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key, String label) { return getSetting(key, label, null); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional, and the * {@code asOfDateTime} as optional. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @param asOfDateTime Datetime used to retrieve the state of the configuration at that time. If null the current * state will be retrieved asOfDateTime is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Attempts to get the ConfigurationSetting given the {@code key}, optional {@code label}, optional * {@code asOfDateTime} * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse * * @param setting The setting to retrieve based on its key and optional label combination. * @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with * asOfDateTime is desired. * @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting * If-None-Match header. * @return A REST response containing the {@link ConfigurationSetting} stored in the service, if the configuration * value does not exist or the key is an invalid value (which will also throw HttpResponseException described * below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist. * @throws HttpResponseException If the {@code} key is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean ifChanged) { return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context)); } Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean onlyIfChanged, Context context) { validateSetting(setting); final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null; return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error)); } /** * Deletes the ConfigurationSetting with a matching {@code key}. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting * * @param key The key of the setting to delete. * @param label The label of the configuration setting to delete, or optionally, null if a setting with * label is desired. * @return The deleted ConfigurationSetting or {@code null} if it didn't exist. {@code null} is also returned if the * {@code key} is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> deleteSetting(String key, String label) { return withContext( context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Deletes the {@link ConfigurationSetting} with a matching key, along with the given label and etag. * * If {@link ConfigurationSetting * the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the * ConfigurationSetting yet. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse * * @param setting The ConfigurationSetting to delete. * @param ifUnchanged A boolean indicator to decide using setting's ETag value as IF-MATCH value. * If false, set IF_MATCH to {@code null}. Otherwise, set the setting's ETag value to IF_MATCH. * @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null} * is also returned if the {@code key} is an invalid value or {@link ConfigurationSetting * does not match the current etag (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws NullPointerException When {@code setting} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws ResourceNotFoundException If {@link ConfigurationSetting * character, and does not match the current etag value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> deleteSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error)); } /** * Lock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly * * @param key The key of the configuration setting to lock. * @param label The label of the configuration setting to lock, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} that was locked, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setReadOnly(String key, String label) { return withContext(context -> setReadOnly( new ConfigurationSetting().setKey(key).setLabel(label), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was unlocked, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> setReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error)); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> clearReadOnly(String key, String label) { return withContext(context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> clearReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error)); } /** * Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all * the {@link ConfigurationSetting configuration settings} are fetched with their current values. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all settings that use the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings} * * @param options Optional. Options to filter configuration setting results from the service. * @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux * contains all of the current settings in the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettings(SettingSelector options) { return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(options, context)), continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken))); } PagedFlux<ConfigurationSetting> listSettings(SettingSelector options, Context context) { return new PagedFlux<>(() -> listFirstPageSettings(options, context), continuationToken -> listNextPageSettings(context, continuationToken)); } private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } return service.listKeyValues(serviceEndpoint, continuationToken, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken, error)); } private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector options, Context context) { if (options == null) { return service.listKeyValues(serviceEndpoint, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings")) .doOnSuccess(response -> logger.info("Listed all ConfigurationSettings")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error)); } String fields = ImplUtils.arrayToString(options.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(options.getKeys(), key -> key); String labels = ImplUtils.arrayToString(options.getLabels(), label -> label); return service.listKeyValues(serviceEndpoint, keys, labels, fields, options.getAcceptDateTime(), context) .doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", options)) .doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", options)) .doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", options, error)); } /** * Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided * in descending order from their {@link ConfigurationSetting * after a period of time. The service maintains change history for up to 7 days. * * If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code options}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions} * * @param selector Optional. Used to filter configuration setting revisions from the service. * @return Revisions of the ConfigurationSetting */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) { return new PagedFlux<>(() -> withContext(context -> listSettingRevisionsFirstPage(selector, context)), continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context))); } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) { Mono<PagedResponse<ConfigurationSetting>> result; if (selector != null) { String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key); String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label); String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null; result = service.listKeyValueRevisions( serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector)) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector)) .doOnError( error -> logger.warning("Failed to list ConfigurationSetting revisions - {}", selector, error)); } else { result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions")) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error)); } return result; } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result; } PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new PagedFlux<>(() -> listSettingRevisionsFirstPage(selector, context), continuationToken -> listSettingRevisionsNextPage(continuationToken, context)); } private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context)); } private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings( PagedResponse<ConfigurationSetting> page, Context context) { return ImplUtils.extractAndFetch(page, context, this::listSettings); } /* * Azure Configuration service requires that the etag value is surrounded in quotation marks. * * @param etag The etag to get the value for. If null is pass in, an empty string is returned. * @return The etag surrounded by quotations. (ex. "etag") */ private static String getETagValue(String etag) { return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\""; } /* * Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL. */ private static void validateSetting(ConfigurationSetting setting) { Objects.requireNonNull(setting); if (setting.getKey() == null) { throw new IllegalArgumentException("Parameter 'key' is required and cannot be null."); } } /* * Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since * add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return * this status when the configuration doesn't exist. * * @param throwable Error response from the service. * * @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException, * otherwise the throwable is returned unmodified. */ private static Throwable addSettingExceptionMapper(Throwable throwable) { if (!(throwable instanceof ResourceNotFoundException)) { return throwable; } ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable; return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse()); } }
This needs to use justOrEmpty as the response value can be null which is an illegal value in a Reactor stream.
public Mono<ConfigurationSetting> deleteSetting(String key, String label) { return withContext( context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context)) .map(response -> response.getValue()); }
}
public Mono<ConfigurationSetting> deleteSetting(String key, String label) { return withContext( context -> deleteSetting(new ConfigurationSetting().setKey(key).setLabel(label), false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); }
class ConfigurationAsyncClient { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class); private static final String ETAG_ANY = "*"; private static final String RANGE_QUERY = "items=%s"; private final String serviceEndpoint; private final ConfigurationService service; /** * Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}. * Each service call goes through the {@code pipeline}. * * @param serviceEndpoint URL for the App Configuration service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ ConfigurationAsyncClient(URL serviceEndpoint, HttpPipeline pipeline) { this.service = RestProxy.create(ConfigurationService.class, pipeline); this.serviceEndpoint = serviceEndpoint.toString(); } /** * Adds a configuration value in the service if that key does not exist. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add, or optionally, null if a setting with * label is desired. * @param value The value associated with this configuration setting key. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If a ConfigurationSetting with the same key exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(String key, String label, String value) { return withContext( context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context)) .map(response -> response.getValue()); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param setting The setting to add to the configuration service. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)) .map(response -> response.getValue()); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse * * @param setting The setting to add to the configuration service. * @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs * or the key is an invalid value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)); } Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service .setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null, getETagValue(ETAG_ANY), context) .doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue())) .onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper) .doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error)); } /** * Creates or updates a configuration value in the service with the given key. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting * * @param key The key of the configuration setting to create or update. * @param label The label of the configuration setting to create or update, or optionally, null if a setting with * label is desired. * @param value The value of this configuration setting. * @return The {@link ConfigurationSetting} that was created or updated, if the key is an invalid value (which will * also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the setting exists and is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setSetting(String key, String label, String value) { return withContext( context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), false, context)) .map(response -> response.getValue()); } /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. * * If {@link ConfigurationSetting * setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse * * @param setting The configuration setting to create or update. * @param ifUnchanged A boolean indicates if using setting's ETag as If-Match's value. * @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an * invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value * (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If the {@link ConfigurationSetting * wildcard character, and the current configuration value's etag does not match, or the setting exists and is * locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> setSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error)); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key, String label) { return getSetting(key, label, null); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional, and the * {@code asOfDateTime} as optional. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @param asOfDateTime Datetime used to retrieve the state of the configuration at that time. If null the current * state will be retrieved asOfDateTime is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) { return withContext(context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime, false, context)).map(response -> response.getValue()); } /** * Attempts to get the ConfigurationSetting given the {@code key}, optional {@code label}, optional * {@code asOfDateTime} * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse * * @param setting The setting to retrieve based on its key and optional label combination. * @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with * asOfDateTime is desired. * @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting * If-None-Match header. * @return A REST response containing the {@link ConfigurationSetting} stored in the service, if the configuration * value does not exist or the key is an invalid value (which will also throw HttpResponseException described * below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist. * @throws HttpResponseException If the {@code} key is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean ifChanged) { return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context)); } Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean onlyIfChanged, Context context) { validateSetting(setting); final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null; return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error)); } /** * Deletes the ConfigurationSetting with a matching {@code key}. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting * * @param key The key of the setting to delete. * @param label The label of the configuration setting to delete, or optionally, null if a setting with * label is desired. * @return The deleted ConfigurationSetting or {@code null} if it didn't exist. {@code null} is also returned if the * {@code key} is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Deletes the {@link ConfigurationSetting} with a matching key, along with the given label and etag. * * If {@link ConfigurationSetting * the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the * ConfigurationSetting yet. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse * * @param setting The ConfigurationSetting to delete. * @param ifUnchanged A boolean indicator to decide using setting's ETag value as IF-MATCH value. * If false, set IF_MATCH to {@code null}. Otherwise, set the setting's ETag value to IF_MATCH. * @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null} * is also returned if the {@code key} is an invalid value or {@link ConfigurationSetting * does not match the current etag (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws NullPointerException When {@code setting} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws ResourceNotFoundException If {@link ConfigurationSetting * character, and does not match the current etag value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> deleteSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error)); } /** * Lock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly * * @param key The key of the configuration setting to lock. * @param label The label of the configuration setting to lock, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} that was locked, if a key collision occurs or the key is an invalid * value(which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setReadOnly(String key, String label) { return withContext(context -> setReadOnly( new ConfigurationSetting().setKey(key).setLabel(label), context)) .map(response -> response.getValue()); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was unlocked, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> setReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error)); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> clearReadOnly(String key, String label) { return withContext(context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context)) .map(response -> response.getValue()); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> clearReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error)); } /** * Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all * the {@link ConfigurationSetting configuration settings} are fetched with their current values. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all settings that use the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings} * * @param options Optional. Options to filter configuration setting results from the service. * @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux * contains all of the current settings in the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettings(SettingSelector options) { return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(options, context)), continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken))); } PagedFlux<ConfigurationSetting> listSettings(SettingSelector options, Context context) { return new PagedFlux<>(() -> listFirstPageSettings(options, context), continuationToken -> listNextPageSettings(context, continuationToken)); } private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } return service.listKeyValues(serviceEndpoint, continuationToken, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken, error)); } private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector options, Context context) { if (options == null) { return service.listKeyValues(serviceEndpoint, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings")) .doOnSuccess(response -> logger.info("Listed all ConfigurationSettings")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error)); } String fields = ImplUtils.arrayToString(options.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(options.getKeys(), key -> key); String labels = ImplUtils.arrayToString(options.getLabels(), label -> label); return service.listKeyValues(serviceEndpoint, keys, labels, fields, options.getAcceptDateTime(), context) .doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", options)) .doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", options)) .doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", options, error)); } /** * Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided * in descending order from their {@link ConfigurationSetting * after a period of time. The service maintains change history for up to 7 days. * * If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code options}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions} * * @param selector Optional. Used to filter configuration setting revisions from the service. * @return Revisions of the ConfigurationSetting */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) { return new PagedFlux<>(() -> withContext(context -> listSettingRevisionsFirstPage(selector, context)), continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context))); } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) { Mono<PagedResponse<ConfigurationSetting>> result; if (selector != null) { String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key); String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label); String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null; result = service.listKeyValueRevisions( serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector)) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector)) .doOnError( error -> logger.warning("Failed to list ConfigurationSetting revisions - {}", selector, error)); } else { result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions")) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error)); } return result; } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result; } PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new PagedFlux<>(() -> listSettingRevisionsFirstPage(selector, context), continuationToken -> listSettingRevisionsNextPage(continuationToken, context)); } private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context)); } private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings( PagedResponse<ConfigurationSetting> page, Context context) { return ImplUtils.extractAndFetch(page, context, this::listSettings); } /* * Azure Configuration service requires that the etag value is surrounded in quotation marks. * * @param etag The etag to get the value for. If null is pass in, an empty string is returned. * @return The etag surrounded by quotations. (ex. "etag") */ private static String getETagValue(String etag) { return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\""; } /* * Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL. */ private static void validateSetting(ConfigurationSetting setting) { Objects.requireNonNull(setting); if (setting.getKey() == null) { throw new IllegalArgumentException("Parameter 'key' is required and cannot be null."); } } /* * Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since * add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return * this status when the configuration doesn't exist. * * @param throwable Error response from the service. * * @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException, * otherwise the throwable is returned unmodified. */ private static Throwable addSettingExceptionMapper(Throwable throwable) { if (!(throwable instanceof ResourceNotFoundException)) { return throwable; } ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable; return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse()); } }
class ConfigurationAsyncClient { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClient.class); private static final String ETAG_ANY = "*"; private static final String RANGE_QUERY = "items=%s"; private final String serviceEndpoint; private final ConfigurationService service; /** * Creates a ConfigurationAsyncClient that sends requests to the configuration service at {@code serviceEndpoint}. * Each service call goes through the {@code pipeline}. * * @param serviceEndpoint URL for the App Configuration service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ ConfigurationAsyncClient(URL serviceEndpoint, HttpPipeline pipeline) { this.service = RestProxy.create(ConfigurationService.class, pipeline); this.serviceEndpoint = serviceEndpoint.toString(); } /** * Adds a configuration value in the service if that key does not exist. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add, or optionally, null if a setting with * label is desired. * @param value The value associated with this configuration setting key. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If a ConfigurationSetting with the same key exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(String key, String label, String value) { return withContext( context -> addSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSetting * * @param setting The setting to add to the configuration service. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Adds a configuration value in the service if that key and label does not exist. The label value of the * ConfigurationSetting is optional. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.addSettingWithResponse * * @param setting The setting to add to the configuration service. * @return A REST response containing the {@link ConfigurationSetting} that was created, if a key collision occurs * or the key is an invalid value (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If a ConfigurationSetting with the same key and label exists. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> addSettingWithResponse(ConfigurationSetting setting) { return withContext(context -> addSetting(setting, context)); } Mono<Response<ConfigurationSetting>> addSetting(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, null, getETagValue(ETAG_ANY), context) .doOnSubscribe(ignoredValue -> logger.info("Adding ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Added ConfigurationSetting - {}", response.getValue())) .onErrorMap(ConfigurationAsyncClient::addSettingExceptionMapper) .doOnError(error -> logger.warning("Failed to add ConfigurationSetting - {}", setting, error)); } /** * Creates or updates a configuration value in the service with the given key. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection" and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSetting * * @param key The key of the configuration setting to create or update. * @param label The label of the configuration setting to create or update, or optionally, null if a setting with * label is desired. * @param value The value of this configuration setting. * @return The {@link ConfigurationSetting} that was created or updated, if the key is an invalid value (which will * also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the setting exists and is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setSetting(String key, String label, String value) { return withContext(context -> setSetting(new ConfigurationSetting().setKey(key).setLabel(label).setValue(value), false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Creates or updates a configuration value in the service. Partial updates are not supported and the entire * configuration setting is updated. * * If {@link ConfigurationSetting * setting's etag matches. If the etag's value is equal to the wildcard character ({@code "*"}), the setting will * always be updated. * * <p><strong>Code Samples</strong></p> * * <p>Add a setting with the key "prodDBConnection", label "westUS", and value "db_connection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setSettingWithResponse * * @param setting The configuration setting to create or update. * @param ifUnchanged A boolean indicates if using setting's ETag as If-Match's value. * @return A REST response containing the {@link ConfigurationSetting} that was created or updated, if the key is an * invalid value, the setting is locked, or an etag was provided but does not match the service's current etag value * (which will also throw HttpResponseException described below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceModifiedException If the {@link ConfigurationSetting * wildcard character, and the current configuration value's etag does not match, or the setting exists and is * locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> setSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> setSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.setKey(serviceEndpoint, setting.getKey(), setting.getLabel(), setting, ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Setting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set ConfigurationSetting - {}", setting, error)); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key, String label) { return getSetting(key, label, null); } /** * Attempts to get a ConfigurationSetting that matches the {@code key}, the {@code label} as optional, and the * {@code asOfDateTime} as optional. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key "prodDBConnection" and a time that one minute before now at UTC-Zone</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSetting * * @param key The key of the setting to retrieve. * @param label The label of the configuration setting to retrieve, or optionally, null if a setting with * label is desired. * @param asOfDateTime Datetime used to retrieve the state of the configuration at that time. If null the current * state will be retrieved asOfDateTime is desired. * @return The {@link ConfigurationSetting} stored in the service, if the configuration value does not exist or the * key is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceNotFoundException If a ConfigurationSetting with {@code key} does not exist. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> getSetting(String key, String label, OffsetDateTime asOfDateTime) { return withContext(context -> getSetting(new ConfigurationSetting().setKey(key).setLabel(label), asOfDateTime, false, context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Attempts to get the ConfigurationSetting given the {@code key}, optional {@code label}, optional * {@code asOfDateTime} * * <p><strong>Code Samples</strong></p> * * <p>Retrieve the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.getSettingWithResponse * * @param setting The setting to retrieve based on its key and optional label combination. * @param asOfDateTime To access a past state of the configuration setting, or optionally, null if a setting with * asOfDateTime is desired. * @param ifChanged Flag indicating if the {@code setting} {@link ConfigurationSetting * If-None-Match header. * @return A REST response containing the {@link ConfigurationSetting} stored in the service, if the configuration * value does not exist or the key is an invalid value (which will also throw HttpResponseException described * below). * @throws NullPointerException If {@code setting} is {@code null}. * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws ResourceNotFoundException If a ConfigurationSetting with the same key and label does not exist. * @throws HttpResponseException If the {@code} key is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> getSettingWithResponse(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean ifChanged) { return withContext(context -> getSetting(setting, asOfDateTime, ifChanged, context)); } Mono<Response<ConfigurationSetting>> getSetting(ConfigurationSetting setting, OffsetDateTime asOfDateTime, boolean onlyIfChanged, Context context) { validateSetting(setting); final String ifNoneMatchETag = onlyIfChanged ? getETagValue(setting.getETag()) : null; return service.getKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, asOfDateTime == null ? null : asOfDateTime.toString(), null, ifNoneMatchETag, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Retrieved ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to get ConfigurationSetting - {}", setting, error)); } /** * Deletes the ConfigurationSetting with a matching {@code key}. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSetting * * @param key The key of the setting to delete. * @param label The label of the configuration setting to delete, or optionally, null if a setting with * label is desired. * @return The deleted ConfigurationSetting or {@code null} if it didn't exist. {@code null} is also returned if the * {@code key} is an invalid value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) /** * Deletes the {@link ConfigurationSetting} with a matching key, along with the given label and etag. * * If {@link ConfigurationSetting * the setting is <b>only</b> deleted if the etag matches the current etag; this means that no one has updated the * ConfigurationSetting yet. * * <p><strong>Code Samples</strong></p> * * <p>Delete the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.deleteSettingWithResponse * * @param setting The ConfigurationSetting to delete. * @param ifUnchanged A boolean indicator to decide using setting's ETag value as IF-MATCH value. * If false, set IF_MATCH to {@code null}. Otherwise, set the setting's ETag value to IF_MATCH. * @return A REST response containing the deleted ConfigurationSetting or {@code null} if didn't exist. {@code null} * is also returned if the {@code key} is an invalid value or {@link ConfigurationSetting * does not match the current etag (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@link ConfigurationSetting * @throws NullPointerException When {@code setting} is {@code null}. * @throws ResourceModifiedException If the ConfigurationSetting is locked. * @throws ResourceNotFoundException If {@link ConfigurationSetting * character, and does not match the current etag value. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> deleteSettingWithResponse(ConfigurationSetting setting, boolean ifUnchanged) { return withContext(context -> deleteSetting(setting, ifUnchanged, context)); } Mono<Response<ConfigurationSetting>> deleteSetting(ConfigurationSetting setting, boolean ifUnchanged, Context context) { validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; return service.delete(serviceEndpoint, setting.getKey(), setting.getLabel(), ifMatchETag, null, context) .doOnSubscribe(ignoredValue -> logger.info("Deleting ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Deleted ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to delete ConfigurationSetting - {}", setting, error)); } /** * Lock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>Lock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnly * * @param key The key of the configuration setting to lock. * @param label The label of the configuration setting to lock, or optionally, null if a setting with * label is desired. * @return The {@link ConfigurationSetting} that was locked, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> setReadOnly(String key, String label) { return withContext(context -> setReadOnly( new ConfigurationSetting().setKey(key).setLabel(label), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.setReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was unlocked, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> setReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> setReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> setReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.lockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Setting read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Set read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to set read only ConfigurationSetting - {}", setting, error)); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnly * * @param key The key of the configuration setting to add. * @param label The label of the configuration setting to add. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ConfigurationSetting> clearReadOnly(String key, String label) { return withContext(context -> clearReadOnly(new ConfigurationSetting().setKey(key).setLabel(label), context)) .flatMap(response -> Mono.justOrEmpty(response.getValue())); } /** * Unlock the {@link ConfigurationSetting} with a matching key, along with the given label. * * <p><strong>Code Samples</strong></p> * * <p>unlock the setting with the key-label "prodDBConnection"-"westUS".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.clearReadOnlyWithResponse * * @param setting The ConfigurationSetting to unlock. * @return The {@link ConfigurationSetting} that was created, if a key collision occurs or the key is an invalid * value (which will also throw HttpResponseException described below). * @throws IllegalArgumentException If {@code key} is {@code null}. * @throws HttpResponseException If {@code key} is an empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ConfigurationSetting>> clearReadOnlyWithResponse(ConfigurationSetting setting) { return withContext(context -> clearReadOnly(setting, context)); } Mono<Response<ConfigurationSetting>> clearReadOnly(ConfigurationSetting setting, Context context) { validateSetting(setting); return service.unlockKeyValue(serviceEndpoint, setting.getKey(), setting.getLabel(), null, null, context) .doOnSubscribe(ignoredValue -> logger.verbose("Clearing read only ConfigurationSetting - {}", setting)) .doOnSuccess(response -> logger.info("Cleared read only ConfigurationSetting - {}", response.getValue())) .doOnError(error -> logger.warning("Failed to clear read only ConfigurationSetting - {}", setting, error)); } /** * Fetches the configuration settings that match the {@code options}. If {@code options} is {@code null}, then all * the {@link ConfigurationSetting configuration settings} are fetched with their current values. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all settings that use the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettings} * * @param options Optional. Options to filter configuration setting results from the service. * @return A Flux of ConfigurationSettings that matches the {@code options}. If no options were provided, the Flux * contains all of the current settings in the service. */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettings(SettingSelector options) { return new PagedFlux<>(() -> withContext(context -> listFirstPageSettings(options, context)), continuationToken -> withContext(context -> listNextPageSettings(context, continuationToken))); } PagedFlux<ConfigurationSetting> listSettings(SettingSelector options, Context context) { return new PagedFlux<>(() -> listFirstPageSettings(options, context), continuationToken -> listNextPageSettings(context, continuationToken)); } private Mono<PagedResponse<ConfigurationSetting>> listNextPageSettings(Context context, String continuationToken) { if (continuationToken == null || continuationToken.isEmpty()) { return Mono.empty(); } return service.listKeyValues(serviceEndpoint, continuationToken, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", continuationToken)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", continuationToken)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", continuationToken, error)); } private Mono<PagedResponse<ConfigurationSetting>> listFirstPageSettings(SettingSelector options, Context context) { if (options == null) { return service.listKeyValues(serviceEndpoint, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing all ConfigurationSettings")) .doOnSuccess(response -> logger.info("Listed all ConfigurationSettings")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting", error)); } String fields = ImplUtils.arrayToString(options.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(options.getKeys(), key -> key); String labels = ImplUtils.arrayToString(options.getLabels(), label -> label); return service.listKeyValues(serviceEndpoint, keys, labels, fields, options.getAcceptDateTime(), context) .doOnSubscribe(ignoredValue -> logger.info("Listing ConfigurationSettings - {}", options)) .doOnSuccess(response -> logger.info("Listed ConfigurationSettings - {}", options)) .doOnError(error -> logger.warning("Failed to list ConfigurationSetting - {}", options, error)); } /** * Lists chronological/historical representation of {@link ConfigurationSetting} resource(s). Revisions are provided * in descending order from their {@link ConfigurationSetting * after a period of time. The service maintains change history for up to 7 days. * * If {@code options} is {@code null}, then all the {@link ConfigurationSetting ConfigurationSettings} are fetched * in their current state. Otherwise, the results returned match the parameters given in {@code options}. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve all revisions of the setting that has the key "prodDBConnection".</p> * * {@codesnippet com.azure.data.appconfiguration.configurationasyncclient.listsettingrevisions} * * @param selector Optional. Used to filter configuration setting revisions from the service. * @return Revisions of the ConfigurationSetting */ @ServiceMethod(returns = ReturnType.COLLECTION) public PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector) { return new PagedFlux<>(() -> withContext(context -> listSettingRevisionsFirstPage(selector, context)), continuationToken -> withContext(context -> listSettingRevisionsNextPage(continuationToken, context))); } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsFirstPage(SettingSelector selector, Context context) { Mono<PagedResponse<ConfigurationSetting>> result; if (selector != null) { String fields = ImplUtils.arrayToString(selector.getFields(), SettingFields::toStringMapper); String keys = ImplUtils.arrayToString(selector.getKeys(), key -> key); String labels = ImplUtils.arrayToString(selector.getLabels(), label -> label); String range = selector.getRange() != null ? String.format(RANGE_QUERY, selector.getRange()) : null; result = service.listKeyValueRevisions( serviceEndpoint, keys, labels, fields, selector.getAcceptDateTime(), range, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions - {}", selector)) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions - {}", selector)) .doOnError( error -> logger.warning("Failed to list ConfigurationSetting revisions - {}", selector, error)); } else { result = service.listKeyValueRevisions(serviceEndpoint, null, null, null, null, null, context) .doOnRequest(ignoredValue -> logger.info("Listing ConfigurationSetting revisions")) .doOnSuccess(response -> logger.info("Listed ConfigurationSetting revisions")) .doOnError(error -> logger.warning("Failed to list all ConfigurationSetting revisions", error)); } return result; } Mono<PagedResponse<ConfigurationSetting>> listSettingRevisionsNextPage(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result; } PagedFlux<ConfigurationSetting> listSettingRevisions(SettingSelector selector, Context context) { return new PagedFlux<>(() -> listSettingRevisionsFirstPage(selector, context), continuationToken -> listSettingRevisionsNextPage(continuationToken, context)); } private Flux<ConfigurationSetting> listSettings(String nextPageLink, Context context) { Mono<PagedResponse<ConfigurationSetting>> result = service.listKeyValues(serviceEndpoint, nextPageLink, context) .doOnSubscribe(ignoredValue -> logger.info("Retrieving the next listing page - Page {}", nextPageLink)) .doOnSuccess(response -> logger.info("Retrieved the next listing page - Page {}", nextPageLink)) .doOnError(error -> logger.warning("Failed to retrieve the next listing page - Page {}", nextPageLink, error)); return result.flatMapMany(r -> extractAndFetchConfigurationSettings(r, context)); } private Publisher<ConfigurationSetting> extractAndFetchConfigurationSettings( PagedResponse<ConfigurationSetting> page, Context context) { return ImplUtils.extractAndFetch(page, context, this::listSettings); } /* * Azure Configuration service requires that the etag value is surrounded in quotation marks. * * @param etag The etag to get the value for. If null is pass in, an empty string is returned. * @return The etag surrounded by quotations. (ex. "etag") */ private static String getETagValue(String etag) { return (etag == null || etag.equals("*")) ? etag : "\"" + etag + "\""; } /* * Ensure that setting is not null. And, key cannot be null because it is part of the service REST URL. */ private static void validateSetting(ConfigurationSetting setting) { Objects.requireNonNull(setting); if (setting.getKey() == null) { throw new IllegalArgumentException("Parameter 'key' is required and cannot be null."); } } /* * Remaps the exception returned from the service if it is a PRECONDITION_FAILED response. This is performed since * add setting returns PRECONDITION_FAILED when the configuration already exists, all other uses of setKey return * this status when the configuration doesn't exist. * * @param throwable Error response from the service. * * @return Exception remapped to a ResourceModifiedException if the throwable was a ResourceNotFoundException, * otherwise the throwable is returned unmodified. */ private static Throwable addSettingExceptionMapper(Throwable throwable) { if (!(throwable instanceof ResourceNotFoundException)) { return throwable; } ResourceNotFoundException notFoundException = (ResourceNotFoundException) throwable; return new ResourceModifiedException(notFoundException.getMessage(), notFoundException.getResponse()); } }
I don't understand what this array of size 1 is (or why it's even an array) and so I don't understand this change.
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int lastIndex = data.read(cache); currentTotalLength[0] += lastIndex; if (lastIndex < count) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error deatils: " + e.getMessage())); } }); }
if (lastIndex < count) {
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int lastIndex = data.read(cache); currentTotalLength[0] += lastIndex; if (lastIndex < count) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error deatils: " + e.getMessage())); } }); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static TreeMap<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static TreeMap<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> TreeMap<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws IllegalArgumentException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(URL baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static TreeMap<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static TreeMap<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> TreeMap<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws IllegalArgumentException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(URL baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ }
This is because we need to variable to remember the current total length. However, the lambda will complain the variable must be immutable if having something like `int sum`. This is the best way of recording the current length in lambda, based on the discussion with team and @anuchandy The fix here is to compare the chunk we currently process, so it should compare the reading bytes and the expected to have for the chunk, not the currentTotalLength.
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int lastIndex = data.read(cache); currentTotalLength[0] += lastIndex; if (lastIndex < count) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error deatils: " + e.getMessage())); } }); }
if (lastIndex < count) {
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int lastIndex = data.read(cache); currentTotalLength[0] += lastIndex; if (lastIndex < count) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error deatils: " + e.getMessage())); } }); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static TreeMap<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static TreeMap<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> TreeMap<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws IllegalArgumentException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(URL baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static TreeMap<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static TreeMap<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> TreeMap<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws IllegalArgumentException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(URL baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ }
Why `.getClass()` versus just printing the object?
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get().getClass()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: {} %s%n", (String) updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: {} %s%n", updatedProcessContext.getData("scope").get().getClass()); }
updatedContext.getData(OPENCENSUS_SPAN_KEY).get().getClass());
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get().toString()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get()); }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", (String) context.getData(OPENCENSUS_SPAN_NAME_KEY).get()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", context.getData(OPENCENSUS_SPAN_NAME_KEY).get().toString()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
Do you need to cast it to (String)? It'll do a .toString() on whatever object is returned from DIAGNOSTIC_ID_KEY.
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get().getClass()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: {} %s%n", (String) updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: {} %s%n", updatedProcessContext.getData("scope").get().getClass()); }
System.out.printf("Diagnostic Id: {} %s%n", (String) updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get());
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get().toString()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get()); }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", (String) context.getData(OPENCENSUS_SPAN_NAME_KEY).get()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", context.getData(OPENCENSUS_SPAN_NAME_KEY).get().toString()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
The {} placeholders are not required. This is only for slf4j
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get().getClass()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: {} %s%n", (String) updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: {} %s%n", updatedProcessContext.getData("scope").get().getClass()); }
System.out.printf("Diagnostic Id: {} %s%n", (String) updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get());
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get().toString()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get()); }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", (String) context.getData(OPENCENSUS_SPAN_NAME_KEY).get()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", context.getData(OPENCENSUS_SPAN_NAME_KEY).get().toString()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
{} is not required. Do you need .getClass?
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get().getClass()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: {} %s%n", (String) updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: {} %s%n", updatedProcessContext.getData("scope").get().getClass()); }
System.out.printf("Scope: {} %s%n", updatedProcessContext.getData("scope").get().getClass());
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get().toString()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get()); }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", (String) context.getData(OPENCENSUS_SPAN_NAME_KEY).get()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", context.getData(OPENCENSUS_SPAN_NAME_KEY).get().toString()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
I was just doing that to use the returned object and avoid one of our checkstyle issues. And thought printing object won't return much information, so..
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get().getClass()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: {} %s%n", (String) updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: {} %s%n", updatedProcessContext.getData("scope").get().getClass()); }
System.out.printf("Scope: {} %s%n", updatedProcessContext.getData("scope").get().getClass());
public void startTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context updatedContext = tracer.start("azure.keyvault.secrets/setsecret", traceContext); System.out.printf("Span returned in the context object: %s%n", updatedContext.getData(OPENCENSUS_SPAN_KEY).get()); Context sendContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(ENTITY_PATH, "entity-path").addData(HOST_NAME, "hostname"); Context updatedSendContext = tracer.start("azure.eventhubs.send", sendContext, ProcessKind.SEND); System.out.printf("Span returned in the context object: %s%n", updatedSendContext.getData(OPENCENSUS_SPAN_KEY).get()); Context updatedReceiveContext = tracer.start("azure.eventhubs.receive", traceContext, ProcessKind.RECEIVE); System.out.printf("Diagnostic Id: %s%n", updatedReceiveContext.getData(DIAGNOSTIC_ID_KEY).get().toString()); Context processContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>") .addData(SPAN_CONTEXT, "<user-current-span-context>"); Context updatedProcessContext = tracer.start("azure.eventhubs.process", processContext, ProcessKind.PROCESS); System.out.printf("Scope: %s%n", updatedProcessContext.getData("scope").get()); }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", (String) context.getData(OPENCENSUS_SPAN_NAME_KEY).get()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
class TracerJavaDocCodeSnippets { final Tracer tracer = new TracerImplementation(); /** * Code snippet for {@link Tracer */ /** * Code snippet for {@link Tracer */ public void endTracingSpan() { Context traceContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); tracer.end(200, null, traceContext); tracer.end("success", null, traceContext); } /** * Code snippet for {@link Tracer */ public void setSpanName() { Context context = tracer.setSpanName("test-span-method", Context.NONE); System.out.printf("Span name: %s%n", context.getData(OPENCENSUS_SPAN_NAME_KEY).get().toString()); } /** * Code snippet for {@link Tracer */ public void addLink() { Context parentContext = new Context(OPENCENSUS_SPAN_KEY, "<user-current-span>"); Context spanContext = tracer.start("test.method", parentContext, ProcessKind.RECEIVE); tracer.addLink(spanContext); } /** * Code snippet for {@link Tracer */ public void extractContext() { Context spanContext = tracer.extractContext("valid-diagnostic-id", Context.NONE); System.out.printf("Span context of the current tracing span: %s%n", spanContext.getData(SPAN_CONTEXT).get()); } private static final class TracerImplementation implements Tracer { @Override public Context start(String methodName, Context context) { return null; } @Override public Context start(String methodName, Context context, ProcessKind processKind) { return null; } @Override public void end(int responseCode, Throwable error, Context context) { } @Override public void end(String errorCondition, Throwable error, Context context) { } @Override public void setAttribute(String key, String value, Context context) { } @Override public Context setSpanName(String spanName, Context context) { return null; } @Override public void addLink(Context context) { } @Override public Context extractContext(String diagnosticId, Context context) { return null; } } }
Should make a check that there are no query parameters already attached to the URL, maybe check for a `?` as I believe that is a reserved URL character.
public String getBlobUrl() { if (!this.isSnapshot()) { return azureBlobStorage.getUrl(); } else { return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot); } }
return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot);
public String getBlobUrl() { if (!this.isSnapshot()) { return azureBlobStorage.getUrl(); } else { if (azureBlobStorage.getUrl().contains("?")) { return String.format("%s&snapshot=%s", azureBlobStorage.getUrl(), snapshot); } else { return String.format("%s?snapshot=%s", azureBlobStorage.getUrl(), snapshot); } } }
class BlobAsyncClientBase { private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB; private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB; private final ClientLogger logger = new ClientLogger(BlobAsyncClientBase.class); protected final AzureBlobStorageImpl azureBlobStorage; private final String snapshot; private final CpkInfo customerProvidedKey; /** * Package-private constructor for use by {@link SpecializedBlobClientBuilder}. * * @param azureBlobStorage the API client for blob storage * @param snapshot Optional. The snapshot identifier for the snapshot blob. * @param customerProvidedKey Optional. Customer provided key used during encryption of the blob's data on the * server. */ protected BlobAsyncClientBase(AzureBlobStorageImpl azureBlobStorage, String snapshot, CpkInfo customerProvidedKey) { this.azureBlobStorage = azureBlobStorage; this.snapshot = snapshot; this.customerProvidedKey = customerProvidedKey; } /** * Creates a new {@link BlobAsyncClientBase} linked to the {@code snapshot} of this blob resource. * * @param snapshot the identifier for a specific snapshot of this blob * @return a {@link BlobAsyncClientBase} used to interact with the specific snapshot. */ public BlobAsyncClientBase getSnapshotClient(String snapshot) { return new BlobAsyncClientBase(new AzureBlobStorageBuilder() .url(getBlobUrl()) .pipeline(azureBlobStorage.getHttpPipeline()) .build(), snapshot, customerProvidedKey); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return BlobURLParts.parse(this.azureBlobStorage.getUrl(), logger).getContainerName(); } /** * Get the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName} * * @return The name of the blob. */ public final String getBlobName() { return BlobURLParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return azureBlobStorage.getHttpPipeline(); } /** * Gets the {@link CpkInfo} used to encrypt this blob's content on the server. * * @return the customer provided key used for encryption. */ public CpkInfo getCustomerProvidedKey() { return customerProvidedKey; } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return this.snapshot; } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return this.snapshot != null; } /** * Determines if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.exists} * * @return true if the blob exists, false if it doesn't */ public Mono<Boolean> exists() { return existsWithResponse().flatMap(FluxUtil::toMono); } /** * Determines if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse} * * @return true if the blob exists, false if it doesn't */ public Mono<Response<Boolean>> existsWithResponse() { return withContext(this::existsWithResponse); } Mono<Response<Boolean>> existsWithResponse(Context context) { return this.getPropertiesWithResponse(null, context) .map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true)) .onErrorResume(t -> t instanceof StorageException && ((StorageException) t).getStatusCode() == 404, t -> { HttpResponse response = ((StorageException) t).getResponse(); return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false)); }); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.startCopyFromURL * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @return A reactive response containing the copy ID for the long running operation. */ public Mono<String> startCopyFromURL(URL sourceURL) { return startCopyFromURLWithResponse(sourceURL, null, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.startCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata Metadata to associate with the destination blob. * @param tier {@link AccessTier} for the destination blob. * @param priority {@link RehydratePriority} for rehydrating the blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @return A reactive response containing the copy ID for the long running operation. */ public Mono<Response<String>> startCopyFromURLWithResponse(URL sourceURL, Map<String, String> metadata, AccessTier tier, RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions) { return withContext(context -> startCopyFromURLWithResponse(sourceURL, metadata, tier, priority, sourceModifiedAccessConditions, destAccessConditions, context)); } Mono<Response<String>> startCopyFromURLWithResponse(URL sourceURL, Map<String, String> metadata, AccessTier tier, RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Context context) { sourceModifiedAccessConditions = sourceModifiedAccessConditions == null ? new ModifiedAccessConditions() : sourceModifiedAccessConditions; destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions; SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions() .setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince()) .setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince()) .setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch()) .setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch()); return postProcessResponse(this.azureBlobStorage.blobs().startCopyFromURLWithRestResponseAsync( null, null, sourceURL, null, metadata, tier, priority, null, sourceConditions, destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(), context)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId())); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURL * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. * @return A reactive response signalling completion. */ public Mono<Void> abortCopyFromURL(String copyId) { return abortCopyFromURLWithResponse(copyId, null).flatMap(FluxUtil::toMono); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @return A reactive response signalling completion. */ public Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions) { return withContext(context -> abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context)); } Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions, Context context) { return postProcessResponse(this.azureBlobStorage.blobs().abortCopyFromURLWithRestResponseAsync( null, null, copyId, null, null, leaseAccessConditions, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURL * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. * @return A reactive response containing the copy ID for the long running operation. */ public Mono<String> copyFromURL(URL copySource) { return copyFromURLWithResponse(copySource, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata Metadata to associate with the destination blob. * @param tier {@link AccessTier} for the destination blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @return A reactive response containing the copy ID for the long running operation. */ public Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions) { return withContext(context -> copyFromURLWithResponse(copySource, metadata, tier, sourceModifiedAccessConditions, destAccessConditions, context)); } Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Context context) { sourceModifiedAccessConditions = sourceModifiedAccessConditions == null ? new ModifiedAccessConditions() : sourceModifiedAccessConditions; destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions; SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions() .setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince()) .setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince()) .setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch()) .setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch()); return postProcessResponse(this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync( null, null, copySource, null, metadata, tier, null, sourceConditions, destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(), context)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId())); } /** * Reads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or * {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.download} * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the blob data. */ public Flux<ByteBuffer> download() { return downloadWithResponse(null, null, null, false) .flatMapMany(Response::getValue); } /** * Reads a range of bytes from a blob. Uploading data must be done from the {@link BlockBlobClient}, {@link * PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse * * <p>For more information, see the * <a href="https: * * @param range {@link BlobRange} * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @return A reactive response containing the blob data. */ public Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5) { return withContext(context -> downloadWithResponse(range, options, accessConditions, rangeGetContentMD5, context)); } Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) { return download(range, accessConditions, rangeGetContentMD5, context) .map(response -> new SimpleResponse<>( response.getRawResponse(), response.body(options).switchIfEmpty(Flux.just(ByteBuffer.wrap(new byte[0]))))); } /** * Reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more * information, see the <a href="https: * <p> * Note that the response body has reliable download functionality built in, meaning that a failed download stream * will be automatically retried. This behavior may be configured with {@link ReliableDownloadOptions}. * * @param range {@link BlobRange} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @return Emits the successful response. */ Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions, boolean rangeGetContentMD5) { return withContext(context -> download(range, accessConditions, rangeGetContentMD5, context)); } Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) { range = range == null ? new BlobRange(0) : range; Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null; accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; HTTPGetterInfo info = new HTTPGetterInfo() .setOffset(range.getOffset()) .setCount(range.getCount()) .setETag(accessConditions.getModifiedAccessConditions().getIfMatch()); return postProcessResponse(this.azureBlobStorage.blobs().downloadWithRestResponseAsync( null, null, snapshot, null, range.toHeaderValue(), getMD5, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey, accessConditions.getModifiedAccessConditions(), context)) .map(response -> { info.setETag(response.getDeserializedHeaders().getETag()); return new DownloadAsyncResponse(response, info, newInfo -> this.download(new BlobRange(newInfo.getOffset(), newInfo.getCount()), new BlobAccessConditions().setModifiedAccessConditions( new ModifiedAccessConditions().setIfMatch(info.getETag())), false, context)); }); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @return An empty response */ public Mono<BlobProperties> downloadToFile(String filePath) { return downloadToFileWithResponse(filePath, null, null, null, null, false).flatMap(FluxUtil::toMono); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra * call, provide the {@link BlobRange} parameter.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @return An empty response * @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB. * @throws UncheckedIOException If an I/O error occurs. */ public Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5) { return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options, accessConditions, rangeGetContentMD5, context)); } Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) { final ParallelTransferOptions finalParallelTransferOptions = parallelTransferOptions == null ? new ParallelTransferOptions() : parallelTransferOptions; return Mono.using(() -> downloadToFileResourceSupplier(filePath), channel -> getPropertiesWithResponse(accessConditions).flatMap(response -> processInRange(channel, response, range, finalParallelTransferOptions.getBlockSize(), options, accessConditions, rangeGetContentMD5, context)), this::downloadToFileCleanup); } private Mono<Response<BlobProperties>> processInRange(AsynchronousFileChannel channel, Response<BlobProperties> blobPropertiesResponse, BlobRange range, Integer blockSize, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) { return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new BlobRange(0, blobPropertiesResponse.getValue().getBlobSize()))).flatMapMany(rg -> Flux.fromIterable(sliceBlobRange(rg, blockSize))) .flatMap(chunk -> this.download(chunk, accessConditions, rangeGetContentMD5, context) .subscribeOn(Schedulers.elastic()) .flatMap(dar -> FluxUtil.writeFile(dar.body(options), channel, chunk.getOffset() - ((range == null) ? 0 : range.getOffset())) )).then(Mono.just(blobPropertiesResponse)); } private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) { try { return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private void downloadToFileCleanup(AsynchronousFileChannel channel) { try { channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private List<BlobRange> sliceBlobRange(BlobRange blobRange, Integer blockSize) { if (blockSize == null) { blockSize = BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE; } long offset = blobRange.getOffset(); long length = blobRange.getCount(); List<BlobRange> chunks = new ArrayList<>(); for (long pos = offset; pos < offset + length; pos += blockSize) { long count = blockSize; if (pos + count > offset + length) { count = offset + length - pos; } chunks.add(new BlobRange(pos, count)); } return chunks; } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.delete} * * <p>For more information, see the * <a href="https: * * @return A reactive response signalling completion. */ public Mono<Void> delete() { return deleteWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param accessConditions {@link BlobAccessConditions} * @return A reactive response signalling completion. */ public Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobAccessConditions accessConditions) { return withContext(context -> deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context)); } Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().deleteWithRestResponseAsync( null, null, snapshot, null, deleteBlobSnapshotOptions, null, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the blob properties and metadata. */ public Mono<BlobProperties> getProperties() { return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param accessConditions {@link BlobAccessConditions} * @return A reactive response containing the blob properties and metadata. */ public Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions) { return withContext(context -> getPropertiesWithResponse(accessConditions, context)); } Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().getPropertiesWithRestResponseAsync( null, null, snapshot, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey, accessConditions.getModifiedAccessConditions(), context)) .map(rb -> new SimpleResponse<>(rb, new BlobProperties(rb.getDeserializedHeaders()))); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} * @return A reactive response signalling completion. */ public Mono<Void> setHTTPHeaders(BlobHTTPHeaders headers) { return setHTTPHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} * @param accessConditions {@link BlobAccessConditions} * @return A reactive response signalling completion. */ public Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions) { return withContext(context -> setHTTPHeadersWithResponse(headers, accessConditions, context)); } Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().setHTTPHeadersWithRestResponseAsync( null, null, null, null, headers, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. * @return A reactive response signalling completion. */ public Mono<Void> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. * @param accessConditions {@link BlobAccessConditions} * @return A reactive response signalling completion. */ public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions) { return withContext(context -> setMetadataWithResponse(metadata, accessConditions, context)); } Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().setMetadataWithRestResponseAsync( null, null, null, metadata, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey, accessConditions.getModifiedAccessConditions(), context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot} * * <p>For more information, see the * <a href="https: * * @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot, * use {@link */ public Mono<BlobAsyncClientBase> createSnapshot() { return createSnapshotWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob snapshot. * @param accessConditions {@link BlobAccessConditions} * @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot, * use {@link */ public Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions) { return withContext(context -> createSnapshotWithResponse(metadata, accessConditions, context)); } Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().createSnapshotWithRestResponseAsync( null, null, null, metadata, null, customerProvidedKey, accessConditions.getModifiedAccessConditions(), accessConditions.getLeaseAccessConditions(), context)) .map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.getDeserializedHeaders().getSnapshot()))); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @return A reactive response signalling completion. */ public Mono<Void> setAccessTier(AccessTier tier) { return setAccessTierWithResponse(tier, null, null).flatMap(FluxUtil::toMono); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @param priority Optional priority to set for re-hydrating blobs. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @return A reactive response signalling completion. */ public Mono<Response<Void>> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority, LeaseAccessConditions leaseAccessConditions) { return withContext(context -> setTierWithResponse(tier, priority, leaseAccessConditions, context)); } Mono<Response<Void>> setTierWithResponse(AccessTier tier, RehydratePriority priority, LeaseAccessConditions leaseAccessConditions, Context context) { Utility.assertNotNull("tier", tier); return postProcessResponse(this.azureBlobStorage.blobs().setTierWithRestResponseAsync( null, null, tier, null, priority, null, leaseAccessConditions, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete} * * <p>For more information, see the * <a href="https: * * @return A reactive response signalling completion. */ public Mono<Void> undelete() { return undeleteWithResponse().flatMap(FluxUtil::toMono); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse} * * <p>For more information, see the * <a href="https: * * @return A reactive response signalling completion. */ public Mono<Response<Void>> undeleteWithResponse() { return withContext(this::undeleteWithResponse); } Mono<Response<Void>> undeleteWithResponse(Context context) { return postProcessResponse(this.azureBlobStorage.blobs().undeleteWithRestResponseAsync(null, null, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return a reactor response containing the sku name and account kind. */ public Mono<StorageAccountInfo> getAccountInfo() { return getAccountInfoWithResponse().flatMap(FluxUtil::toMono); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse} * * <p>For more information, see the * <a href="https: * * @return a reactor response containing the sku name and account kind. */ public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() { return withContext(this::getAccountInfoWithResponse); } Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) { return postProcessResponse( this.azureBlobStorage.blobs().getAccountInfoWithRestResponseAsync(null, null, context)) .map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.getDeserializedHeaders()))); } /** * Generates a user delegation SAS with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code ContainerSASPermissions} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime) { return this.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, null /* startTime */, null /* version */, null /*sasProtocol */, null /* ipRange */, null /* cacheControl */, null /*contentDisposition */, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code ContainerSASPermissions} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange, null /* cacheControl */, null /* contentDisposition */, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a user delegation SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSAS * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { BlobServiceSASSignatureValues blobServiceSASSignatureValues = new BlobServiceSASSignatureValues(version, sasProtocol, startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange, null /* identifier*/, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); BlobServiceSASSignatureValues values = configureServiceSASSignatureValues(blobServiceSASSignatureValues, accountName); BlobServiceSASQueryParameters blobServiceSasQueryParameters = values.generateSASQueryParameters(userDelegationKey); return blobServiceSasQueryParameters.encode(); } /** * Generates a SAS token with the specified parameters * * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @return A string that represents the SAS token */ public String generateSAS(BlobSASPermission permissions, OffsetDateTime expiryTime) { return this.generateSAS(null, permissions, expiryTime, null /* startTime */, /* identifier */ null /* version */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null /* contentLanguage*/, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @return A string that represents the SAS token */ public String generateSAS(String identifier) { return this.generateSAS(identifier, null /* permissions */, null /* expiryTime */, null /* startTime */, null /* version */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null /* contentLanguage*/, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange, null /* cacheControl */, null /* contentLanguage*/, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSAS * * <p>For more information, see the * <a href="https: * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateSAS(String identifier, BlobSASPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { BlobServiceSASSignatureValues blobServiceSASSignatureValues = new BlobServiceSASSignatureValues(version, sasProtocol, startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange, identifier, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); SharedKeyCredential sharedKeyCredential = Utility.getSharedKeyCredential(this.azureBlobStorage.getHttpPipeline()); Utility.assertNotNull("sharedKeyCredential", sharedKeyCredential); BlobServiceSASSignatureValues values = configureServiceSASSignatureValues(blobServiceSASSignatureValues, sharedKeyCredential.getAccountName()); BlobServiceSASQueryParameters blobServiceSasQueryParameters = values.generateSASQueryParameters(sharedKeyCredential); return blobServiceSasQueryParameters.encode(); } /** * Sets blobServiceSASSignatureValues parameters dependent on the current blob type */ private BlobServiceSASSignatureValues configureServiceSASSignatureValues( BlobServiceSASSignatureValues blobServiceSASSignatureValues, String accountName) { blobServiceSASSignatureValues.setCanonicalName(this.azureBlobStorage.getUrl(), accountName); blobServiceSASSignatureValues.setSnapshotId(getSnapshotId()); if (isSnapshot()) { blobServiceSASSignatureValues.setResource(Constants.UrlConstants.SAS_BLOB_SNAPSHOT_CONSTANT); } else { blobServiceSASSignatureValues.setResource(Constants.UrlConstants.SAS_BLOB_CONSTANT); } return blobServiceSASSignatureValues; } }
class BlobAsyncClientBase { private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB; private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB; private final ClientLogger logger = new ClientLogger(BlobAsyncClientBase.class); protected final AzureBlobStorageImpl azureBlobStorage; private final String snapshot; private final CpkInfo customerProvidedKey; /** * Package-private constructor for use by {@link SpecializedBlobClientBuilder}. * * @param azureBlobStorage the API client for blob storage * @param snapshot Optional. The snapshot identifier for the snapshot blob. * @param customerProvidedKey Optional. Customer provided key used during encryption of the blob's data on the * server. */ protected BlobAsyncClientBase(AzureBlobStorageImpl azureBlobStorage, String snapshot, CpkInfo customerProvidedKey) { this.azureBlobStorage = azureBlobStorage; this.snapshot = snapshot; this.customerProvidedKey = customerProvidedKey; } /** * Creates a new {@link BlobAsyncClientBase} linked to the {@code snapshot} of this blob resource. * * @param snapshot the identifier for a specific snapshot of this blob * @return a {@link BlobAsyncClientBase} used to interact with the specific snapshot. */ public BlobAsyncClientBase getSnapshotClient(String snapshot) { return new BlobAsyncClientBase(new AzureBlobStorageBuilder() .url(getBlobUrl()) .pipeline(azureBlobStorage.getHttpPipeline()) .build(), snapshot, customerProvidedKey); } /** * Gets the URL of the blob represented by this client. * * @return the URL. */ /** * Get the container name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getContainerName} * * @return The name of the container. */ public final String getContainerName() { return BlobURLParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobContainerName(); } /** * Get the blob name. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getBlobName} * * @return The name of the blob. */ public final String getBlobName() { return BlobURLParts.parse(this.azureBlobStorage.getUrl(), logger).getBlobName(); } /** * Gets the {@link HttpPipeline} powering this client. * * @return The pipeline. */ public HttpPipeline getHttpPipeline() { return azureBlobStorage.getHttpPipeline(); } /** * Gets the {@link CpkInfo} used to encrypt this blob's content on the server. * * @return the customer provided key used for encryption. */ public CpkInfo getCustomerProvidedKey() { return customerProvidedKey; } /** * Gets the snapshotId for a blob resource * * @return A string that represents the snapshotId of the snapshot blob */ public String getSnapshotId() { return this.snapshot; } /** * Determines if a blob is a snapshot * * @return A boolean that indicates if a blob is a snapshot */ public boolean isSnapshot() { return this.snapshot != null; } /** * Determines if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.exists} * * @return true if the blob exists, false if it doesn't */ public Mono<Boolean> exists() { return existsWithResponse().flatMap(FluxUtil::toMono); } /** * Determines if the blob this client represents exists in the cloud. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.existsWithResponse} * * @return true if the blob exists, false if it doesn't */ public Mono<Response<Boolean>> existsWithResponse() { return withContext(this::existsWithResponse); } Mono<Response<Boolean>> existsWithResponse(Context context) { return this.getPropertiesWithResponse(null, context) .map(cp -> (Response<Boolean>) new SimpleResponse<>(cp, true)) .onErrorResume(t -> t instanceof StorageException && ((StorageException) t).getStatusCode() == 404, t -> { HttpResponse response = ((StorageException) t).getResponse(); return Mono.just(new SimpleResponse<>(response.getRequest(), response.getStatusCode(), response.getHeaders(), false)); }); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.startCopyFromURL * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @return A reactive response containing the copy ID for the long running operation. */ public Mono<String> startCopyFromURL(URL sourceURL) { return startCopyFromURLWithResponse(sourceURL, null, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Copies the data at the source URL to a blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.startCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceURL The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata Metadata to associate with the destination blob. * @param tier {@link AccessTier} for the destination blob. * @param priority {@link RehydratePriority} for rehydrating the blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @return A reactive response containing the copy ID for the long running operation. */ public Mono<Response<String>> startCopyFromURLWithResponse(URL sourceURL, Map<String, String> metadata, AccessTier tier, RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions) { return withContext(context -> startCopyFromURLWithResponse(sourceURL, metadata, tier, priority, sourceModifiedAccessConditions, destAccessConditions, context)); } Mono<Response<String>> startCopyFromURLWithResponse(URL sourceURL, Map<String, String> metadata, AccessTier tier, RehydratePriority priority, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Context context) { sourceModifiedAccessConditions = sourceModifiedAccessConditions == null ? new ModifiedAccessConditions() : sourceModifiedAccessConditions; destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions; SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions() .setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince()) .setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince()) .setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch()) .setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch()); return postProcessResponse(this.azureBlobStorage.blobs().startCopyFromURLWithRestResponseAsync( null, null, sourceURL, null, metadata, tier, priority, null, sourceConditions, destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(), context)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId())); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURL * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. * @return A reactive response signalling completion. */ public Mono<Void> abortCopyFromURL(String copyId) { return abortCopyFromURLWithResponse(copyId, null).flatMap(FluxUtil::toMono); } /** * Stops a pending copy that was previously started and leaves a destination blob with 0 length and metadata. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.abortCopyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId The id of the copy operation to abort. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @return A reactive response signalling completion. */ public Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions) { return withContext(context -> abortCopyFromURLWithResponse(copyId, leaseAccessConditions, context)); } Mono<Response<Void>> abortCopyFromURLWithResponse(String copyId, LeaseAccessConditions leaseAccessConditions, Context context) { return postProcessResponse(this.azureBlobStorage.blobs().abortCopyFromURLWithRestResponseAsync( null, null, copyId, null, null, leaseAccessConditions, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURL * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. * @return A reactive response containing the copy ID for the long running operation. */ public Mono<String> copyFromURL(URL copySource) { return copyFromURLWithResponse(copySource, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Copies the data at the source URL to a blob and waits for the copy to complete before returning a response. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.copyFromURLWithResponse * * <p>For more information, see the * <a href="https: * * @param copySource The source URL to copy from. URLs outside of Azure may only be copied to block blobs. * @param metadata Metadata to associate with the destination blob. * @param tier {@link AccessTier} for the destination blob. * @param sourceModifiedAccessConditions {@link ModifiedAccessConditions} against the source. Standard HTTP Access * conditions related to the modification of data. ETag and LastModifiedTime are used to construct conditions * related to when the blob was changed relative to the given request. The request will fail if the specified * condition is not satisfied. * @param destAccessConditions {@link BlobAccessConditions} against the destination. * @return A reactive response containing the copy ID for the long running operation. */ public Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions) { return withContext(context -> copyFromURLWithResponse(copySource, metadata, tier, sourceModifiedAccessConditions, destAccessConditions, context)); } Mono<Response<String>> copyFromURLWithResponse(URL copySource, Map<String, String> metadata, AccessTier tier, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Context context) { sourceModifiedAccessConditions = sourceModifiedAccessConditions == null ? new ModifiedAccessConditions() : sourceModifiedAccessConditions; destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions; SourceModifiedAccessConditions sourceConditions = new SourceModifiedAccessConditions() .setSourceIfModifiedSince(sourceModifiedAccessConditions.getIfModifiedSince()) .setSourceIfUnmodifiedSince(sourceModifiedAccessConditions.getIfUnmodifiedSince()) .setSourceIfMatch(sourceModifiedAccessConditions.getIfMatch()) .setSourceIfNoneMatch(sourceModifiedAccessConditions.getIfNoneMatch()); return postProcessResponse(this.azureBlobStorage.blobs().copyFromURLWithRestResponseAsync( null, null, copySource, null, metadata, tier, null, sourceConditions, destAccessConditions.getModifiedAccessConditions(), destAccessConditions.getLeaseAccessConditions(), context)) .map(rb -> new SimpleResponse<>(rb, rb.getDeserializedHeaders().getCopyId())); } /** * Reads the entire blob. Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or * {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.download} * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the blob data. */ public Flux<ByteBuffer> download() { return downloadWithResponse(null, null, null, false) .flatMapMany(Response::getValue); } /** * Reads a range of bytes from a blob. Uploading data must be done from the {@link BlockBlobClient}, {@link * PageBlobClient}, or {@link AppendBlobClient}. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadWithResponse * * <p>For more information, see the * <a href="https: * * @param range {@link BlobRange} * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @return A reactive response containing the blob data. */ public Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5) { return withContext(context -> downloadWithResponse(range, options, accessConditions, rangeGetContentMD5, context)); } Mono<Response<Flux<ByteBuffer>>> downloadWithResponse(BlobRange range, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) { return download(range, accessConditions, rangeGetContentMD5, context) .map(response -> new SimpleResponse<>( response.getRawResponse(), response.body(options).switchIfEmpty(Flux.just(ByteBuffer.wrap(new byte[0]))))); } /** * Reads a range of bytes from a blob. The response also includes the blob's properties and metadata. For more * information, see the <a href="https: * <p> * Note that the response body has reliable download functionality built in, meaning that a failed download stream * will be automatically retried. This behavior may be configured with {@link ReliableDownloadOptions}. * * @param range {@link BlobRange} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @return Emits the successful response. */ Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions, boolean rangeGetContentMD5) { return withContext(context -> download(range, accessConditions, rangeGetContentMD5, context)); } Mono<DownloadAsyncResponse> download(BlobRange range, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) { range = range == null ? new BlobRange(0) : range; Boolean getMD5 = rangeGetContentMD5 ? rangeGetContentMD5 : null; accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; HTTPGetterInfo info = new HTTPGetterInfo() .setOffset(range.getOffset()) .setCount(range.getCount()) .setETag(accessConditions.getModifiedAccessConditions().getIfMatch()); return postProcessResponse(this.azureBlobStorage.blobs().downloadWithRestResponseAsync( null, null, snapshot, null, range.toHeaderValue(), getMD5, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey, accessConditions.getModifiedAccessConditions(), context)) .map(response -> { info.setETag(response.getDeserializedHeaders().getETag()); return new DownloadAsyncResponse(response, info, newInfo -> this.download(new BlobRange(newInfo.getOffset(), newInfo.getCount()), new BlobAccessConditions().setModifiedAccessConditions( new ModifiedAccessConditions().setIfMatch(info.getETag())), false, context)); }); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @return An empty response */ public Mono<BlobProperties> downloadToFile(String filePath) { return downloadToFileWithResponse(filePath, null, null, null, null, false).flatMap(FluxUtil::toMono); } /** * Downloads the entire blob into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p>Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link * AppendBlobClient}.</p> * * <p>This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra * call, provide the {@link BlobRange} parameter.</p> * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. * @param range {@link BlobRange} * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel * transfers parameter is ignored. * @param options {@link ReliableDownloadOptions} * @param accessConditions {@link BlobAccessConditions} * @param rangeGetContentMD5 Whether the contentMD5 for the specified blob range should be returned. * @return An empty response * @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB. * @throws UncheckedIOException If an I/O error occurs. */ public Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5) { return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options, accessConditions, rangeGetContentMD5, context)); } Mono<Response<BlobProperties>> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) { final ParallelTransferOptions finalParallelTransferOptions = parallelTransferOptions == null ? new ParallelTransferOptions() : parallelTransferOptions; return Mono.using(() -> downloadToFileResourceSupplier(filePath), channel -> getPropertiesWithResponse(accessConditions).flatMap(response -> processInRange(channel, response, range, finalParallelTransferOptions.getBlockSize(), options, accessConditions, rangeGetContentMD5, context)), this::downloadToFileCleanup); } private Mono<Response<BlobProperties>> processInRange(AsynchronousFileChannel channel, Response<BlobProperties> blobPropertiesResponse, BlobRange range, Integer blockSize, ReliableDownloadOptions options, BlobAccessConditions accessConditions, boolean rangeGetContentMD5, Context context) { return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new BlobRange(0, blobPropertiesResponse.getValue().getBlobSize()))).flatMapMany(rg -> Flux.fromIterable(sliceBlobRange(rg, blockSize))) .flatMap(chunk -> this.download(chunk, accessConditions, rangeGetContentMD5, context) .subscribeOn(Schedulers.elastic()) .flatMap(dar -> FluxUtil.writeFile(dar.body(options), channel, chunk.getOffset() - ((range == null) ? 0 : range.getOffset())) )).then(Mono.just(blobPropertiesResponse)); } private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) { try { return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private void downloadToFileCleanup(AsynchronousFileChannel channel) { try { channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private List<BlobRange> sliceBlobRange(BlobRange blobRange, Integer blockSize) { if (blockSize == null) { blockSize = BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE; } long offset = blobRange.getOffset(); long length = blobRange.getCount(); List<BlobRange> chunks = new ArrayList<>(); for (long pos = offset; pos < offset + length; pos += blockSize) { long count = blockSize; if (pos + count > offset + length) { count = offset + length - pos; } chunks.add(new BlobRange(pos, count)); } return chunks; } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.delete} * * <p>For more information, see the * <a href="https: * * @return A reactive response signalling completion. */ public Mono<Void> delete() { return deleteWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Deletes the specified blob or snapshot. Note that deleting a blob also deletes all its snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.deleteWithResponse * * <p>For more information, see the * <a href="https: * * @param deleteBlobSnapshotOptions Specifies the behavior for deleting the snapshots on this blob. {@code Include} * will delete the base blob and all snapshots. {@code Only} will delete only the snapshots. If a snapshot is being * deleted, you must pass null. * @param accessConditions {@link BlobAccessConditions} * @return A reactive response signalling completion. */ public Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobAccessConditions accessConditions) { return withContext(context -> deleteWithResponse(deleteBlobSnapshotOptions, accessConditions, context)); } Mono<Response<Void>> deleteWithResponse(DeleteSnapshotsOptionType deleteBlobSnapshotOptions, BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().deleteWithRestResponseAsync( null, null, snapshot, null, deleteBlobSnapshotOptions, null, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getProperties} * * <p>For more information, see the * <a href="https: * * @return A reactive response containing the blob properties and metadata. */ public Mono<BlobProperties> getProperties() { return getPropertiesWithResponse(null).flatMap(FluxUtil::toMono); } /** * Returns the blob's metadata and properties. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param accessConditions {@link BlobAccessConditions} * @return A reactive response containing the blob properties and metadata. */ public Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions) { return withContext(context -> getPropertiesWithResponse(accessConditions, context)); } Mono<Response<BlobProperties>> getPropertiesWithResponse(BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().getPropertiesWithRestResponseAsync( null, null, snapshot, null, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey, accessConditions.getModifiedAccessConditions(), context)) .map(rb -> new SimpleResponse<>(rb, new BlobProperties(rb.getDeserializedHeaders()))); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeaders * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} * @return A reactive response signalling completion. */ public Mono<Void> setHTTPHeaders(BlobHTTPHeaders headers) { return setHTTPHeadersWithResponse(headers, null).flatMap(FluxUtil::toMono); } /** * Changes a blob's HTTP header properties. if only one HTTP header is updated, the others will all be erased. In * order to preserve existing values, they must be passed alongside the header being changed. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setHTTPHeadersWithResponse * * <p>For more information, see the * <a href="https: * * @param headers {@link BlobHTTPHeaders} * @param accessConditions {@link BlobAccessConditions} * @return A reactive response signalling completion. */ public Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions) { return withContext(context -> setHTTPHeadersWithResponse(headers, accessConditions, context)); } Mono<Response<Void>> setHTTPHeadersWithResponse(BlobHTTPHeaders headers, BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().setHTTPHeadersWithRestResponseAsync( null, null, null, null, headers, accessConditions.getLeaseAccessConditions(), accessConditions.getModifiedAccessConditions(), context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadata * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. * @return A reactive response signalling completion. */ public Mono<Void> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata, null).flatMap(FluxUtil::toMono); } /** * Changes a blob's metadata. The specified metadata in this method will replace existing metadata. If old values * must be preserved, they must be downloaded and included in the call to this method. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob. * @param accessConditions {@link BlobAccessConditions} * @return A reactive response signalling completion. */ public Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions) { return withContext(context -> setMetadataWithResponse(metadata, accessConditions, context)); } Mono<Response<Void>> setMetadataWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().setMetadataWithRestResponseAsync( null, null, null, metadata, null, accessConditions.getLeaseAccessConditions(), customerProvidedKey, accessConditions.getModifiedAccessConditions(), context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshot} * * <p>For more information, see the * <a href="https: * * @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot, * use {@link */ public Mono<BlobAsyncClientBase> createSnapshot() { return createSnapshotWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Creates a read-only snapshot of the blob. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.createSnapshotWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Metadata to associate with the blob snapshot. * @param accessConditions {@link BlobAccessConditions} * @return A response containing a {@link BlobAsyncClientBase} which is used to interact with the created snapshot, * use {@link */ public Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions) { return withContext(context -> createSnapshotWithResponse(metadata, accessConditions, context)); } Mono<Response<BlobAsyncClientBase>> createSnapshotWithResponse(Map<String, String> metadata, BlobAccessConditions accessConditions, Context context) { accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs().createSnapshotWithRestResponseAsync( null, null, null, metadata, null, customerProvidedKey, accessConditions.getModifiedAccessConditions(), accessConditions.getLeaseAccessConditions(), context)) .map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.getDeserializedHeaders().getSnapshot()))); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTier * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @return A reactive response signalling completion. * @throws NullPointerException if {@code tier} is null. */ public Mono<Void> setAccessTier(AccessTier tier) { return setAccessTierWithResponse(tier, null, null).flatMap(FluxUtil::toMono); } /** * Sets the tier on a blob. The operation is allowed on a page blob in a premium storage account or a block blob in * a blob storage or GPV2 account. A premium page blob's tier determines the allowed size, IOPS, and bandwidth of * the blob. A block blob's tier determines the Hot/Cool/Archive storage type. This does not update the blob's * etag. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.setAccessTierWithResponse * * <p>For more information, see the * <a href="https: * * @param tier The new tier for the blob. * @param priority Optional priority to set for re-hydrating blobs. * @param leaseAccessConditions By setting lease access conditions, requests will fail if the provided lease does * not match the active lease on the blob. * @return A reactive response signalling completion. * @throws NullPointerException if {@code tier} is null. */ public Mono<Response<Void>> setAccessTierWithResponse(AccessTier tier, RehydratePriority priority, LeaseAccessConditions leaseAccessConditions) { return withContext(context -> setTierWithResponse(tier, priority, leaseAccessConditions, context)); } Mono<Response<Void>> setTierWithResponse(AccessTier tier, RehydratePriority priority, LeaseAccessConditions leaseAccessConditions, Context context) { Utility.assertNotNull("tier", tier); return postProcessResponse(this.azureBlobStorage.blobs().setTierWithRestResponseAsync( null, null, tier, null, priority, null, leaseAccessConditions, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undelete} * * <p>For more information, see the * <a href="https: * * @return A reactive response signalling completion. */ public Mono<Void> undelete() { return undeleteWithResponse().flatMap(FluxUtil::toMono); } /** * Undelete restores the content and metadata of a soft-deleted blob and/or any associated soft-deleted snapshots. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.undeleteWithResponse} * * <p>For more information, see the * <a href="https: * * @return A reactive response signalling completion. */ public Mono<Response<Void>> undeleteWithResponse() { return withContext(this::undeleteWithResponse); } Mono<Response<Void>> undeleteWithResponse(Context context) { return postProcessResponse(this.azureBlobStorage.blobs().undeleteWithRestResponseAsync(null, null, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfo} * * <p>For more information, see the * <a href="https: * * @return a reactor response containing the sku name and account kind. */ public Mono<StorageAccountInfo> getAccountInfo() { return getAccountInfoWithResponse().flatMap(FluxUtil::toMono); } /** * Returns the sku name and account kind for the account. * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.getAccountInfoWithResponse} * * <p>For more information, see the * <a href="https: * * @return a reactor response containing the sku name and account kind. */ public Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse() { return withContext(this::getAccountInfoWithResponse); } Mono<Response<StorageAccountInfo>> getAccountInfoWithResponse(Context context) { return postProcessResponse( this.azureBlobStorage.blobs().getAccountInfoWithRestResponseAsync(null, null, context)) .map(rb -> new SimpleResponse<>(rb, new StorageAccountInfo(rb.getDeserializedHeaders()))); } /** * Generates a user delegation SAS with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code ContainerSASPermissions} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSasPermission permissions, OffsetDateTime expiryTime) { return this.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, null /* startTime */, null /* version */, null /*sasProtocol */, null /* ipRange */, null /* cacheControl */, null /*contentDisposition */, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a user delegation SAS token with the specified parameters * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code ContainerSASPermissions} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSasPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.generateUserDelegationSAS(userDelegationKey, accountName, permissions, expiryTime, startTime, version, sasProtocol, ipRange, null /* cacheControl */, null /* contentDisposition */, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a user delegation SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.generateUserDelegationSAS * * <p>For more information, see the * <a href="https: * Docs</a></p> * * @param userDelegationKey The {@code UserDelegationKey} user delegation key for the SAS * @param accountName The {@code String} account name for the SAS * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token */ public String generateUserDelegationSAS(UserDelegationKey userDelegationKey, String accountName, BlobSasPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { BlobServiceSasSignatureValues blobServiceSASSignatureValues = new BlobServiceSasSignatureValues(version, sasProtocol, startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange, null /* identifier*/, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); BlobServiceSasSignatureValues values = configureServiceSASSignatureValues(blobServiceSASSignatureValues, accountName); BlobServiceSasQueryParameters blobServiceSasQueryParameters = values.generateSASQueryParameters(userDelegationKey); return blobServiceSasQueryParameters.encode(); } /** * Generates a SAS token with the specified parameters * * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @return A string that represents the SAS token * @throws NullPointerException if {@code sharedKeyCredential} is null */ public String generateSAS(BlobSasPermission permissions, OffsetDateTime expiryTime) { return this.generateSAS(null, permissions, expiryTime, null /* startTime */, /* identifier */ null /* version */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null /* contentLanguage*/, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @return A string that represents the SAS token * @throws NullPointerException if {@code sharedKeyCredential} is null */ public String generateSAS(String identifier) { return this.generateSAS(identifier, null /* permissions */, null /* expiryTime */, null /* startTime */, null /* version */, null /* sasProtocol */, null /* ipRange */, null /* cacheControl */, null /* contentLanguage*/, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a SAS token with the specified parameters * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @return A string that represents the SAS token * @throws NullPointerException if {@code sharedKeyCredential} is null */ public String generateSAS(String identifier, BlobSasPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange) { return this.generateSAS(identifier, permissions, expiryTime, startTime, version, sasProtocol, ipRange, null /* cacheControl */, null /* contentLanguage*/, null /* contentEncoding */, null /* contentLanguage */, null /* contentType */); } /** * Generates a SAS token with the specified parameters * * <p><strong>Code Samples</strong></p> * * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.generateSAS * * <p>For more information, see the * <a href="https: * * @param identifier The {@code String} name of the access policy on the container this SAS references if any * @param permissions The {@code BlobSASPermission} permission for the SAS * @param expiryTime The {@code OffsetDateTime} expiry time for the SAS * @param startTime An optional {@code OffsetDateTime} start time for the SAS * @param version An optional {@code String} version for the SAS * @param sasProtocol An optional {@code SASProtocol} protocol for the SAS * @param ipRange An optional {@code IPRange} ip address range for the SAS * @param cacheControl An optional {@code String} cache-control header for the SAS. * @param contentDisposition An optional {@code String} content-disposition header for the SAS. * @param contentEncoding An optional {@code String} content-encoding header for the SAS. * @param contentLanguage An optional {@code String} content-language header for the SAS. * @param contentType An optional {@code String} content-type header for the SAS. * @return A string that represents the SAS token * @throws NullPointerException if {@code sharedKeyCredential} is null */ public String generateSAS(String identifier, BlobSasPermission permissions, OffsetDateTime expiryTime, OffsetDateTime startTime, String version, SASProtocol sasProtocol, IPRange ipRange, String cacheControl, String contentDisposition, String contentEncoding, String contentLanguage, String contentType) { BlobServiceSasSignatureValues blobServiceSASSignatureValues = new BlobServiceSasSignatureValues(version, sasProtocol, startTime, expiryTime, permissions == null ? null : permissions.toString(), ipRange, identifier, cacheControl, contentDisposition, contentEncoding, contentLanguage, contentType); SharedKeyCredential sharedKeyCredential = Utility.getSharedKeyCredential(this.azureBlobStorage.getHttpPipeline()); Utility.assertNotNull("sharedKeyCredential", sharedKeyCredential); BlobServiceSasSignatureValues values = configureServiceSASSignatureValues(blobServiceSASSignatureValues, sharedKeyCredential.getAccountName()); BlobServiceSasQueryParameters blobServiceSasQueryParameters = values.generateSASQueryParameters(sharedKeyCredential); return blobServiceSasQueryParameters.encode(); } /** * Sets blobServiceSASSignatureValues parameters dependent on the current blob type */ private BlobServiceSasSignatureValues configureServiceSASSignatureValues( BlobServiceSasSignatureValues blobServiceSASSignatureValues, String accountName) { blobServiceSASSignatureValues.setCanonicalName(this.azureBlobStorage.getUrl(), accountName); blobServiceSASSignatureValues.setSnapshotId(getSnapshotId()); if (isSnapshot()) { blobServiceSASSignatureValues.setResource(Constants.UrlConstants.SAS_BLOB_SNAPSHOT_CONSTANT); } else { blobServiceSASSignatureValues.setResource(Constants.UrlConstants.SAS_BLOB_CONSTANT); } return blobServiceSASSignatureValues; } }
Do we want to use the NO_LABEL static here to show what passing null means?
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException { String connectionString = "endpoint={endpoint_value};id={id_value};name={secret_value}"; ConfigurationAsyncClient client = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); String key = "hello"; client.setSetting(key, null, "world").subscribe( result -> { ConfigurationSetting setting = result; System.out.println(String.format("Key: %s, Value: %s", setting.getKey(), setting.getValue())); }, error -> System.err.println("There was an error adding the setting: " + error.toString()), () -> { System.out.println("Completed. Deleting setting..."); client.deleteSetting(key).block(); }); }
client.setSetting(key, null, "world").subscribe(
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeyException { String connectionString = "endpoint={endpoint_value};id={id_value};name={secret_value}"; ConfigurationAsyncClient client = new ConfigurationClientBuilder() .credential(new ConfigurationClientCredentials(connectionString)) .buildAsyncClient(); String key = "hello"; client.setSetting(key, null, "world").subscribe( result -> { ConfigurationSetting setting = result; System.out.println(String.format("Key: %s, Value: %s", setting.getKey(), setting.getValue())); }, error -> System.err.println("There was an error adding the setting: " + error.toString()), () -> { System.out.println("Completed. Deleting setting..."); client.deleteSetting(key).block(); }); }
class HelloWorld { /** * Runs the sample algorithm and demonstrates how to add, get, and delete a configuration setting. * * @param args Unused. Arguments to the program. * @throws NoSuchAlgorithmException when credentials cannot be created because the service cannot resolve the * HMAC-SHA256 algorithm. * @throws InvalidKeyException when credentials cannot be created because the connection string is invalid. */ }
class HelloWorld { /** * Runs the sample algorithm and demonstrates how to add, get, and delete a configuration setting. * * @param args Unused. Arguments to the program. * @throws NoSuchAlgorithmException when credentials cannot be created because the service cannot resolve the * HMAC-SHA256 algorithm. * @throws InvalidKeyException when credentials cannot be created because the connection string is invalid. */ }
It probably makes sense to just have the log level be NONE by default.
public ConfigurationClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions().setLogLevel(HttpLogDetailLevel.NONE); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); }
httpLogOptions = new HttpLogOptions().setLogLevel(HttpLogDetailLevel.NONE);
public ConfigurationClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); }
class ConfigurationClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private static final String ACCEPT_HEADER = "Accept"; private static final String ACCEPT_HEADER_VALUE = "application/vnd.microsoft.azconfig.kv+json"; private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private ConfigurationClientCredentials credential; private URL endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; /** * The constructor with defaults. */ /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * * <p> * If {@link * {@link * settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * * <p> * If {@link * {@link * builder settings are ignored. * </p> * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; ConfigurationClientCredentials configurationCredentials = getConfigurationCredentials(buildConfiguration); URL buildEndpoint = getBuildEndpoint(configurationCredentials); Objects.requireNonNull(buildEndpoint); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline); } ConfigurationClientCredentials buildCredential = (credential == null) ? configurationCredentials : credential; if (buildCredential == null) { throw logger.logExceptionAsWarning(new IllegalStateException("'credential' is required.")); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(AzureConfiguration.NAME, AzureConfiguration.VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); policies.add(new AddDatePolicy()); policies.add(new ConfigurationCredentialsPolicy(buildCredential)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline); } /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance to send {@link ConfigurationSetting} * service requests to and receive responses from. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException if {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { this.endpoint = new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param credential The credential to use for authenticating HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationClientBuilder credential(ConfigurationClientCredentials credential) { this.credential = Objects.requireNonNull(credential); this.endpoint = credential.getBaseUri(); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code logOptions} is {@code null}. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = Objects.requireNonNull(logOptions, "Http log options cannot be null."); 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 ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); policies.add(policy); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from * {@link ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * @param retryPolicy RetryPolicy applied to each request. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } private ConfigurationClientCredentials getConfigurationCredentials(Configuration configuration) { String connectionString = configuration.get("AZURE_APPCONFIG_CONNECTION_STRING"); if (ImplUtils.isNullOrEmpty(connectionString)) { return credential; } try { return new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException | NoSuchAlgorithmException ex) { return null; } } private URL getBuildEndpoint(ConfigurationClientCredentials buildCredentials) { if (endpoint != null) { return endpoint; } else if (buildCredentials != null) { return buildCredentials.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private static final String ACCEPT_HEADER = "Accept"; private static final String ACCEPT_HEADER_VALUE = "application/vnd.microsoft.azconfig.kv+json"; private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private ConfigurationClientCredentials credential; private URL endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; /** * The constructor with defaults. */ /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * * <p> * If {@link * {@link * settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * * <p> * If {@link * {@link * builder settings are ignored. * </p> * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; ConfigurationClientCredentials configurationCredentials = getConfigurationCredentials(buildConfiguration); URL buildEndpoint = getBuildEndpoint(configurationCredentials); Objects.requireNonNull(buildEndpoint); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline); } ConfigurationClientCredentials buildCredential = (credential == null) ? configurationCredentials : credential; if (buildCredential == null) { throw logger.logExceptionAsWarning(new IllegalStateException("'credential' is required.")); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(AzureConfiguration.NAME, AzureConfiguration.VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); policies.add(new AddDatePolicy()); policies.add(new ConfigurationCredentialsPolicy(buildCredential)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline); } /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance to send {@link ConfigurationSetting} * service requests to and receive responses from. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException if {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { this.endpoint = new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param credential The credential to use for authenticating HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationClientBuilder credential(ConfigurationClientCredentials credential) { this.credential = Objects.requireNonNull(credential); this.endpoint = credential.getBaseUri(); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; 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 ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); policies.add(policy); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from * {@link ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * @param retryPolicy RetryPolicy applied to each request. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } private ConfigurationClientCredentials getConfigurationCredentials(Configuration configuration) { String connectionString = configuration.get("AZURE_APPCONFIG_CONNECTION_STRING"); if (ImplUtils.isNullOrEmpty(connectionString)) { return credential; } try { return new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException | NoSuchAlgorithmException ex) { return null; } } private URL getBuildEndpoint(ConfigurationClientCredentials buildCredentials) { if (endpoint != null) { return endpoint; } else if (buildCredentials != null) { return buildCredentials.getBaseUri(); } else { return null; } } }
We should probably allow null now that I think about it - this lets the user clear out the configuration in the builder so that the next time they call build, they will get an HttpLoggingPolicy with null options. This also means you need to have HttpLoggingPolicy know what to do if the options are null!
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = Objects.requireNonNull(logOptions, "Http log options cannot be null."); return this; }
httpLogOptions = Objects.requireNonNull(logOptions, "Http log options cannot be null.");
public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; return this; }
class ConfigurationClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private static final String ACCEPT_HEADER = "Accept"; private static final String ACCEPT_HEADER_VALUE = "application/vnd.microsoft.azconfig.kv+json"; private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private ConfigurationClientCredentials credential; private URL endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; /** * The constructor with defaults. */ public ConfigurationClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions().setLogLevel(HttpLogDetailLevel.NONE); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * * <p> * If {@link * {@link * settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * * <p> * If {@link * {@link * builder settings are ignored. * </p> * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; ConfigurationClientCredentials configurationCredentials = getConfigurationCredentials(buildConfiguration); URL buildEndpoint = getBuildEndpoint(configurationCredentials); Objects.requireNonNull(buildEndpoint); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline); } ConfigurationClientCredentials buildCredential = (credential == null) ? configurationCredentials : credential; if (buildCredential == null) { throw logger.logExceptionAsWarning(new IllegalStateException("'credential' is required.")); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(AzureConfiguration.NAME, AzureConfiguration.VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); policies.add(new AddDatePolicy()); policies.add(new ConfigurationCredentialsPolicy(buildCredential)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline); } /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance to send {@link ConfigurationSetting} * service requests to and receive responses from. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException if {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { this.endpoint = new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param credential The credential to use for authenticating HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationClientBuilder credential(ConfigurationClientCredentials credential) { this.credential = Objects.requireNonNull(credential); this.endpoint = credential.getBaseUri(); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code logOptions} is {@code null}. */ /** * 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 ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); policies.add(policy); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from * {@link ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * @param retryPolicy RetryPolicy applied to each request. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } private ConfigurationClientCredentials getConfigurationCredentials(Configuration configuration) { String connectionString = configuration.get("AZURE_APPCONFIG_CONNECTION_STRING"); if (ImplUtils.isNullOrEmpty(connectionString)) { return credential; } try { return new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException | NoSuchAlgorithmException ex) { return null; } } private URL getBuildEndpoint(ConfigurationClientCredentials buildCredentials) { if (endpoint != null) { return endpoint; } else if (buildCredentials != null) { return buildCredentials.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private static final String ACCEPT_HEADER = "Accept"; private static final String ACCEPT_HEADER_VALUE = "application/vnd.microsoft.azconfig.kv+json"; private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private ConfigurationClientCredentials credential; private URL endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; /** * The constructor with defaults. */ public ConfigurationClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * * <p> * If {@link * {@link * settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * * <p> * If {@link * {@link * builder settings are ignored. * </p> * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; ConfigurationClientCredentials configurationCredentials = getConfigurationCredentials(buildConfiguration); URL buildEndpoint = getBuildEndpoint(configurationCredentials); Objects.requireNonNull(buildEndpoint); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline); } ConfigurationClientCredentials buildCredential = (credential == null) ? configurationCredentials : credential; if (buildCredential == null) { throw logger.logExceptionAsWarning(new IllegalStateException("'credential' is required.")); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(AzureConfiguration.NAME, AzureConfiguration.VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); policies.add(new AddDatePolicy()); policies.add(new ConfigurationCredentialsPolicy(buildCredential)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline); } /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance to send {@link ConfigurationSetting} * service requests to and receive responses from. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException if {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { this.endpoint = new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param credential The credential to use for authenticating HTTP requests. * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is {@code null}. */ public ConfigurationClientBuilder credential(ConfigurationClientCredentials credential) { this.credential = Objects.requireNonNull(credential); this.endpoint = credential.getBaseUri(); return this; } /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ /** * 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 ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); policies.add(policy); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from * {@link ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * @param retryPolicy RetryPolicy applied to each request. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } private ConfigurationClientCredentials getConfigurationCredentials(Configuration configuration) { String connectionString = configuration.get("AZURE_APPCONFIG_CONNECTION_STRING"); if (ImplUtils.isNullOrEmpty(connectionString)) { return credential; } try { return new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException | NoSuchAlgorithmException ex) { return null; } } private URL getBuildEndpoint(ConfigurationClientCredentials buildCredentials) { if (endpoint != null) { return endpoint; } else if (buildCredentials != null) { return buildCredentials.getBaseUri(); } else { return null; } } }
Maybe rather than require non-null, if null is passed in just set it to NONE. Be sure to document that though.
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) { this.logLevel = Objects.requireNonNull(logLevel); return this; }
this.logLevel = Objects.requireNonNull(logLevel);
public HttpLogOptions setLogLevel(final HttpLogDetailLevel logLevel) { this.logLevel = logLevel == null ? HttpLogDetailLevel.NONE : logLevel; return this; }
class HttpLogOptions { private HttpLogDetailLevel logLevel; private Set<String> allowedHeaderNames; private Set<String> allowedQueryParamNames; public HttpLogOptions() { allowedHeaderNames = new HashSet<>(); allowedQueryParamNames = new HashSet<>(); } /** * Gets the level of detail to log on HTTP messages. * * @return The {@link HttpLogDetailLevel}. */ public HttpLogDetailLevel getLogLevel() { return logLevel; } /** * Sets the level of detail to log on Http messages. * * @param logLevel The {@link HttpLogDetailLevel}. * @return The updated HttpLogOptions object. * @throws NullPointerException If {@code logLevel} is {@code null}. */ /** * Gets the whitelisted headers that should be logged. * * @return The list of whitelisted headers. */ public Set<String> getAllowedHeaderNames() { return allowedHeaderNames; } /** * Sets the given whitelisted headers that should be logged. * * @param allowedHeaderNames The list of whitelisted header names from the user. * @return The updated HttpLogOptions object. * @throws NullPointerException If {@code allowedHeaderNames} is {@code null}. */ public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) { this.allowedHeaderNames = Objects.requireNonNull(allowedHeaderNames); return this; } /** * Sets the given whitelisted header that should be logged. * * @param allowedHeaderName The whitelisted header name from the user. * @return The updated HttpLogOptions object. * @throws NullPointerException If {@code allowedHeaderName} is {@code null}. */ public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) { Objects.requireNonNull(allowedHeaderName); this.allowedHeaderNames.add(allowedHeaderName); return this; } /** * Gets the whitelisted query parameters. * * @return The list of whitelisted query parameters. */ public Set<String> getAllowedQueryParamNames() { return allowedQueryParamNames; } /** * Sets the given whitelisted query params to be displayed in the logging info. * * @param allowedQueryParamNames The list of whitelisted query params from the user. * @return The updated HttpLogOptions object. * @throws NullPointerException If {@code allowedQueryParamNames} is {@code null}. */ public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) { this.allowedQueryParamNames = Objects.requireNonNull(allowedQueryParamNames); return this; } /** * Sets the given whitelisted query param that should be logged. * * @param allowedQueryParamName The whitelisted query param name from the user. * @return The updated HttpLogOptions object. * @throws NullPointerException If {@code allowedQueryParamName} is {@code null}. */ public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) { Objects.requireNonNull(allowedQueryParamName); this.allowedQueryParamNames.add(allowedQueryParamName); return this; } }
class HttpLogOptions { private HttpLogDetailLevel logLevel; private Set<String> allowedHeaderNames; private Set<String> allowedQueryParamNames; public HttpLogOptions() { logLevel = HttpLogDetailLevel.NONE; allowedHeaderNames = new HashSet<>(); allowedQueryParamNames = new HashSet<>(); } /** * Gets the level of detail to log on HTTP messages. * * @return The {@link HttpLogDetailLevel}. */ public HttpLogDetailLevel getLogLevel() { return logLevel; } /** * Sets the level of detail to log on Http messages. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logLevel The {@link HttpLogDetailLevel}. * @return The updated HttpLogOptions object. */ /** * Gets the whitelisted headers that should be logged. * * @return The list of whitelisted headers. */ public Set<String> getAllowedHeaderNames() { return allowedHeaderNames; } /** * Sets the given whitelisted headers that should be logged. * * @param allowedHeaderNames The list of whitelisted header names from the user. * @return The updated HttpLogOptions object. * @throws NullPointerException If {@code allowedHeaderNames} is {@code null}. */ public HttpLogOptions setAllowedHeaderNames(final Set<String> allowedHeaderNames) { this.allowedHeaderNames = allowedHeaderNames; return this; } /** * Sets the given whitelisted header that should be logged. * * @param allowedHeaderName The whitelisted header name from the user. * @return The updated HttpLogOptions object. * @throws NullPointerException If {@code allowedHeaderName} is {@code null}. */ public HttpLogOptions addAllowedHeaderName(final String allowedHeaderName) { Objects.requireNonNull(allowedHeaderName); this.allowedHeaderNames.add(allowedHeaderName); return this; } /** * Gets the whitelisted query parameters. * * @return The list of whitelisted query parameters. */ public Set<String> getAllowedQueryParamNames() { return allowedQueryParamNames; } /** * Sets the given whitelisted query params to be displayed in the logging info. * * @param allowedQueryParamNames The list of whitelisted query params from the user. * @return The updated HttpLogOptions object. */ public HttpLogOptions setAllowedQueryParamNames(final Set<String> allowedQueryParamNames) { this.allowedQueryParamNames = allowedQueryParamNames; return this; } /** * Sets the given whitelisted query param that should be logged. * * @param allowedQueryParamName The whitelisted query param name from the user. * @return The updated HttpLogOptions object. * @throws NullPointerException If {@code allowedQueryParamName} is {@code null}. */ public HttpLogOptions addAllowedQueryParamName(final String allowedQueryParamName) { this.allowedQueryParamNames.add(allowedQueryParamName); return this; } }
Whenever I see a method call (like `getLogLevel()`) multiple times I prefer to see it referred to in a local variable.
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (httpLogOptions.getLogLevel().shouldLogUrl()) { logger.info("--> {} {}", request.getHttpMethod(), request.getUrl()); } if (httpLogOptions.getLogLevel().shouldLogHeaders()) { formatAllowableHeaders(httpLogOptions.getAllowedHeaderNames(), request, logger); } if (httpLogOptions.getLogLevel().shouldLogQueryParams()) { formatAllowableQueryParams(httpLogOptions.getAllowedQueryParamNames(), request, logger); } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (httpLogOptions.getLogLevel().shouldLogBody()) { if (request.getBody() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.getHttpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.getHeaders().getValue("Content-Type")); final long contentLength = getContentLength(request.getHeaders()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.getBody()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.getHeaders().getValue("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.getHttpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.getHttpMethod()); } } } return reqBodyLoggingMono; }
if (httpLogOptions.getLogLevel().shouldLogBody()) {
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { final HttpLogDetailLevel httpLogLevel = httpLogOptions.getLogLevel(); if (httpLogLevel.shouldLogUrl()) { logger.info("--> {} {}", request.getHttpMethod(), request.getUrl()); formatAllowableQueryParams(httpLogOptions.getAllowedQueryParamNames(), request.getUrl().getQuery(), logger); } if (httpLogLevel.shouldLogHeaders()) { formatAllowableHeaders(httpLogOptions.getAllowedHeaderNames(), request.getHeaders(), logger); } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (httpLogLevel.shouldLogBody()) { if (request.getBody() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.getHttpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.getHeaders().getValue("Content-Type")); final long contentLength = getContentLength(request.getHeaders()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.getBody()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.getHeaders().getValue("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.getHttpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.getHttpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogOptions httpLogOptions; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; private static final String REDACTED_PLACEHOLDER = "REDACTED"; /** * Creates an HttpLoggingPolicy with the given log configurations. * * @param httpLogOptions The HTTP logging configurations. */ public HttpLoggingPolicy(HttpLogOptions httpLogOptions) { this(httpLogOptions, false); } /** * Creates an HttpLoggingPolicy with the given log configuration and pretty printing setting. * * @param httpLogOptions The HTTP logging configuration options. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogOptions httpLogOptions, boolean prettyPrintJSON) { this.httpLogOptions = httpLogOptions; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.getHttpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.getHttpRequest().getUrl(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private void formatAllowableHeaders(Set<String> allowedHeaderNames, HttpRequest request, ClientLogger logger) { StringBuilder sb = new StringBuilder(); for (HttpHeader header : request.getHeaders()) { sb.append(header.getName()).append(":"); if (allowedHeaderNames.contains(header.getName())) { sb.append(header.getValue()); } else { sb.append(REDACTED_PLACEHOLDER); } } logger.info(sb.toString()); } private void formatAllowableQueryParams(Set<String> allowedQueryParamNames, HttpRequest request, ClientLogger logger) { StringBuilder sb = new StringBuilder(); String queryString = request.getUrl().getQuery(); if (queryString != null) { String[] queryParams = queryString.split("&"); for (String queryParam : queryParams) { String[] queryPair = queryParam.split("=", 2); if (queryPair.length == 2) { if (allowedQueryParamNames.contains(queryPair[0])) { sb.append(queryParam); } else { sb.append(queryPair[0]).append("=").append(REDACTED_PLACEHOLDER); } } else { sb.append(queryParam); } sb.append("&"); } if (sb.length() > 0) { logger.info(sb.substring(0, sb.length() - 1)); } } } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.getHeaderValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (httpLogOptions.getLogLevel().shouldLogUrl()) { logger.info("<-- {} {} ({} ms, {} body)", response.getStatusCode(), url, tookMs, bodySize); } if (httpLogOptions.getLogLevel().shouldLogHeaders()) { StringBuilder sb = new StringBuilder(); for (HttpHeader header : response.getHeaders()) { sb.append(header.getName()).append(":"); if (httpLogOptions.getAllowedHeaderNames().contains(header.getName())) { sb.append(header.getValue()); } else { sb.append(REDACTED_PLACEHOLDER); } } logger.info(sb.toString()); } if (httpLogOptions.getLogLevel().shouldLogBody()) { long contentLength = getContentLength(response.getHeaders()); final String contentTypeHeader = response.getHeaderValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.getBodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.getValue("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogOptions httpLogOptions; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; private static final String REDACTED_PLACEHOLDER = "REDACTED"; /** * Creates an HttpLoggingPolicy with the given log configurations. * * @param httpLogOptions The HTTP logging configurations. */ public HttpLoggingPolicy(HttpLogOptions httpLogOptions) { this(httpLogOptions, false); } /** * Creates an HttpLoggingPolicy with the given log configuration and pretty printing setting. * * @param httpLogOptions The HTTP logging configuration options. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ HttpLoggingPolicy(HttpLogOptions httpLogOptions, boolean prettyPrintJSON) { this.httpLogOptions = httpLogOptions; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); if (httpLogOptions != null) { Mono<Void> logRequest = logRequest(logger, context.getHttpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.getHttpRequest().getUrl(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } return Mono.empty(); } private void formatAllowableHeaders(Set<String> allowedHeaderNames, HttpHeaders requestResponseHeaders, ClientLogger logger) { if (allowedHeaderNames != null && !allowedHeaderNames.isEmpty()) { StringBuilder sb = new StringBuilder(); for (HttpHeader header : requestResponseHeaders) { sb.append(header.getName()).append(":"); if (allowedHeaderNames.contains(header.getName())) { sb.append(header.getValue()); } else { sb.append(REDACTED_PLACEHOLDER); } sb.append(System.getProperty("line.separator")); } logger.info(sb.toString()); } } private void formatAllowableQueryParams(Set<String> allowedQueryParamNames, String queryString, ClientLogger logger) { if (allowedQueryParamNames != null && !allowedQueryParamNames.isEmpty() && queryString != null) { StringBuilder sb = new StringBuilder(); String[] queryParams = queryString.split("&"); for (String queryParam : queryParams) { String[] queryPair = queryParam.split("=", 2); if (queryPair.length == 2) { if (allowedQueryParamNames.contains(queryPair[0])) { sb.append(queryParam); } else { sb.append(queryPair[0]).append("=").append(REDACTED_PLACEHOLDER); } } else { sb.append(queryParam); } sb.append("&"); } if (sb.length() > 0) { logger.info(sb.substring(0, sb.length() - 1)); } } } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.getHeaderValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } HttpLogDetailLevel httpLogLevel = httpLogOptions.getLogLevel(); if (httpLogLevel.shouldLogUrl()) { logger.info("<-- {} {} ({} ms, {} body)", response.getStatusCode(), url, tookMs, bodySize); } if (httpLogLevel.shouldLogHeaders()) { formatAllowableHeaders(httpLogOptions.getAllowedHeaderNames(), response.getHeaders(), logger); } if (httpLogLevel.shouldLogBody()) { long contentLength = getContentLength(response.getHeaders()); final String contentTypeHeader = response.getHeaderValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.getBodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.getValue("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
Should properties be setable? Also what if properties argument is null?
public Secret setProperties(SecretProperties properties) { properties.name = this.properties.name; this.properties = properties; return this; }
return this;
public Secret setProperties(SecretProperties properties) { Objects.requireNonNull(properties); properties.name = this.properties.name; this.properties = properties; return this; }
class Secret { /** * The value of the secret. */ @JsonProperty(value = "value") private String value; /** * The secret properties. */ private SecretProperties properties; /** * Creates an empty instance of the Secret. */ Secret() { properties = new SecretProperties(); } /** * Creates a Secret with {@code name} and {@code value}. * * @param name The name of the secret. * @param value the value of the secret. */ public Secret(String name, String value) { properties = new SecretProperties(name); this.value = value; } /** * Get the value of the secret. * * @return the secret value */ public String getValue() { return this.value; } /** * Get the secret identifier. * * @return the secret identifier. */ public Secret getId() { properties.getId(); return this; } /** * Get the secret name. * * @return the secret name. */ public String getName() { return properties.getName(); } /** * Get the secret properties * @return the Secret properties */ public SecretProperties getProperties() { return this.properties; } /** * Set the secret properties * @param properties The Secret properties * @return the updated secret object */ @JsonProperty(value = "id") private void unpackId(String id) { properties.unpackId(id); } /** * Unpacks the attributes json response and updates the variables in the Secret Attributes object. * Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are * part of main json body and not attributes json body when the secret response comes from list Secrets operations. * @param attributes The key value mapping of the Secret attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private void unpackAttributes(Map<String, Object> attributes) { properties.unpackAttributes(attributes); } @JsonProperty("managed") private void unpackManaged(Boolean managed) { properties.managed = managed; } @JsonProperty("kid") private void unpackKid(String kid) { properties.keyId = kid; } @JsonProperty("contentType") private void unpackContentType(String contentType) { properties.contentType = contentType; } @JsonProperty("tags") private void unpackTags(Map<String, String> tags) { properties.tags = tags; } }
class Secret { /** * The value of the secret. */ @JsonProperty(value = "value") private String value; /** * The secret properties. */ private SecretProperties properties; /** * Creates an empty instance of the Secret. */ Secret() { properties = new SecretProperties(); } /** * Creates a Secret with {@code name} and {@code value}. * * @param name The name of the secret. * @param value the value of the secret. */ public Secret(String name, String value) { properties = new SecretProperties(name); this.value = value; } /** * Get the value of the secret. * * @return the secret value */ public String getValue() { return this.value; } /** * Get the secret identifier. * * @return the secret identifier. */ public String getId() { return properties.getId(); } /** * Get the secret name. * * @return the secret name. */ public String getName() { return properties.getName(); } /** * Get the secret properties * @return the Secret properties */ public SecretProperties getProperties() { return this.properties; } /** * Set the secret properties * @param properties The Secret properties * @throws NullPointerException if {@code properties} is null. * @return the updated secret object */ @JsonProperty(value = "id") private void unpackId(String id) { properties.unpackId(id); } /** * Unpacks the attributes json response and updates the variables in the Secret Attributes object. * Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are * part of main json body and not attributes json body when the secret response comes from list Secrets operations. * @param attributes The key value mapping of the Secret attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private void unpackAttributes(Map<String, Object> attributes) { properties.unpackAttributes(attributes); } @JsonProperty("managed") private void unpackManaged(Boolean managed) { properties.managed = managed; } @JsonProperty("kid") private void unpackKid(String kid) { properties.keyId = kid; } @JsonProperty("contentType") private void unpackContentType(String contentType) { properties.contentType = contentType; } @JsonProperty("tags") private void unpackTags(Map<String, String> tags) { properties.tags = tags; } }
"The ~~Secret Base~~ Secret Properties parameter ..." More of these below.
Mono<Response<Secret>> getSecretWithResponse(SecretProperties secretProperties, Context context) { Objects.requireNonNull(secretProperties, "The Secret Base parameter cannot be null."); return getSecretWithResponse(secretProperties.getName(), secretProperties.getVersion() == null ? "" : secretProperties.getVersion(), context); }
Objects.requireNonNull(secretProperties, "The Secret Base parameter cannot be null.");
return getSecretWithResponse(secretProperties.getName(), secretProperties.getVersion() == null ? "" : secretProperties.getVersion(), context); } /** * Get the latest version of the specified secret from the key vault. The get operation is applicable to any secret * stored in Azure Key Vault. * This operation requires the {@code secrets/get}
class SecretAsyncClient { static final String API_VERSION = "7.0"; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private final String endpoint; private final SecretService service; private final ClientLogger logger = new ClientLogger(SecretAsyncClient.class); /** * Creates a SecretAsyncClient that uses {@code pipeline} to service requests * * @param endpoint URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ SecretAsyncClient(URL endpoint, HttpPipeline pipeline) { Objects.requireNonNull(endpoint, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.endpoint = endpoint.toString(); this.service = RestProxy.create(SecretService.class, pipeline); } /** * The set operation adds a secret to the key vault. If the named secret already exists, Azure Key Vault creates * a new version of that secret. This operation requires the {@code secrets/set} permission. * * <p>The {@link Secret} is required. The {@link SecretProperties * {@link SecretProperties * values in {@code secret} are optional. The {@link SecretProperties * by key vault, if not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Creates a new secret which activates in 1 day and expires in 1 year in the Azure Key Vault. Subscribes to the * call asynchronously and prints out the newly created secret details when a response is received.</p> * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecret * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @return A {@link Mono} containing the {@link Secret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpRequestException if {@link Secret */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Secret> setSecret(Secret secret) { return setSecretWithResponse(secret).flatMap(FluxUtil::toMono); } /** * The set operation adds a secret to the key vault. If the named secret already exists, Azure Key Vault creates * a new version of that secret. This operation requires the {@code secrets/set} permission. * * <p>The {@link Secret} is required. The {@link SecretProperties * {@link SecretProperties * values in {@code secret} are optional. The {@link SecretProperties * key vault, if not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Creates a new secret which activates in 1 day and expires in 1 year in the Azure Key Vault. Subscribes to the * call asynchronously and prints out the newly created secret details when a response is received.</p> * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecretWithResponse * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @return A {@link Mono} containing a {@link Response} whose {@link Response * Secret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpRequestException if {@link Secret */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Secret>> setSecretWithResponse(Secret secret) { return withContext(context -> setSecretWithResponse(secret, context)); } Mono<Response<Secret>> setSecretWithResponse(Secret secret, Context context) { Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(endpoint, secret.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } /** * The set operation adds a secret to the key vault. If the named secret already exists, Azure Key * Vault creates a new version of that secret. This operation requires the {@code secrets/set} * permission. * * <p><strong>Code Samples</strong></p> * <p>Creates a new secret in the key vault. Subscribes to the call asynchronously and prints out * the newly created secret details when a response is received.</p> * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecret * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return A {@link Mono} containing the {@link Secret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} are specified. * @throws HttpRequestException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Secret> setSecret(String name, String value) { return withContext(context -> setSecretWithResponse(name, value, context)).flatMap(FluxUtil::toMono); } Mono<Response<Secret>> setSecretWithResponse(String name, String value, Context context) { SecretRequestParameters parameters = new SecretRequestParameters().setValue(value); return service.setSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignored -> logger.info("Setting secret - {}", name)) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", name, error)); } /** * Get the specified secret with specified version from the key vault. The get operation is applicable to any secret * stored in Azure Key Vault. This operation requires the {@code secrets/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the secret in the key vault. Subscribes to the call * asynchronously and prints out the returned secret details when a response is received.</p> * {@codesnippet com.azure.keyvault.secrets.secretclient.getSecret * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty String or null, this * call is equivalent to calling {@link * retrieved. * @return A {@link Mono} containing a {@link Response} whose {@link Response * contains the requested {@link Secret secret}. * @throws ResourceNotFoundException when a secret with {@code name} and {@code version} doesn't * exist in the key vault. * @throws HttpRequestException if {@code name} name}
class SecretAsyncClient { static final String API_VERSION = "7.0"; static final String ACCEPT_LANGUAGE = "en-US"; static final int DEFAULT_MAX_PAGE_RESULTS = 25; static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; static final String KEY_VAULT_SCOPE = "https: private final String endpoint; private final SecretService service; private final ClientLogger logger = new ClientLogger(SecretAsyncClient.class); /** * Creates a SecretAsyncClient that uses {@code pipeline} to service requests * * @param endpoint URL for the Azure KeyVault service. * @param pipeline HttpPipeline that the HTTP requests and responses flow through. */ SecretAsyncClient(URL endpoint, HttpPipeline pipeline) { Objects.requireNonNull(endpoint, KeyVaultErrorCodeStrings.getErrorString(KeyVaultErrorCodeStrings.VAULT_END_POINT_REQUIRED)); this.endpoint = endpoint.toString(); this.service = RestProxy.create(SecretService.class, pipeline); } /** * The set operation adds a secret to the key vault. If the named secret already exists, Azure Key Vault creates * a new version of that secret. This operation requires the {@code secrets/set} permission. * * <p>The {@link Secret} is required. The {@link SecretProperties * {@link SecretProperties * values in {@code secret} are optional. The {@link SecretProperties * by key vault, if not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Creates a new secret which activates in 1 day and expires in 1 year in the Azure Key Vault. Subscribes to the * call asynchronously and prints out the newly created secret details when a response is received.</p> * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecret * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @return A {@link Mono} containing the {@link Secret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpRequestException if {@link Secret */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Secret> setSecret(Secret secret) { return setSecretWithResponse(secret).flatMap(FluxUtil::toMono); } /** * The set operation adds a secret to the key vault. If the named secret already exists, Azure Key Vault creates * a new version of that secret. This operation requires the {@code secrets/set} permission. * * <p>The {@link Secret} is required. The {@link SecretProperties * {@link SecretProperties * values in {@code secret} are optional. The {@link SecretProperties * key vault, if not specified.</p> * * <p><strong>Code Samples</strong></p> * <p>Creates a new secret which activates in 1 day and expires in 1 year in the Azure Key Vault. Subscribes to the * call asynchronously and prints out the newly created secret details when a response is received.</p> * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecretWithResponse * * @param secret The Secret object containing information about the secret and its properties. The properties * secret.name and secret.value must be non null. * @return A {@link Mono} containing a {@link Response} whose {@link Response * Secret created secret}. * @throws NullPointerException if {@code secret} is {@code null}. * @throws ResourceModifiedException if {@code secret} is malformed. * @throws HttpRequestException if {@link Secret */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<Secret>> setSecretWithResponse(Secret secret) { return withContext(context -> setSecretWithResponse(secret, context)); } Mono<Response<Secret>> setSecretWithResponse(Secret secret, Context context) { Objects.requireNonNull(secret, "The Secret input parameter cannot be null."); SecretRequestParameters parameters = new SecretRequestParameters() .setValue(secret.getValue()) .setTags(secret.getProperties().getTags()) .setContentType(secret.getProperties().getContentType()) .setSecretAttributes(new SecretRequestAttributes(secret.getProperties())); return service.setSecret(endpoint, secret.getName(), API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignored -> logger.info("Setting secret - {}", secret.getName())) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", secret.getName(), error)); } /** * The set operation adds a secret to the key vault. If the named secret already exists, Azure Key * Vault creates a new version of that secret. This operation requires the {@code secrets/set} * permission. * * <p><strong>Code Samples</strong></p> * <p>Creates a new secret in the key vault. Subscribes to the call asynchronously and prints out * the newly created secret details when a response is received.</p> * {@codesnippet com.azure.keyvault.secrets.secretclient.setSecret * * @param name The name of the secret. It is required and cannot be null. * @param value The value of the secret. It is required and cannot be null. * @return A {@link Mono} containing the {@link Secret created secret}. * @throws ResourceModifiedException if invalid {@code name} or {@code value} are specified. * @throws HttpRequestException if {@code name} or {@code value} is empty string. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Secret> setSecret(String name, String value) { return withContext(context -> setSecretWithResponse(name, value, context)).flatMap(FluxUtil::toMono); } Mono<Response<Secret>> setSecretWithResponse(String name, String value, Context context) { SecretRequestParameters parameters = new SecretRequestParameters().setValue(value); return service.setSecret(endpoint, name, API_VERSION, ACCEPT_LANGUAGE, parameters, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignored -> logger.info("Setting secret - {}", name)) .doOnSuccess(response -> logger.info("Set secret - {}", response.getValue().getName())) .doOnError(error -> logger.warning("Failed to set secret - {}", name, error)); } /** * Get the specified secret with specified version from the key vault. The get operation is applicable to any secret * stored in Azure Key Vault. This operation requires the {@code secrets/get} permission. * * <p><strong>Code Samples</strong></p> * <p>Gets a specific version of the secret in the key vault. Subscribes to the call * asynchronously and prints out the returned secret details when a response is received.</p> * {@codesnippet com.azure.keyvault.secrets.secretclient.getSecret * * @param name The name of the secret, cannot be null * @param version The version of the secret to retrieve. If this is an empty String or null, this * call is equivalent to calling {@link * retrieved. * @return A {@link Mono} containing a {@link Response} whose {@link Response * contains the requested {@link Secret secret}. * @throws ResourceNotFoundException when a secret with {@code name} and {@code version} doesn't * exist in the key vault. * @throws HttpRequestException if {@code name} name}
should we have `Objects.requireNonNull` in these?
public SecretProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; }
this.enabled = enabled;
public SecretProperties setEnabled(Boolean enabled) { Objects.requireNonNull(enabled); this.enabled = enabled; return this; }
class SecretProperties { /** * The secret id. */ String id; /** * The secret version. */ String version; /** * Determines whether the object is enabled. */ Boolean enabled; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * Expiry date in UTC. */ OffsetDateTime expires; /** * Creation time in UTC. */ OffsetDateTime created; /** * Last updated time in UTC. */ OffsetDateTime updated; /** * The secret name. */ String name; /** * Reflects the deletion recovery level currently in effect for secrets in * the current vault. If it contains 'Purgeable', the secret can be * permanently deleted by a privileged user; otherwise, only the system can * purge the secret, at the end of the retention interval. Possible values * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', * 'Recoverable+ProtectedSubscription'. */ String recoveryLevel; /** * The content type of the secret. */ @JsonProperty(value = "contentType") String contentType; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") Map<String, String> tags; /** * If this is a secret backing a KV certificate, then this field specifies * the corresponding key backing the KV certificate. */ @JsonProperty(value = "kid", access = JsonProperty.Access.WRITE_ONLY) String keyId; /** * True if the secret's lifetime is managed by key vault. If this is a * secret backing a certificate, then managed will be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) Boolean managed; SecretProperties(String secretName) { this.name = secretName; } /** * Creates empty instance of SecretProperties. */ public SecretProperties() {} /** * Get the secret name. * * @return the name of the secret. */ public String getName() { return this.name; } /** * Get the recovery level of the secret. * @return the recoveryLevel of the secret. */ public String getRecoveryLevel() { return recoveryLevel; } /** * Get the enabled value. * * @return the enabled value */ public Boolean isEnabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled The enabled value to set * @return the SecretProperties object itself. */ /** * Get the notBefore UTC time. * * @return the notBefore UTC time. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set * @return the SecretProperties object itself. */ public SecretProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the Secret Expiry time in UTC. * * @return the expires UTC time. */ public OffsetDateTime getExpires() { if (this.expires == null) { return null; } return this.expires; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expires The expiry time to set for the secret. * @return the SecretProperties object itself. */ public SecretProperties setExpires(OffsetDateTime expires) { this.expires = expires; return this; } /** * Get the the UTC time at which secret was created. * * @return the created UTC time. */ public OffsetDateTime getCreated() { return created; } /** * Get the UTC time at which secret was last updated. * * @return the last updated UTC time. */ public OffsetDateTime getUpdated() { return updated; } /** * Get the secret identifier. * * @return the secret identifier. */ public String getId() { return this.id; } /** * Get the content type. * * @return the content type. */ public String getContentType() { return this.contentType; } /** * Set the contentType. * * @param contentType The contentType to set * @return the SecretProperties object itself. */ public SecretProperties setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get the tags associated with the secret. * * @return the value of the tags. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the secret. * * @param tags The tags to set * @return the SecretProperties object itself. */ public SecretProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the keyId identifier. * * @return the keyId identifier. */ public String getKeyId() { return this.keyId; } /** * Get the managed value. * * @return the managed value */ public Boolean isManaged() { return this.managed; } /** * Get the version of the secret. * * @return the version of the secret. */ public String getVersion() { return this.version; } /** * Unpacks the attributes json response and updates the variables in the Secret Attributes object. * Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are * part of main json body and not attributes json body when the secret response comes from list Secrets operations. * @param attributes The key value mapping of the Secret attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expires = epochToOffsetDateTime(attributes.get("exp")); this.created = epochToOffsetDateTime(attributes.get("created")); this.updated = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.contentType = (String) lazyValueSelection(attributes.get("contentType"), this.contentType); this.keyId = (String) lazyValueSelection(attributes.get("keyId"), this.keyId); this.tags = (Map<String, String>) lazyValueSelection(attributes.get("tags"), this.tags); this.managed = (Boolean) lazyValueSelection(attributes.get("managed"), this.managed); unpackId((String) attributes.get("id")); } @JsonProperty(value = "id") void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } private Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } }
class SecretProperties { private final ClientLogger logger = new ClientLogger(SecretProperties.class); /** * The secret id. */ String id; /** * The secret version. */ String version; /** * Determines whether the object is enabled. */ Boolean enabled; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * Expiry date in UTC. */ OffsetDateTime expires; /** * Creation time in UTC. */ OffsetDateTime created; /** * Last updated time in UTC. */ OffsetDateTime updated; /** * The secret name. */ String name; /** * Reflects the deletion recovery level currently in effect for secrets in * the current vault. If it contains 'Purgeable', the secret can be * permanently deleted by a privileged user; otherwise, only the system can * purge the secret, at the end of the retention interval. Possible values * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', * 'Recoverable+ProtectedSubscription'. */ String recoveryLevel; /** * The content type of the secret. */ @JsonProperty(value = "contentType") String contentType; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") Map<String, String> tags; /** * If this is a secret backing a KV certificate, then this field specifies * the corresponding key backing the KV certificate. */ @JsonProperty(value = "kid", access = JsonProperty.Access.WRITE_ONLY) String keyId; /** * True if the secret's lifetime is managed by key vault. If this is a * secret backing a certificate, then managed will be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) Boolean managed; SecretProperties(String secretName) { this.name = secretName; } /** * Creates empty instance of SecretProperties. */ public SecretProperties() { } /** * Get the secret name. * * @return the name of the secret. */ public String getName() { return this.name; } /** * Get the recovery level of the secret. * @return the recoveryLevel of the secret. */ public String getRecoveryLevel() { return recoveryLevel; } /** * Get the enabled value. * * @return the enabled value */ public Boolean isEnabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled The enabled value to set * @throws NullPointerException if {@code enabled} is null. * @return the SecretProperties object itself. */ /** * Get the notBefore UTC time. * * @return the notBefore UTC time. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set * @return the SecretProperties object itself. */ public SecretProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the Secret Expiry time in UTC. * * @return the expires UTC time. */ public OffsetDateTime getExpires() { if (this.expires == null) { return null; } return this.expires; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expires The expiry time to set for the secret. * @return the SecretProperties object itself. */ public SecretProperties setExpires(OffsetDateTime expires) { this.expires = expires; return this; } /** * Get the the UTC time at which secret was created. * * @return the created UTC time. */ public OffsetDateTime getCreated() { return created; } /** * Get the UTC time at which secret was last updated. * * @return the last updated UTC time. */ public OffsetDateTime getUpdated() { return updated; } /** * Get the secret identifier. * * @return the secret identifier. */ public String getId() { return this.id; } /** * Get the content type. * * @return the content type. */ public String getContentType() { return this.contentType; } /** * Set the contentType. * * @param contentType The contentType to set * @return the updated SecretProperties object itself. */ public SecretProperties setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get the tags associated with the secret. * * @return the value of the tags. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the secret. * * @param tags The tags to set * @return the updated SecretProperties object itself. */ public SecretProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the keyId identifier. * * @return the keyId identifier. */ public String getKeyId() { return this.keyId; } /** * Get the managed value. * * @return the managed value */ public Boolean isManaged() { return this.managed; } /** * Get the version of the secret. * * @return the version of the secret. */ public String getVersion() { return this.version; } /** * Unpacks the attributes json response and updates the variables in the Secret Attributes object. * Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are * part of main json body and not attributes json body when the secret response comes from list Secrets operations. * @param attributes The key value mapping of the Secret attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expires = epochToOffsetDateTime(attributes.get("exp")); this.created = epochToOffsetDateTime(attributes.get("created")); this.updated = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.contentType = (String) lazyValueSelection(attributes.get("contentType"), this.contentType); this.keyId = (String) lazyValueSelection(attributes.get("keyId"), this.keyId); this.tags = (Map<String, String>) lazyValueSelection(attributes.get("tags"), this.tags); this.managed = (Boolean) lazyValueSelection(attributes.get("managed"), this.managed); unpackId((String) attributes.get("id")); } @JsonProperty(value = "id") void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { logger.error("Received Malformed Secret Id URL from KV Service"); } } } private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } private Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } }
added the null check. setters are idiomatic in java, facilitates fluency.
public Secret setProperties(SecretProperties properties) { properties.name = this.properties.name; this.properties = properties; return this; }
return this;
public Secret setProperties(SecretProperties properties) { Objects.requireNonNull(properties); properties.name = this.properties.name; this.properties = properties; return this; }
class Secret { /** * The value of the secret. */ @JsonProperty(value = "value") private String value; /** * The secret properties. */ private SecretProperties properties; /** * Creates an empty instance of the Secret. */ Secret() { properties = new SecretProperties(); } /** * Creates a Secret with {@code name} and {@code value}. * * @param name The name of the secret. * @param value the value of the secret. */ public Secret(String name, String value) { properties = new SecretProperties(name); this.value = value; } /** * Get the value of the secret. * * @return the secret value */ public String getValue() { return this.value; } /** * Get the secret identifier. * * @return the secret identifier. */ public Secret getId() { properties.getId(); return this; } /** * Get the secret name. * * @return the secret name. */ public String getName() { return properties.getName(); } /** * Get the secret properties * @return the Secret properties */ public SecretProperties getProperties() { return this.properties; } /** * Set the secret properties * @param properties The Secret properties * @return the updated secret object */ @JsonProperty(value = "id") private void unpackId(String id) { properties.unpackId(id); } /** * Unpacks the attributes json response and updates the variables in the Secret Attributes object. * Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are * part of main json body and not attributes json body when the secret response comes from list Secrets operations. * @param attributes The key value mapping of the Secret attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private void unpackAttributes(Map<String, Object> attributes) { properties.unpackAttributes(attributes); } @JsonProperty("managed") private void unpackManaged(Boolean managed) { properties.managed = managed; } @JsonProperty("kid") private void unpackKid(String kid) { properties.keyId = kid; } @JsonProperty("contentType") private void unpackContentType(String contentType) { properties.contentType = contentType; } @JsonProperty("tags") private void unpackTags(Map<String, String> tags) { properties.tags = tags; } }
class Secret { /** * The value of the secret. */ @JsonProperty(value = "value") private String value; /** * The secret properties. */ private SecretProperties properties; /** * Creates an empty instance of the Secret. */ Secret() { properties = new SecretProperties(); } /** * Creates a Secret with {@code name} and {@code value}. * * @param name The name of the secret. * @param value the value of the secret. */ public Secret(String name, String value) { properties = new SecretProperties(name); this.value = value; } /** * Get the value of the secret. * * @return the secret value */ public String getValue() { return this.value; } /** * Get the secret identifier. * * @return the secret identifier. */ public String getId() { return properties.getId(); } /** * Get the secret name. * * @return the secret name. */ public String getName() { return properties.getName(); } /** * Get the secret properties * @return the Secret properties */ public SecretProperties getProperties() { return this.properties; } /** * Set the secret properties * @param properties The Secret properties * @throws NullPointerException if {@code properties} is null. * @return the updated secret object */ @JsonProperty(value = "id") private void unpackId(String id) { properties.unpackId(id); } /** * Unpacks the attributes json response and updates the variables in the Secret Attributes object. * Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are * part of main json body and not attributes json body when the secret response comes from list Secrets operations. * @param attributes The key value mapping of the Secret attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") private void unpackAttributes(Map<String, Object> attributes) { properties.unpackAttributes(attributes); } @JsonProperty("managed") private void unpackManaged(Boolean managed) { properties.managed = managed; } @JsonProperty("kid") private void unpackKid(String kid) { properties.keyId = kid; } @JsonProperty("contentType") private void unpackContentType(String contentType) { properties.contentType = contentType; } @JsonProperty("tags") private void unpackTags(Map<String, String> tags) { properties.tags = tags; } }
Doesn't break the service or code flow. But worth adding the check for user code readability.
public SecretProperties setEnabled(Boolean enabled) { this.enabled = enabled; return this; }
this.enabled = enabled;
public SecretProperties setEnabled(Boolean enabled) { Objects.requireNonNull(enabled); this.enabled = enabled; return this; }
class SecretProperties { /** * The secret id. */ String id; /** * The secret version. */ String version; /** * Determines whether the object is enabled. */ Boolean enabled; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * Expiry date in UTC. */ OffsetDateTime expires; /** * Creation time in UTC. */ OffsetDateTime created; /** * Last updated time in UTC. */ OffsetDateTime updated; /** * The secret name. */ String name; /** * Reflects the deletion recovery level currently in effect for secrets in * the current vault. If it contains 'Purgeable', the secret can be * permanently deleted by a privileged user; otherwise, only the system can * purge the secret, at the end of the retention interval. Possible values * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', * 'Recoverable+ProtectedSubscription'. */ String recoveryLevel; /** * The content type of the secret. */ @JsonProperty(value = "contentType") String contentType; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") Map<String, String> tags; /** * If this is a secret backing a KV certificate, then this field specifies * the corresponding key backing the KV certificate. */ @JsonProperty(value = "kid", access = JsonProperty.Access.WRITE_ONLY) String keyId; /** * True if the secret's lifetime is managed by key vault. If this is a * secret backing a certificate, then managed will be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) Boolean managed; SecretProperties(String secretName) { this.name = secretName; } /** * Creates empty instance of SecretProperties. */ public SecretProperties() {} /** * Get the secret name. * * @return the name of the secret. */ public String getName() { return this.name; } /** * Get the recovery level of the secret. * @return the recoveryLevel of the secret. */ public String getRecoveryLevel() { return recoveryLevel; } /** * Get the enabled value. * * @return the enabled value */ public Boolean isEnabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled The enabled value to set * @return the SecretProperties object itself. */ /** * Get the notBefore UTC time. * * @return the notBefore UTC time. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set * @return the SecretProperties object itself. */ public SecretProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the Secret Expiry time in UTC. * * @return the expires UTC time. */ public OffsetDateTime getExpires() { if (this.expires == null) { return null; } return this.expires; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expires The expiry time to set for the secret. * @return the SecretProperties object itself. */ public SecretProperties setExpires(OffsetDateTime expires) { this.expires = expires; return this; } /** * Get the the UTC time at which secret was created. * * @return the created UTC time. */ public OffsetDateTime getCreated() { return created; } /** * Get the UTC time at which secret was last updated. * * @return the last updated UTC time. */ public OffsetDateTime getUpdated() { return updated; } /** * Get the secret identifier. * * @return the secret identifier. */ public String getId() { return this.id; } /** * Get the content type. * * @return the content type. */ public String getContentType() { return this.contentType; } /** * Set the contentType. * * @param contentType The contentType to set * @return the SecretProperties object itself. */ public SecretProperties setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get the tags associated with the secret. * * @return the value of the tags. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the secret. * * @param tags The tags to set * @return the SecretProperties object itself. */ public SecretProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the keyId identifier. * * @return the keyId identifier. */ public String getKeyId() { return this.keyId; } /** * Get the managed value. * * @return the managed value */ public Boolean isManaged() { return this.managed; } /** * Get the version of the secret. * * @return the version of the secret. */ public String getVersion() { return this.version; } /** * Unpacks the attributes json response and updates the variables in the Secret Attributes object. * Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are * part of main json body and not attributes json body when the secret response comes from list Secrets operations. * @param attributes The key value mapping of the Secret attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expires = epochToOffsetDateTime(attributes.get("exp")); this.created = epochToOffsetDateTime(attributes.get("created")); this.updated = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.contentType = (String) lazyValueSelection(attributes.get("contentType"), this.contentType); this.keyId = (String) lazyValueSelection(attributes.get("keyId"), this.keyId); this.tags = (Map<String, String>) lazyValueSelection(attributes.get("tags"), this.tags); this.managed = (Boolean) lazyValueSelection(attributes.get("managed"), this.managed); unpackId((String) attributes.get("id")); } @JsonProperty(value = "id") void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { e.printStackTrace(); } } } private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } private Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } }
class SecretProperties { private final ClientLogger logger = new ClientLogger(SecretProperties.class); /** * The secret id. */ String id; /** * The secret version. */ String version; /** * Determines whether the object is enabled. */ Boolean enabled; /** * Not before date in UTC. */ OffsetDateTime notBefore; /** * Expiry date in UTC. */ OffsetDateTime expires; /** * Creation time in UTC. */ OffsetDateTime created; /** * Last updated time in UTC. */ OffsetDateTime updated; /** * The secret name. */ String name; /** * Reflects the deletion recovery level currently in effect for secrets in * the current vault. If it contains 'Purgeable', the secret can be * permanently deleted by a privileged user; otherwise, only the system can * purge the secret, at the end of the retention interval. Possible values * include: 'Purgeable', 'Recoverable+Purgeable', 'Recoverable', * 'Recoverable+ProtectedSubscription'. */ String recoveryLevel; /** * The content type of the secret. */ @JsonProperty(value = "contentType") String contentType; /** * Application specific metadata in the form of key-value pairs. */ @JsonProperty(value = "tags") Map<String, String> tags; /** * If this is a secret backing a KV certificate, then this field specifies * the corresponding key backing the KV certificate. */ @JsonProperty(value = "kid", access = JsonProperty.Access.WRITE_ONLY) String keyId; /** * True if the secret's lifetime is managed by key vault. If this is a * secret backing a certificate, then managed will be true. */ @JsonProperty(value = "managed", access = JsonProperty.Access.WRITE_ONLY) Boolean managed; SecretProperties(String secretName) { this.name = secretName; } /** * Creates empty instance of SecretProperties. */ public SecretProperties() { } /** * Get the secret name. * * @return the name of the secret. */ public String getName() { return this.name; } /** * Get the recovery level of the secret. * @return the recoveryLevel of the secret. */ public String getRecoveryLevel() { return recoveryLevel; } /** * Get the enabled value. * * @return the enabled value */ public Boolean isEnabled() { return this.enabled; } /** * Set the enabled value. * * @param enabled The enabled value to set * @throws NullPointerException if {@code enabled} is null. * @return the SecretProperties object itself. */ /** * Get the notBefore UTC time. * * @return the notBefore UTC time. */ public OffsetDateTime getNotBefore() { return notBefore; } /** * Set the {@link OffsetDateTime notBefore} UTC time. * * @param notBefore The notBefore UTC time to set * @return the SecretProperties object itself. */ public SecretProperties setNotBefore(OffsetDateTime notBefore) { this.notBefore = notBefore; return this; } /** * Get the Secret Expiry time in UTC. * * @return the expires UTC time. */ public OffsetDateTime getExpires() { if (this.expires == null) { return null; } return this.expires; } /** * Set the {@link OffsetDateTime expires} UTC time. * * @param expires The expiry time to set for the secret. * @return the SecretProperties object itself. */ public SecretProperties setExpires(OffsetDateTime expires) { this.expires = expires; return this; } /** * Get the the UTC time at which secret was created. * * @return the created UTC time. */ public OffsetDateTime getCreated() { return created; } /** * Get the UTC time at which secret was last updated. * * @return the last updated UTC time. */ public OffsetDateTime getUpdated() { return updated; } /** * Get the secret identifier. * * @return the secret identifier. */ public String getId() { return this.id; } /** * Get the content type. * * @return the content type. */ public String getContentType() { return this.contentType; } /** * Set the contentType. * * @param contentType The contentType to set * @return the updated SecretProperties object itself. */ public SecretProperties setContentType(String contentType) { this.contentType = contentType; return this; } /** * Get the tags associated with the secret. * * @return the value of the tags. */ public Map<String, String> getTags() { return this.tags; } /** * Set the tags to be associated with the secret. * * @param tags The tags to set * @return the updated SecretProperties object itself. */ public SecretProperties setTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Get the keyId identifier. * * @return the keyId identifier. */ public String getKeyId() { return this.keyId; } /** * Get the managed value. * * @return the managed value */ public Boolean isManaged() { return this.managed; } /** * Get the version of the secret. * * @return the version of the secret. */ public String getVersion() { return this.version; } /** * Unpacks the attributes json response and updates the variables in the Secret Attributes object. * Uses Lazy Update to set values for variables id, tags, contentType, managed and keyId as these variables are * part of main json body and not attributes json body when the secret response comes from list Secrets operations. * @param attributes The key value mapping of the Secret attributes */ @JsonProperty("attributes") @SuppressWarnings("unchecked") void unpackAttributes(Map<String, Object> attributes) { this.enabled = (Boolean) attributes.get("enabled"); this.notBefore = epochToOffsetDateTime(attributes.get("nbf")); this.expires = epochToOffsetDateTime(attributes.get("exp")); this.created = epochToOffsetDateTime(attributes.get("created")); this.updated = epochToOffsetDateTime(attributes.get("updated")); this.recoveryLevel = (String) attributes.get("recoveryLevel"); this.contentType = (String) lazyValueSelection(attributes.get("contentType"), this.contentType); this.keyId = (String) lazyValueSelection(attributes.get("keyId"), this.keyId); this.tags = (Map<String, String>) lazyValueSelection(attributes.get("tags"), this.tags); this.managed = (Boolean) lazyValueSelection(attributes.get("managed"), this.managed); unpackId((String) attributes.get("id")); } @JsonProperty(value = "id") void unpackId(String id) { if (id != null && id.length() > 0) { this.id = id; try { URL url = new URL(id); String[] tokens = url.getPath().split("/"); this.name = (tokens.length >= 3 ? tokens[2] : null); this.version = (tokens.length >= 4 ? tokens[3] : null); } catch (MalformedURLException e) { logger.error("Received Malformed Secret Id URL from KV Service"); } } } private OffsetDateTime epochToOffsetDateTime(Object epochValue) { if (epochValue != null) { Instant instant = Instant.ofEpochMilli(((Number) epochValue).longValue() * 1000L); return OffsetDateTime.ofInstant(instant, ZoneOffset.UTC); } return null; } private Object lazyValueSelection(Object input1, Object input2) { if (input1 == null) { return input2; } return input1; } }
Same here. Error message shouldn't include corrective actions. "Host URL is invalid" would be better.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException("Please check the host URL: " + urlBuilder.setHost(host), e)); } return result; }
result = Mono.error(new RuntimeException("Please check the host URL: " + urlBuilder.setHost(host), e));
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL '%s' is invalid.", host), e)); } return result; }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
👍 - this is good as the message is clear about what went wrong.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); if (overwrite || urlBuilder.getPort() == null) { logger.info("Changing port to {}", port); try { context.getHttpRequest().setUrl(urlBuilder.setPort(port).toURL()); } catch (MalformedURLException e) { return Mono.error(new RuntimeException( String.format("Failed to set port %d to http request.", port), e)); } } return next.process(); }
String.format("Failed to set port %d to http request.", port), e));
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); if (overwrite || urlBuilder.getPort() == null) { logger.info("Changing port to {}", port); try { context.getHttpRequest().setUrl(urlBuilder.setPort(port).toURL()); } catch (MalformedURLException e) { return Mono.error(new RuntimeException( String.format("Failed to set the HTTP request port to %d.", port), e)); } } return next.process(); }
class PortPolicy implements HttpPipelinePolicy { private final int port; private final boolean overwrite; private final ClientLogger logger = new ClientLogger(PortPolicy.class); /** * Create a new PortPolicy object. * * @param port The port to set. * @param overwrite Whether or not to overwrite a HttpRequest's port if it already has one. */ public PortPolicy(int port, boolean overwrite) { this.port = port; this.overwrite = overwrite; } @Override }
class PortPolicy implements HttpPipelinePolicy { private final int port; private final boolean overwrite; private final ClientLogger logger = new ClientLogger(PortPolicy.class); /** * Create a new PortPolicy object. * * @param port The port to set. * @param overwrite Whether or not to overwrite a HttpRequest's port if it already has one. */ public PortPolicy(int port, boolean overwrite) { this.port = port; this.overwrite = overwrite; } @Override }
Are you also invoking a method in here to set the host? Is this a desired side-effect?
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL %s is invalid ", urlBuilder.setHost(host)), e)); } return result; }
urlBuilder.setHost(host)), e));
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL '%s' is invalid.", host), e)); } return result; }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
```suggestion result = Mono.error(new RuntimeException(String.format("Host URL '%s' is invalid.", ```
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL %s is invalid ", urlBuilder.setHost(host)), e)); } return result; }
result = Mono.error(new RuntimeException(String.format("Host URL %s is invalid ",
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL '%s' is invalid.", host), e)); } return result; }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
Yeah, this looks really odd. We shouldn't expect side effects from an exception.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL %s is invalid ", urlBuilder.setHost(host)), e)); } return result; }
urlBuilder.setHost(host)), e));
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL '%s' is invalid.", host), e)); } return result; }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
Yes. Good catch. The right logging is String.format("Host URL %s is invalid ", host)
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL %s is invalid ", urlBuilder.setHost(host)), e)); } return result; }
urlBuilder.setHost(host)), e));
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { logger.info("Setting host to {}", host); Mono<HttpResponse> result; final UrlBuilder urlBuilder = UrlBuilder.parse(context.getHttpRequest().getUrl()); try { context.getHttpRequest().setUrl(urlBuilder.setHost(host).toURL()); result = next.process(); } catch (MalformedURLException e) { result = Mono.error(new RuntimeException(String.format("Host URL '%s' is invalid.", host), e)); } return result; }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
class HostPolicy implements HttpPipelinePolicy { private final String host; private final ClientLogger logger = new ClientLogger(HostPolicy.class); /** * Create HostPolicy. * * @param host The host to set on every HttpRequest. */ public HostPolicy(String host) { this.host = host; } @Override }
Would change this to Objects.requireNotnull
public void putCustomEventMapping(final String eventType, final Type eventDataType) { if (eventType == null || eventType.isEmpty()) { throw new IllegalArgumentException("eventType parameter is required and cannot be null or empty"); } if (eventDataType == null) { throw new IllegalArgumentException("eventDataType parameter is required and cannot be null."); } this.eventTypeToEventDataMapping.put(canonicalizeEventType(eventType), eventDataType); }
if (eventDataType == null) {
public void putCustomEventMapping(final String eventType, final Type eventDataType) { if (eventType == null || eventType.isEmpty()) { throw new IllegalArgumentException("eventType parameter is required and cannot be null or empty"); } if (eventDataType == null) { throw new IllegalArgumentException("eventDataType parameter is required and cannot be null"); } this.eventTypeToEventDataMapping.put(canonicalizeEventType(eventType), eventDataType); }
class EventGridSubscriber { /** * The default adapter to be used for de-serializing the events. */ private final AzureJacksonAdapter defaultSerializerAdapter; /** * The map containing user defined mapping of eventType to Java model type. */ private Map<String, Type> eventTypeToEventDataMapping; /** * Creates EventGridSubscriber with default de-serializer. */ @Beta public EventGridSubscriber() { this.defaultSerializerAdapter = new AzureJacksonAdapter(); this.eventTypeToEventDataMapping = new HashMap<>(); } /** * Add a custom event mapping. If a mapping with same eventType exists then the old eventDataType is replaced by * the specified eventDataType. * * @param eventType the event type name. * @param eventDataType type of the Java model that the event type name mapped to. */ @Beta /** * Get type of the Java model that is mapped to the given eventType. * * @param eventType the event type name. * @return type of the Java model if mapping exists, null otherwise. */ @Beta public Type getCustomEventMapping(final String eventType) { if (!containsCustomEventMappingFor(eventType)) { return null; } else { return this.eventTypeToEventDataMapping.get(canonicalizeEventType(eventType)); } } /** * @return get all registered custom event mappings. */ @Beta public Set<Map.Entry<String, Type>> getAllCustomEventMappings() { return Collections.unmodifiableSet(this.eventTypeToEventDataMapping.entrySet()); } /** * Removes the mapping with the given eventType. * * @param eventType the event type name. * @return true if the mapping exists and removed, false if mapping does not exists. */ @Beta public boolean removeCustomEventMapping(final String eventType) { if (!containsCustomEventMappingFor(eventType)) { return false; } else { this.eventTypeToEventDataMapping.remove(canonicalizeEventType(eventType)); return true; } } /** * Checks if an event mapping with the given eventType exists. * * @param eventType the event type name. * @return true if the mapping exists, false otherwise. */ @Beta public boolean containsCustomEventMappingFor(final String eventType) { if (eventType == null || eventType.isEmpty()) { return false; } else { return this.eventTypeToEventDataMapping.containsKey(canonicalizeEventType(eventType)); } } /** * De-serialize the events in the given requested content using default de-serializer. * * @param requestContent the request content in string format. * @return De-serialized events. * * @throws IOException */ @Beta public EventGridEvent[] deserializeEventGridEvents(final String requestContent) throws IOException { return this.deserializeEventGridEvents(requestContent, this.defaultSerializerAdapter); } /** * De-serialize the events in the given requested content using the provided de-serializer. * * @param requestContent the request content as string. * @param serializerAdapter the de-serializer. * @return de-serialized events. * @throws IOException */ @Beta public EventGridEvent[] deserializeEventGridEvents(final String requestContent, final SerializerAdapter<ObjectMapper> serializerAdapter) throws IOException { EventGridEvent[] eventGridEvents = serializerAdapter.<EventGridEvent[]>deserialize(requestContent, EventGridEvent[].class); for (EventGridEvent receivedEvent : eventGridEvents) { if (receivedEvent.data() == null) { continue; } else { final String eventType = receivedEvent.eventType(); final Type eventDataType; if (SystemEventTypeMappings.containsMappingFor(eventType)) { eventDataType = SystemEventTypeMappings.getMapping(eventType); } else if (containsCustomEventMappingFor(eventType)) { eventDataType = getCustomEventMapping(eventType); } else { eventDataType = null; } if (eventDataType != null) { final String eventDataAsString = serializerAdapter.serializeRaw(receivedEvent.data()); final Object eventData = serializerAdapter.<Object>deserialize(eventDataAsString, eventDataType); setEventData(receivedEvent, eventData); } } } return eventGridEvents; } private static void setEventData(EventGridEvent event, final Object data) { try { Field dataField = event.getClass().getDeclaredField("data"); dataField.setAccessible(true); dataField.set(event, data); } catch (NoSuchFieldException nsfe) { throw new RuntimeException(nsfe); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } private static String canonicalizeEventType(final String eventType) { if (eventType == null) { return null; } else { return eventType.toLowerCase(); } } }
class EventGridSubscriber { /** * The default adapter to be used for de-serializing the events. */ private final AzureJacksonAdapter defaultSerializerAdapter; /** * The map containing user defined mapping of eventType to Java model type. */ private Map<String, Type> eventTypeToEventDataMapping; /** * Creates EventGridSubscriber with default de-serializer. */ @Beta public EventGridSubscriber() { this.defaultSerializerAdapter = new AzureJacksonAdapter(); this.eventTypeToEventDataMapping = new HashMap<>(); } /** * Add a custom event mapping. If a mapping with same eventType exists then the old eventDataType is replaced by * the specified eventDataType. * * @param eventType the event type name. * @param eventDataType type of the Java model that the event type name mapped to. */ @Beta /** * Get type of the Java model that is mapped to the given eventType. * * @param eventType the event type name. * @return type of the Java model if mapping exists, null otherwise. */ @Beta public Type getCustomEventMapping(final String eventType) { if (!containsCustomEventMappingFor(eventType)) { return null; } else { return this.eventTypeToEventDataMapping.get(canonicalizeEventType(eventType)); } } /** * @return get all registered custom event mappings. */ @Beta public Set<Map.Entry<String, Type>> getAllCustomEventMappings() { return Collections.unmodifiableSet(this.eventTypeToEventDataMapping.entrySet()); } /** * Removes the mapping with the given eventType. * * @param eventType the event type name. * @return true if the mapping exists and removed, false if mapping does not exists. */ @Beta public boolean removeCustomEventMapping(final String eventType) { if (!containsCustomEventMappingFor(eventType)) { return false; } else { this.eventTypeToEventDataMapping.remove(canonicalizeEventType(eventType)); return true; } } /** * Checks if an event mapping with the given eventType exists. * * @param eventType the event type name. * @return true if the mapping exists, false otherwise. */ @Beta public boolean containsCustomEventMappingFor(final String eventType) { if (eventType == null || eventType.isEmpty()) { return false; } else { return this.eventTypeToEventDataMapping.containsKey(canonicalizeEventType(eventType)); } } /** * De-serialize the events in the given requested content using default de-serializer. * * @param requestContent the request content in string format. * @return De-serialized events. * * @throws IOException */ @Beta public EventGridEvent[] deserializeEventGridEvents(final String requestContent) throws IOException { return this.deserializeEventGridEvents(requestContent, this.defaultSerializerAdapter); } /** * De-serialize the events in the given requested content using the provided de-serializer. * * @param requestContent the request content as string. * @param serializerAdapter the de-serializer. * @return de-serialized events. * @throws IOException */ @Beta public EventGridEvent[] deserializeEventGridEvents(final String requestContent, final SerializerAdapter<ObjectMapper> serializerAdapter) throws IOException { EventGridEvent[] eventGridEvents = serializerAdapter.<EventGridEvent[]>deserialize(requestContent, EventGridEvent[].class); for (EventGridEvent receivedEvent : eventGridEvents) { if (receivedEvent.data() == null) { continue; } else { final String eventType = receivedEvent.eventType(); final Type eventDataType; if (SystemEventTypeMappings.containsMappingFor(eventType)) { eventDataType = SystemEventTypeMappings.getMapping(eventType); } else if (containsCustomEventMappingFor(eventType)) { eventDataType = getCustomEventMapping(eventType); } else { eventDataType = null; } if (eventDataType != null) { final String eventDataAsString = serializerAdapter.serializeRaw(receivedEvent.data()); final Object eventData = serializerAdapter.<Object>deserialize(eventDataAsString, eventDataType); setEventData(receivedEvent, eventData); } } } return eventGridEvents; } private static void setEventData(EventGridEvent event, final Object data) { try { Field dataField = event.getClass().getDeclaredField("data"); dataField.setAccessible(true); dataField.set(event, data); } catch (NoSuchFieldException nsfe) { throw new RuntimeException(nsfe); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } private static String canonicalizeEventType(final String eventType) { if (eventType == null) { return null; } else { return eventType.toLowerCase(); } } }
Why are we creating a new one here instead of having a private final one in the class?
public String serializeRaw(Object object) { final ClientLogger logger = new ClientLogger(JacksonAdapter.class); if (object == null) { return null; } try { return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", ""); } catch (IOException ex) { logger.warning("Failed to serialize {} to JSON.", object.getClass()); return null; } }
final ClientLogger logger = new ClientLogger(JacksonAdapter.class);
public String serializeRaw(Object object) { if (object == null) { return null; } try { return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", ""); } catch (IOException ex) { logger.warning("Failed to serialize {} to JSON.", object.getClass(), ex); return null; } }
class JacksonAdapter implements SerializerAdapter { private final ClientLogger logger = new ClientLogger(JacksonAdapter.class); /** * An instance of {@link ObjectMapper} to serialize/deserialize objects. */ private final ObjectMapper mapper; /** * An instance of {@link ObjectMapper} that does not do flattening. */ private final ObjectMapper simpleMapper; private final XmlMapper xmlMapper; /* * The lazily-created serializer for this ServiceClient. */ private static SerializerAdapter serializerAdapter; /* * BOM header from some response bodies. To be removed in deserialization. */ private static final String BOM = "\uFEFF"; /** * Creates a new JacksonAdapter instance with default mapper settings. */ public JacksonAdapter() { simpleMapper = initializeObjectMapper(new ObjectMapper()); xmlMapper = initializeObjectMapper(new XmlMapper()); xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); xmlMapper.setDefaultUseWrapper(false); ObjectMapper flatteningMapper = initializeObjectMapper(new ObjectMapper()) .registerModule(FlatteningSerializer.getModule(simpleMapper())) .registerModule(FlatteningDeserializer.getModule(simpleMapper())); mapper = initializeObjectMapper(new ObjectMapper()) .registerModule(AdditionalPropertiesSerializer.getModule(flatteningMapper)) .registerModule(AdditionalPropertiesDeserializer.getModule(flatteningMapper)) .registerModule(FlatteningSerializer.getModule(simpleMapper())) .registerModule(FlatteningDeserializer.getModule(simpleMapper())); } /** * Gets a static instance of {@link ObjectMapper} that doesn't handle flattening. * * @return an instance of {@link ObjectMapper}. */ protected ObjectMapper simpleMapper() { return simpleMapper; } /** * maintain singleton instance of the default serializer adapter. * * @return the default serializer */ public static synchronized SerializerAdapter createDefaultSerializerAdapter() { if (serializerAdapter == null) { serializerAdapter = new JacksonAdapter(); } return serializerAdapter; } /** * @return the original serializer type */ public ObjectMapper serializer() { return mapper; } @Override public String serialize(Object object, SerializerEncoding encoding) throws IOException { if (object == null) { return null; } StringWriter writer = new StringWriter(); if (encoding == SerializerEncoding.XML) { xmlMapper.writeValue(writer, object); } else { serializer().writeValue(writer, object); } return writer.toString(); } @Override @Override public String serializeList(List<?> list, CollectionFormat format) { if (list == null) { return null; } List<String> serialized = new ArrayList<>(); for (Object element : list) { String raw = serializeRaw(element); serialized.add(raw != null ? raw : ""); } return String.join(format.getDelimiter(), serialized); } @Override @SuppressWarnings("unchecked") public <T> T deserialize(String value, final Type type, SerializerEncoding encoding) throws IOException { if (value == null || value.isEmpty() || value.equals(BOM)) { return null; } if (value.startsWith(BOM)) { value = value.replaceFirst(BOM, ""); } final JavaType javaType = createJavaType(type); try { if (encoding == SerializerEncoding.XML) { return (T) xmlMapper.readValue(value, javaType); } else { return (T) serializer().readValue(value, javaType); } } catch (JsonParseException jpe) { throw logger.logExceptionAsError(new MalformedValueException(jpe.getMessage(), jpe)); } } /** * Initializes an instance of JacksonMapperAdapter with default configurations * applied to the object mapper. * * @param mapper the object mapper to use. */ private static <T extends ObjectMapper> T initializeObjectMapper(T mapper) { mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .registerModule(new JavaTimeModule()) .registerModule(ByteArraySerializer.getModule()) .registerModule(Base64UrlSerializer.getModule()) .registerModule(DateTimeSerializer.getModule()) .registerModule(DateTimeRfc1123Serializer.getModule()) .registerModule(DurationSerializer.getModule()) .registerModule(HttpHeadersSerializer.getModule()); mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)); return mapper; } private JavaType createJavaType(Type type) { JavaType result; if (type == null) { result = null; } else if (type instanceof JavaType) { result = (JavaType) type; } else if (type instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) type; final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); JavaType[] javaTypeArguments = new JavaType[actualTypeArguments.length]; for (int i = 0; i != actualTypeArguments.length; i++) { javaTypeArguments[i] = createJavaType(actualTypeArguments[i]); } result = mapper .getTypeFactory().constructParametricType((Class<?>) parameterizedType.getRawType(), javaTypeArguments); } else { result = mapper .getTypeFactory().constructType(type); } return result; } }
class JacksonAdapter implements SerializerAdapter { private final ClientLogger logger = new ClientLogger(JacksonAdapter.class); /** * An instance of {@link ObjectMapper} to serialize/deserialize objects. */ private final ObjectMapper mapper; /** * An instance of {@link ObjectMapper} that does not do flattening. */ private final ObjectMapper simpleMapper; private final XmlMapper xmlMapper; private final ObjectMapper headerMapper; /* * The lazily-created serializer for this ServiceClient. */ private static SerializerAdapter serializerAdapter; /* * BOM header from some response bodies. To be removed in deserialization. */ private static final String BOM = "\uFEFF"; /** * Creates a new JacksonAdapter instance with default mapper settings. */ public JacksonAdapter() { simpleMapper = initializeObjectMapper(new ObjectMapper()); xmlMapper = initializeObjectMapper(new XmlMapper()); xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); xmlMapper.setDefaultUseWrapper(false); ObjectMapper flatteningMapper = initializeObjectMapper(new ObjectMapper()) .registerModule(FlatteningSerializer.getModule(simpleMapper())) .registerModule(FlatteningDeserializer.getModule(simpleMapper())); mapper = initializeObjectMapper(new ObjectMapper()) .registerModule(AdditionalPropertiesSerializer.getModule(flatteningMapper)) .registerModule(AdditionalPropertiesDeserializer.getModule(flatteningMapper)) .registerModule(FlatteningSerializer.getModule(simpleMapper())) .registerModule(FlatteningDeserializer.getModule(simpleMapper())); headerMapper = simpleMapper .copy() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); } /** * Gets a static instance of {@link ObjectMapper} that doesn't handle flattening. * * @return an instance of {@link ObjectMapper}. */ protected ObjectMapper simpleMapper() { return simpleMapper; } /** * maintain singleton instance of the default serializer adapter. * * @return the default serializer */ public static synchronized SerializerAdapter createDefaultSerializerAdapter() { if (serializerAdapter == null) { serializerAdapter = new JacksonAdapter(); } return serializerAdapter; } /** * @return the original serializer type */ public ObjectMapper serializer() { return mapper; } @Override public String serialize(Object object, SerializerEncoding encoding) throws IOException { if (object == null) { return null; } StringWriter writer = new StringWriter(); if (encoding == SerializerEncoding.XML) { xmlMapper.writeValue(writer, object); } else { serializer().writeValue(writer, object); } return writer.toString(); } @Override @Override public String serializeList(List<?> list, CollectionFormat format) { if (list == null) { return null; } List<String> serialized = new ArrayList<>(); for (Object element : list) { String raw = serializeRaw(element); serialized.add(raw != null ? raw : ""); } return String.join(format.getDelimiter(), serialized); } @Override @SuppressWarnings("unchecked") public <T> T deserialize(String value, final Type type, SerializerEncoding encoding) throws IOException { if (value == null || value.isEmpty() || value.equals(BOM)) { return null; } if (value.startsWith(BOM)) { value = value.replaceFirst(BOM, ""); } final JavaType javaType = createJavaType(type); try { if (encoding == SerializerEncoding.XML) { return (T) xmlMapper.readValue(value, javaType); } else { return (T) serializer().readValue(value, javaType); } } catch (JsonParseException jpe) { throw logger.logExceptionAsError(new MalformedValueException(jpe.getMessage(), jpe)); } } @Override public <T> T deserialize(HttpHeaders headers, Type deserializedHeadersType) throws IOException { if (deserializedHeadersType == null) { return null; } final String headersJsonString = headerMapper.writeValueAsString(headers); T deserializedHeaders = headerMapper.readValue(headersJsonString, createJavaType(deserializedHeadersType)); final Class<?> deserializedHeadersClass = TypeUtil.getRawClass(deserializedHeadersType); final Field[] declaredFields = deserializedHeadersClass.getDeclaredFields(); for (final Field declaredField : declaredFields) { if (declaredField.isAnnotationPresent(HeaderCollection.class)) { final Type declaredFieldType = declaredField.getGenericType(); if (TypeUtil.isTypeOrSubTypeOf(declaredField.getType(), Map.class)) { final Type[] mapTypeArguments = TypeUtil.getTypeArguments(declaredFieldType); if (mapTypeArguments.length == 2 && mapTypeArguments[0] == String.class && mapTypeArguments[1] == String.class) { final HeaderCollection headerCollectionAnnotation = declaredField.getAnnotation(HeaderCollection.class); final String headerCollectionPrefix = headerCollectionAnnotation.value().toLowerCase(Locale.ROOT); final int headerCollectionPrefixLength = headerCollectionPrefix.length(); if (headerCollectionPrefixLength > 0) { final Map<String, String> headerCollection = new HashMap<>(); for (final HttpHeader header : headers) { final String headerName = header.getName(); if (headerName.toLowerCase(Locale.ROOT).startsWith(headerCollectionPrefix)) { headerCollection.put(headerName.substring(headerCollectionPrefixLength), header.getValue()); } } final boolean declaredFieldAccessibleBackup = declaredField.isAccessible(); try { if (!declaredFieldAccessibleBackup) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { declaredField.setAccessible(true); return null; }); } declaredField.set(deserializedHeaders, headerCollection); } catch (IllegalAccessException ignored) { } finally { if (!declaredFieldAccessibleBackup) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { declaredField.setAccessible(declaredFieldAccessibleBackup); return null; }); } } } } } } } return deserializedHeaders; } /** * Initializes an instance of JacksonMapperAdapter with default configurations * applied to the object mapper. * * @param mapper the object mapper to use. */ private static <T extends ObjectMapper> T initializeObjectMapper(T mapper) { mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .registerModule(new JavaTimeModule()) .registerModule(ByteArraySerializer.getModule()) .registerModule(Base64UrlSerializer.getModule()) .registerModule(DateTimeSerializer.getModule()) .registerModule(DateTimeRfc1123Serializer.getModule()) .registerModule(DurationSerializer.getModule()) .registerModule(HttpHeadersSerializer.getModule()); mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)); return mapper; } private JavaType createJavaType(Type type) { JavaType result; if (type == null) { result = null; } else if (type instanceof JavaType) { result = (JavaType) type; } else if (type instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) type; final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); JavaType[] javaTypeArguments = new JavaType[actualTypeArguments.length]; for (int i = 0; i != actualTypeArguments.length; i++) { javaTypeArguments[i] = createJavaType(actualTypeArguments[i]); } result = mapper .getTypeFactory().constructParametricType((Class<?>) parameterizedType.getRawType(), javaTypeArguments); } else { result = mapper .getTypeFactory().constructType(type); } return result; } }
Log the exception as the last parameter in this.
public String serializeRaw(Object object) { final ClientLogger logger = new ClientLogger(JacksonAdapter.class); if (object == null) { return null; } try { return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", ""); } catch (IOException ex) { logger.warning("Failed to serialize {} to JSON.", object.getClass()); return null; } }
logger.warning("Failed to serialize {} to JSON.", object.getClass());
public String serializeRaw(Object object) { if (object == null) { return null; } try { return serialize(object, SerializerEncoding.JSON).replaceAll("^\"*", "").replaceAll("\"*$", ""); } catch (IOException ex) { logger.warning("Failed to serialize {} to JSON.", object.getClass(), ex); return null; } }
class JacksonAdapter implements SerializerAdapter { private final ClientLogger logger = new ClientLogger(JacksonAdapter.class); /** * An instance of {@link ObjectMapper} to serialize/deserialize objects. */ private final ObjectMapper mapper; /** * An instance of {@link ObjectMapper} that does not do flattening. */ private final ObjectMapper simpleMapper; private final XmlMapper xmlMapper; /* * The lazily-created serializer for this ServiceClient. */ private static SerializerAdapter serializerAdapter; /* * BOM header from some response bodies. To be removed in deserialization. */ private static final String BOM = "\uFEFF"; /** * Creates a new JacksonAdapter instance with default mapper settings. */ public JacksonAdapter() { simpleMapper = initializeObjectMapper(new ObjectMapper()); xmlMapper = initializeObjectMapper(new XmlMapper()); xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); xmlMapper.setDefaultUseWrapper(false); ObjectMapper flatteningMapper = initializeObjectMapper(new ObjectMapper()) .registerModule(FlatteningSerializer.getModule(simpleMapper())) .registerModule(FlatteningDeserializer.getModule(simpleMapper())); mapper = initializeObjectMapper(new ObjectMapper()) .registerModule(AdditionalPropertiesSerializer.getModule(flatteningMapper)) .registerModule(AdditionalPropertiesDeserializer.getModule(flatteningMapper)) .registerModule(FlatteningSerializer.getModule(simpleMapper())) .registerModule(FlatteningDeserializer.getModule(simpleMapper())); } /** * Gets a static instance of {@link ObjectMapper} that doesn't handle flattening. * * @return an instance of {@link ObjectMapper}. */ protected ObjectMapper simpleMapper() { return simpleMapper; } /** * maintain singleton instance of the default serializer adapter. * * @return the default serializer */ public static synchronized SerializerAdapter createDefaultSerializerAdapter() { if (serializerAdapter == null) { serializerAdapter = new JacksonAdapter(); } return serializerAdapter; } /** * @return the original serializer type */ public ObjectMapper serializer() { return mapper; } @Override public String serialize(Object object, SerializerEncoding encoding) throws IOException { if (object == null) { return null; } StringWriter writer = new StringWriter(); if (encoding == SerializerEncoding.XML) { xmlMapper.writeValue(writer, object); } else { serializer().writeValue(writer, object); } return writer.toString(); } @Override @Override public String serializeList(List<?> list, CollectionFormat format) { if (list == null) { return null; } List<String> serialized = new ArrayList<>(); for (Object element : list) { String raw = serializeRaw(element); serialized.add(raw != null ? raw : ""); } return String.join(format.getDelimiter(), serialized); } @Override @SuppressWarnings("unchecked") public <T> T deserialize(String value, final Type type, SerializerEncoding encoding) throws IOException { if (value == null || value.isEmpty() || value.equals(BOM)) { return null; } if (value.startsWith(BOM)) { value = value.replaceFirst(BOM, ""); } final JavaType javaType = createJavaType(type); try { if (encoding == SerializerEncoding.XML) { return (T) xmlMapper.readValue(value, javaType); } else { return (T) serializer().readValue(value, javaType); } } catch (JsonParseException jpe) { throw logger.logExceptionAsError(new MalformedValueException(jpe.getMessage(), jpe)); } } /** * Initializes an instance of JacksonMapperAdapter with default configurations * applied to the object mapper. * * @param mapper the object mapper to use. */ private static <T extends ObjectMapper> T initializeObjectMapper(T mapper) { mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .registerModule(new JavaTimeModule()) .registerModule(ByteArraySerializer.getModule()) .registerModule(Base64UrlSerializer.getModule()) .registerModule(DateTimeSerializer.getModule()) .registerModule(DateTimeRfc1123Serializer.getModule()) .registerModule(DurationSerializer.getModule()) .registerModule(HttpHeadersSerializer.getModule()); mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)); return mapper; } private JavaType createJavaType(Type type) { JavaType result; if (type == null) { result = null; } else if (type instanceof JavaType) { result = (JavaType) type; } else if (type instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) type; final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); JavaType[] javaTypeArguments = new JavaType[actualTypeArguments.length]; for (int i = 0; i != actualTypeArguments.length; i++) { javaTypeArguments[i] = createJavaType(actualTypeArguments[i]); } result = mapper .getTypeFactory().constructParametricType((Class<?>) parameterizedType.getRawType(), javaTypeArguments); } else { result = mapper .getTypeFactory().constructType(type); } return result; } }
class JacksonAdapter implements SerializerAdapter { private final ClientLogger logger = new ClientLogger(JacksonAdapter.class); /** * An instance of {@link ObjectMapper} to serialize/deserialize objects. */ private final ObjectMapper mapper; /** * An instance of {@link ObjectMapper} that does not do flattening. */ private final ObjectMapper simpleMapper; private final XmlMapper xmlMapper; private final ObjectMapper headerMapper; /* * The lazily-created serializer for this ServiceClient. */ private static SerializerAdapter serializerAdapter; /* * BOM header from some response bodies. To be removed in deserialization. */ private static final String BOM = "\uFEFF"; /** * Creates a new JacksonAdapter instance with default mapper settings. */ public JacksonAdapter() { simpleMapper = initializeObjectMapper(new ObjectMapper()); xmlMapper = initializeObjectMapper(new XmlMapper()); xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true); xmlMapper.setDefaultUseWrapper(false); ObjectMapper flatteningMapper = initializeObjectMapper(new ObjectMapper()) .registerModule(FlatteningSerializer.getModule(simpleMapper())) .registerModule(FlatteningDeserializer.getModule(simpleMapper())); mapper = initializeObjectMapper(new ObjectMapper()) .registerModule(AdditionalPropertiesSerializer.getModule(flatteningMapper)) .registerModule(AdditionalPropertiesDeserializer.getModule(flatteningMapper)) .registerModule(FlatteningSerializer.getModule(simpleMapper())) .registerModule(FlatteningDeserializer.getModule(simpleMapper())); headerMapper = simpleMapper .copy() .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); } /** * Gets a static instance of {@link ObjectMapper} that doesn't handle flattening. * * @return an instance of {@link ObjectMapper}. */ protected ObjectMapper simpleMapper() { return simpleMapper; } /** * maintain singleton instance of the default serializer adapter. * * @return the default serializer */ public static synchronized SerializerAdapter createDefaultSerializerAdapter() { if (serializerAdapter == null) { serializerAdapter = new JacksonAdapter(); } return serializerAdapter; } /** * @return the original serializer type */ public ObjectMapper serializer() { return mapper; } @Override public String serialize(Object object, SerializerEncoding encoding) throws IOException { if (object == null) { return null; } StringWriter writer = new StringWriter(); if (encoding == SerializerEncoding.XML) { xmlMapper.writeValue(writer, object); } else { serializer().writeValue(writer, object); } return writer.toString(); } @Override @Override public String serializeList(List<?> list, CollectionFormat format) { if (list == null) { return null; } List<String> serialized = new ArrayList<>(); for (Object element : list) { String raw = serializeRaw(element); serialized.add(raw != null ? raw : ""); } return String.join(format.getDelimiter(), serialized); } @Override @SuppressWarnings("unchecked") public <T> T deserialize(String value, final Type type, SerializerEncoding encoding) throws IOException { if (value == null || value.isEmpty() || value.equals(BOM)) { return null; } if (value.startsWith(BOM)) { value = value.replaceFirst(BOM, ""); } final JavaType javaType = createJavaType(type); try { if (encoding == SerializerEncoding.XML) { return (T) xmlMapper.readValue(value, javaType); } else { return (T) serializer().readValue(value, javaType); } } catch (JsonParseException jpe) { throw logger.logExceptionAsError(new MalformedValueException(jpe.getMessage(), jpe)); } } @Override public <T> T deserialize(HttpHeaders headers, Type deserializedHeadersType) throws IOException { if (deserializedHeadersType == null) { return null; } final String headersJsonString = headerMapper.writeValueAsString(headers); T deserializedHeaders = headerMapper.readValue(headersJsonString, createJavaType(deserializedHeadersType)); final Class<?> deserializedHeadersClass = TypeUtil.getRawClass(deserializedHeadersType); final Field[] declaredFields = deserializedHeadersClass.getDeclaredFields(); for (final Field declaredField : declaredFields) { if (declaredField.isAnnotationPresent(HeaderCollection.class)) { final Type declaredFieldType = declaredField.getGenericType(); if (TypeUtil.isTypeOrSubTypeOf(declaredField.getType(), Map.class)) { final Type[] mapTypeArguments = TypeUtil.getTypeArguments(declaredFieldType); if (mapTypeArguments.length == 2 && mapTypeArguments[0] == String.class && mapTypeArguments[1] == String.class) { final HeaderCollection headerCollectionAnnotation = declaredField.getAnnotation(HeaderCollection.class); final String headerCollectionPrefix = headerCollectionAnnotation.value().toLowerCase(Locale.ROOT); final int headerCollectionPrefixLength = headerCollectionPrefix.length(); if (headerCollectionPrefixLength > 0) { final Map<String, String> headerCollection = new HashMap<>(); for (final HttpHeader header : headers) { final String headerName = header.getName(); if (headerName.toLowerCase(Locale.ROOT).startsWith(headerCollectionPrefix)) { headerCollection.put(headerName.substring(headerCollectionPrefixLength), header.getValue()); } } final boolean declaredFieldAccessibleBackup = declaredField.isAccessible(); try { if (!declaredFieldAccessibleBackup) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { declaredField.setAccessible(true); return null; }); } declaredField.set(deserializedHeaders, headerCollection); } catch (IllegalAccessException ignored) { } finally { if (!declaredFieldAccessibleBackup) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { declaredField.setAccessible(declaredFieldAccessibleBackup); return null; }); } } } } } } } return deserializedHeaders; } /** * Initializes an instance of JacksonMapperAdapter with default configurations * applied to the object mapper. * * @param mapper the object mapper to use. */ private static <T extends ObjectMapper> T initializeObjectMapper(T mapper) { mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) .configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, true) .configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true) .setSerializationInclusion(JsonInclude.Include.NON_NULL) .registerModule(new JavaTimeModule()) .registerModule(ByteArraySerializer.getModule()) .registerModule(Base64UrlSerializer.getModule()) .registerModule(DateTimeSerializer.getModule()) .registerModule(DateTimeRfc1123Serializer.getModule()) .registerModule(DurationSerializer.getModule()) .registerModule(HttpHeadersSerializer.getModule()); mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker() .withFieldVisibility(JsonAutoDetect.Visibility.ANY) .withSetterVisibility(JsonAutoDetect.Visibility.NONE) .withGetterVisibility(JsonAutoDetect.Visibility.NONE) .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE)); return mapper; } private JavaType createJavaType(Type type) { JavaType result; if (type == null) { result = null; } else if (type instanceof JavaType) { result = (JavaType) type; } else if (type instanceof ParameterizedType) { final ParameterizedType parameterizedType = (ParameterizedType) type; final Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); JavaType[] javaTypeArguments = new JavaType[actualTypeArguments.length]; for (int i = 0; i != actualTypeArguments.length; i++) { javaTypeArguments[i] = createJavaType(actualTypeArguments[i]); } result = mapper .getTypeFactory().constructParametricType((Class<?>) parameterizedType.getRawType(), javaTypeArguments); } else { result = mapper .getTypeFactory().constructType(type); } return result; } }
This should log and throw. ClassNotFoundException means the necessary libraries are not loaded at runtime. Instead of logging and ignoring it, we should propagate this exception upwards.
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); final ClientLogger logger = new ClientLogger(HttpResponseBodyDecoder.class); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } else if (TypeUtil.isTypeOrSubTypeOf(token, Flux.class)) { Type t = TypeUtil.getTypeArgument(token); try { if (TypeUtil.isTypeOrSubTypeOf(t, Class.forName( "com.azure.core.management.implementation.OperationStatus"))) { token = t; } } catch (ClassNotFoundException ignored) { logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'."); } } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil.getRestResponseBodyType(token); } try { if (TypeUtil.isTypeOrSubTypeOf(token, Class.forName( "com.azure.core.management.implementation.OperationStatus"))) { token = TypeUtil.getTypeArgument(token); } } catch (ClassNotFoundException ignored) { logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'."); } } return token; }
logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'.");
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); final ClientLogger logger = new ClientLogger(HttpResponseBodyDecoder.class); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } else if (TypeUtil.isTypeOrSubTypeOf(token, Flux.class)) { Type t = TypeUtil.getTypeArgument(token); try { if (TypeUtil.isTypeOrSubTypeOf(t, Class.forName( "com.azure.core.management.implementation.OperationStatus"))) { token = t; } } catch (ClassNotFoundException ignored) { logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'."); } } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil.getRestResponseBodyType(token); } try { if (TypeUtil.isTypeOrSubTypeOf(token, Class.forName( "com.azure.core.management.implementation.OperationStatus"))) { token = TypeUtil.getTypeArgument(token); } } catch (ClassNotFoundException ignored) { logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'."); } } return token; }
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
@anuchandy Could you give me some insights on whether we need to throw exception or silence pass when the method encountered ClassNotFoundException ?
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); final ClientLogger logger = new ClientLogger(HttpResponseBodyDecoder.class); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } else if (TypeUtil.isTypeOrSubTypeOf(token, Flux.class)) { Type t = TypeUtil.getTypeArgument(token); try { if (TypeUtil.isTypeOrSubTypeOf(t, Class.forName( "com.azure.core.management.implementation.OperationStatus"))) { token = t; } } catch (ClassNotFoundException ignored) { logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'."); } } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil.getRestResponseBodyType(token); } try { if (TypeUtil.isTypeOrSubTypeOf(token, Class.forName( "com.azure.core.management.implementation.OperationStatus"))) { token = TypeUtil.getTypeArgument(token); } } catch (ClassNotFoundException ignored) { logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'."); } } return token; }
logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'.");
private static Type extractEntityTypeFromReturnType(HttpResponseDecodeData decodeData) { Type token = decodeData.getReturnType(); final ClientLogger logger = new ClientLogger(HttpResponseBodyDecoder.class); if (token != null) { if (TypeUtil.isTypeOrSubTypeOf(token, Mono.class)) { token = TypeUtil.getTypeArgument(token); } else if (TypeUtil.isTypeOrSubTypeOf(token, Flux.class)) { Type t = TypeUtil.getTypeArgument(token); try { if (TypeUtil.isTypeOrSubTypeOf(t, Class.forName( "com.azure.core.management.implementation.OperationStatus"))) { token = t; } } catch (ClassNotFoundException ignored) { logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'."); } } if (TypeUtil.isTypeOrSubTypeOf(token, Response.class)) { token = TypeUtil.getRestResponseBodyType(token); } try { if (TypeUtil.isTypeOrSubTypeOf(token, Class.forName( "com.azure.core.management.implementation.OperationStatus"))) { token = TypeUtil.getTypeArgument(token); } } catch (ClassNotFoundException ignored) { logger.warning("Failed to find class 'com.azure.core.management.implementation.OperationStatus'."); } } return token; }
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
class instead. wireResponseType = TypeUtil.createParameterizedType(ItemPage.class, resultType); } else { wireResponseType = wireType; }
Change `headers` map to use `ConcurrentHashMap`.
public HttpHeader remove(String name) { return headers.remove(formatKey(name)); }
return headers.remove(formatKey(name));
public HttpHeader remove(String name) { return headers.remove(formatKey(name)); }
class HttpHeaders implements Iterable<HttpHeader> { private final Map<String, HttpHeader> headers = new HashMap<>(); /** * Create an empty HttpHeaders instance. */ public HttpHeaders() { } /** * Create a HttpHeaders instance with the provided initial headers. * * @param headers the map of initial headers */ public HttpHeaders(Map<String, String> headers) { for (final Map.Entry<String, String> header : headers.entrySet()) { this.put(header.getKey(), header.getValue()); } } /** * Create a HttpHeaders instance with the provided initial headers. * * @param headers the collection of initial headers */ public HttpHeaders(Iterable<HttpHeader> headers) { this(); for (final HttpHeader header : headers) { this.put(header.getName(), header.getValue()); } } /** * Gets the number of headers in the collection. * * @return the number of headers in this collection. */ public int getSize() { return headers.size(); } /** * Sets a {@link HttpHeader header} with the given name and value. * * <p>If header with same name already exists then the value will be overwritten.</p> * * @param name the name * @param value the value * @return The updated HttpHeaders object */ public HttpHeaders put(String name, String value) { headers.put(formatKey(name), new HttpHeader(name, value)); return this; } /** * Gets the {@link HttpHeader header} for the provided header name. {@code Null} is returned if the header isn't * found. * * @param name the name of the header to find. * @return the header if found, null otherwise. */ public HttpHeader get(String name) { return headers.get(formatKey(name)); } /** * Removes the {@link HttpHeader header} with the provided header name. {@code Null} is returned if the header * isn't found. * * @param name the name of the header to remove. * @return the header if removed, null otherwise. */ /** * Get the value for the provided header name. {@code Null} is returned if the header name isn't found. * * @param name the name of the header whose value is being retrieved. * @return the value of the header, or null if the header isn't found */ public String getValue(String name) { final HttpHeader header = get(name); return header == null ? null : header.getValue(); } /** * Get the values for the provided header name. {@code Null} is returned if the header name isn't found. * * <p>This returns {@link * * @param name the name of the header whose value is being retrieved. * @return the values of the header, or null if the header isn't found */ public String[] getValues(String name) { final HttpHeader header = get(name); return header == null ? null : header.getValues(); } private String formatKey(final String key) { return key.toLowerCase(Locale.ROOT); } /** * Gets a {@link Map} representation of the HttpHeaders collection. * * @return the headers as map */ public Map<String, String> toMap() { final Map<String, String> result = new HashMap<>(); for (final HttpHeader header : headers.values()) { result.put(header.getName(), header.getValue()); } return result; } @Override public Iterator<HttpHeader> iterator() { return headers.values().iterator(); } /** * Get a {@link Stream} representation of the HttpHeader values in this instance. * * @return A {@link Stream} of all header values in this instance. */ public Stream<HttpHeader> stream() { return headers.values().stream(); } }
class HttpHeaders implements Iterable<HttpHeader> { private final Map<String, HttpHeader> headers = new ConcurrentHashMap<>(); /** * Create an empty HttpHeaders instance. */ public HttpHeaders() { } /** * Create a HttpHeaders instance with the provided initial headers. * * @param headers the map of initial headers */ public HttpHeaders(Map<String, String> headers) { for (final Map.Entry<String, String> header : headers.entrySet()) { this.put(header.getKey(), header.getValue()); } } /** * Create a HttpHeaders instance with the provided initial headers. * * @param headers the collection of initial headers */ public HttpHeaders(Iterable<HttpHeader> headers) { this(); for (final HttpHeader header : headers) { this.put(header.getName(), header.getValue()); } } /** * Gets the number of headers in the collection. * * @return the number of headers in this collection. */ public int getSize() { return headers.size(); } /** * Sets a {@link HttpHeader header} with the given name and value. * * <p>If header with same name already exists then the value will be overwritten.</p> * * @param name the name * @param value the value * @return The updated HttpHeaders object */ public HttpHeaders put(String name, String value) { headers.put(formatKey(name), new HttpHeader(name, value)); return this; } /** * Gets the {@link HttpHeader header} for the provided header name. {@code Null} is returned if the header isn't * found. * * @param name the name of the header to find. * @return the header if found, null otherwise. */ public HttpHeader get(String name) { return headers.get(formatKey(name)); } /** * Removes the {@link HttpHeader header} with the provided header name. {@code Null} is returned if the header * isn't found. * * @param name the name of the header to remove. * @return the header if removed, null otherwise. */ /** * Get the value for the provided header name. {@code Null} is returned if the header name isn't found. * * @param name the name of the header whose value is being retrieved. * @return the value of the header, or null if the header isn't found */ public String getValue(String name) { final HttpHeader header = get(name); return header == null ? null : header.getValue(); } /** * Get the values for the provided header name. {@code Null} is returned if the header name isn't found. * * <p>This returns {@link * * @param name the name of the header whose value is being retrieved. * @return the values of the header, or null if the header isn't found */ public String[] getValues(String name) { final HttpHeader header = get(name); return header == null ? null : header.getValues(); } private String formatKey(final String key) { return key.toLowerCase(Locale.ROOT); } /** * Gets a {@link Map} representation of the HttpHeaders collection. * * @return the headers as map */ public Map<String, String> toMap() { final Map<String, String> result = new HashMap<>(); for (final HttpHeader header : headers.values()) { result.put(header.getName(), header.getValue()); } return result; } @Override public Iterator<HttpHeader> iterator() { return headers.values().iterator(); } /** * Get a {@link Stream} representation of the HttpHeader values in this instance. * * @return A {@link Stream} of all header values in this instance. */ public Stream<HttpHeader> stream() { return headers.values().stream(); } }
I would make use of optional in case key1's value doesn't exist. ```java if (optionalObject.isPresent()) { System.out.printf("Key1 value: %s%n", optionalObject.get()); } else { System.out.println("Key1 does not exist or have data."); } ```
public void getDataContext() { final String key1 = "Key1"; final String value1 = "first-value"; Context context = new Context(key1, value1); Optional<Object> optionalObject = context.getData(key1); System.out.printf("Key1 value : %s%n", optionalObject.get().toString()); }
System.out.printf("Key1 value : %s%n", optionalObject.get().toString());
public void getDataContext() { final String key1 = "Key1"; final String value1 = "first-value"; Context context = new Context(key1, value1); Optional<Object> optionalObject = context.getData(key1); if (optionalObject.isPresent()) { System.out.printf("Key1 value: %s%n", optionalObject.get()); } else { System.out.println("Key1 does not exist or have data."); } }
class ContextJavaDocCodeSnippets { /** * Code snippet for {@link Context */ public void constructContextObject() { final String key1 = "Key1"; final String value1 = "first-value"; Context emptyContext = Context.NONE; Context keyValueContext = new Context(key1, value1); } /** * Code snippet for creating Context object using key-value pair map */ public void contextOfObject() { final String key1 = "Key1"; final String value1 = "first-value"; Map<Object, Object> keyValueMap = new HashMap<>(); keyValueMap.put(key1, value1); Context keyValueContext = Context.of(keyValueMap); System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get().toString()); } /** * Code snippet for {@link Context */ public void addDataToContext() { final String key1 = "Key1"; final String value1 = "first-value"; final String key2 = "Key2"; final String value2 = "second-value"; Context originalContext = new Context(key1, value1); Context updatedContext = originalContext.addData(key2, value2); System.out.printf("Key1 value: %s%n", updatedContext.getData(key1).get().toString()); System.out.printf("Key2 value: %s%n", updatedContext.getData(key2).get().toString()); } /** * Code snippet for {@link Context */ }
class ContextJavaDocCodeSnippets { /** * Code snippet for {@link Context */ public void constructContextObject() { Context emptyContext = Context.NONE; final String userParentSpan = "user-parent-span"; Context keyValueContext = new Context(OPENCENSUS_SPAN_KEY, userParentSpan); } /** * Code snippet for creating Context object using key-value pair map */ public void contextOfObject() { final String key1 = "Key1"; final String value1 = "first-value"; Map<Object, Object> keyValueMap = new HashMap<>(); keyValueMap.put(key1, value1); Context keyValueContext = Context.of(keyValueMap); System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get()); } /** * Code snippet for {@link Context */ public void addDataToContext() { final String hostNameValue = "host-name-value"; final String entityPathValue = "entity-path-value"; final String userParentSpan = "user-parent-span"; Context parentSpanContext = new Context(OPENCENSUS_SPAN_KEY, userParentSpan); Context updatedContext = parentSpanContext.addData(HOST_NAME, hostNameValue) .addData(ENTITY_PATH, entityPathValue); System.out.printf("HOSTNAME value: %s%n", updatedContext.getData(HOST_NAME).get()); System.out.printf("ENTITY_PATH value: %s%n", updatedContext.getData(ENTITY_PATH).get()); } /** * Code snippet for {@link Context */ }
The .toString() isn't necessary, the `%s` formatter will call .toString() on it.
public void contextOfObject() { final String key1 = "Key1"; final String value1 = "first-value"; Map<Object, Object> keyValueMap = new HashMap<>(); keyValueMap.put(key1, value1); Context keyValueContext = Context.of(keyValueMap); System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get().toString()); }
System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get().toString());
public void contextOfObject() { final String key1 = "Key1"; final String value1 = "first-value"; Map<Object, Object> keyValueMap = new HashMap<>(); keyValueMap.put(key1, value1); Context keyValueContext = Context.of(keyValueMap); System.out.printf("Key1 value %s%n", keyValueContext.getData(key1).get()); }
class ContextJavaDocCodeSnippets { /** * Code snippet for {@link Context */ public void constructContextObject() { final String key1 = "Key1"; final String value1 = "first-value"; Context emptyContext = Context.NONE; Context keyValueContext = new Context(key1, value1); } /** * Code snippet for creating Context object using key-value pair map */ /** * Code snippet for {@link Context */ public void addDataToContext() { final String key1 = "Key1"; final String value1 = "first-value"; final String key2 = "Key2"; final String value2 = "second-value"; Context originalContext = new Context(key1, value1); Context updatedContext = originalContext.addData(key2, value2); System.out.printf("Key1 value: %s%n", updatedContext.getData(key1).get().toString()); System.out.printf("Key2 value: %s%n", updatedContext.getData(key2).get().toString()); } /** * Code snippet for {@link Context */ public void getDataContext() { final String key1 = "Key1"; final String value1 = "first-value"; Context context = new Context(key1, value1); Optional<Object> optionalObject = context.getData(key1); System.out.printf("Key1 value : %s%n", optionalObject.get().toString()); } }
class ContextJavaDocCodeSnippets { /** * Code snippet for {@link Context */ public void constructContextObject() { Context emptyContext = Context.NONE; final String userParentSpan = "user-parent-span"; Context keyValueContext = new Context(OPENCENSUS_SPAN_KEY, userParentSpan); } /** * Code snippet for creating Context object using key-value pair map */ /** * Code snippet for {@link Context */ public void addDataToContext() { final String hostNameValue = "host-name-value"; final String entityPathValue = "entity-path-value"; final String userParentSpan = "user-parent-span"; Context parentSpanContext = new Context(OPENCENSUS_SPAN_KEY, userParentSpan); Context updatedContext = parentSpanContext.addData(HOST_NAME, hostNameValue) .addData(ENTITY_PATH, entityPathValue); System.out.printf("HOSTNAME value: %s%n", updatedContext.getData(HOST_NAME).get()); System.out.printf("ENTITY_PATH value: %s%n", updatedContext.getData(ENTITY_PATH).get()); } /** * Code snippet for {@link Context */ public void getDataContext() { final String key1 = "Key1"; final String value1 = "first-value"; Context context = new Context(key1, value1); Optional<Object> optionalObject = context.getData(key1); if (optionalObject.isPresent()) { System.out.printf("Key1 value: %s%n", optionalObject.get()); } else { System.out.println("Key1 does not exist or have data."); } } }
This is getting closer to an implementation that would handle a stream that is buffering slowly but there is an issue that this will have random chunks of data missing. With the current implementation given a scenario where I have 5 100 byte chunks I could have this happen: Read 100 Read 100 Read 10 (slow buffering) Read 10 (slow buffering) Read 100 Throw UnexpectedLengthException, expected 500 got 320 But there could still be more data loading into the stream. Instead there should be a looping mechanism on each concatMap emissions where if I read that 10 I try to read more until one of the following scenarios 1. I have filled by current buffer, wrap this and trigger the next concatMap emission 2. I have hit end of file, wrap this and trigger on complete 3. I have hit end of file and I got less than expected, trigger an error Now the scenario should look like Read 100 Read 100, Read 10 (slow buffering), read 10 (slow buffering), read 80 Read 100 Read 100 Everything is good here, send the data to the service.
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.range(0, (int) Math.ceil((double) length / (double) blockSize)) .map(i -> i * blockSize) .concatMap(pos -> Mono.fromCallable(() -> { long count = pos + blockSize > length ? length - pos : blockSize; byte[] cache = new byte[(int) count]; int lastIndex = data.read(cache); if (lastIndex == -1 && currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } currentTotalLength[0] += lastIndex; return ByteBuffer.wrap(cache); })) .doOnComplete(() -> { try { if (data.available() > 0) { long totalLength = currentTotalLength[0] + data.available(); throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", totalLength, length), totalLength, length)); } } catch (IOException e) { throw LOGGER.logExceptionAsError(new RuntimeException("I/O errors occurs. Error details: " + e.getMessage())); } }); }
if (lastIndex == -1 && currentTotalLength[0] < length) {
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { Pair pair = new Pair(); final long[] currentTotalLength = new long[1]; return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[blockSize]; try { int numBytes = data.read(buffer); if (numBytes > 0) { currentTotalLength[0] += numBytes; return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }) .takeUntil(p -> p.readBytes() == -1 || currentTotalLength[0] > length) .filter(p -> p.readBytes() > 0) .flatMap(p -> { if (currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else if (currentTotalLength[0] > length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else { return Flux.just(p.buffer()); } }); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> Map<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws NullPointerException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new NullPointerException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(String baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the account name from host part of the URL object. * * @param url URL having its hostanme * @return account name. */ public static String getAccountName(URL url) { UrlBuilder builder = UrlBuilder.parse(url); String accountName = null; String host = builder.getHost(); if (!ImplUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { accountName = host; } else { accountName = host.substring(0, accountNameIndex); } } return accountName; } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> Map<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws NullPointerException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new NullPointerException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(String baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the account name from host part of the URL object. * * @param url URL having its hostanme * @return account name. */ public static String getAccountName(URL url) { UrlBuilder builder = UrlBuilder.parse(url); String accountName = null; String host = builder.getHost(); if (!ImplUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { accountName = host; } else { accountName = host.substring(0, accountNameIndex); } } return accountName; } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
Now that we've repeat() and `length` I guess we can simplify this a bit and avoid extra allocation of `Pair` type & avoid extra filter , onComplete and flatmap. We could also move validations to within this map. I didn't test below code but this is something in my mind. ```java public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { final long[] currentTotalLength = new long[1]; return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[blockSize]; int totalBytesRead = 0; while (totalBytesRead < blockSize) { int numBytesRead = data.read(buffer, totalBytesRead, blockSize - totalBytesRead); if (numBytesRead == -1) { break; } else { totalBytesRead += numBytesRead; } } if (totalBytesRead == 0) { // If totalBytesRead is zero after the above loop then means either we reached EOF // or blockSize is zero if (currentTotalLength[0] < length) { throw "Stream has less than provided length!" } else { // Emit an empty ByteBuffer that get filtered out by below takeUntil. return ByteBuffer.wrap(buffer, 0, 0); } } else { currentTotalLength[0] += totalBytesRead; if (currentTotalLength[0] > length) { throw "Stream has more than provided length!" } else { return ByteBuffer.wrap(buffer, 0, totalBytesRead); } } }) .takeUntil(bb -> !bb.hasRemaining()); ```
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { Pair pair = new Pair(); final long[] currentTotalLength = new long[1]; return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[blockSize]; try { int numBytes = data.read(buffer); if (numBytes > 0) { currentTotalLength[0] += numBytes; return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .flatMap(p -> { if (currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else if (currentTotalLength[0] > length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else { return Flux.just(p.buffer()); } }); }
int numBytes = data.read(buffer);
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { Pair pair = new Pair(); final long[] currentTotalLength = new long[1]; return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[blockSize]; try { int numBytes = data.read(buffer); if (numBytes > 0) { currentTotalLength[0] += numBytes; return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }) .takeUntil(p -> p.readBytes() == -1 || currentTotalLength[0] > length) .filter(p -> p.readBytes() > 0) .flatMap(p -> { if (currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else if (currentTotalLength[0] > length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else { return Flux.just(p.buffer()); } }); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> Map<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws NullPointerException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new NullPointerException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(String baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the account name from host part of the URL object. * * @param url URL having its hostanme * @return account name. */ public static String getAccountName(URL url) { UrlBuilder builder = UrlBuilder.parse(url); String accountName = null; String host = builder.getHost(); if (!ImplUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { accountName = host; } else { accountName = host.substring(0, accountNameIndex); } } return accountName; } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> Map<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws NullPointerException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new NullPointerException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(String baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the account name from host part of the URL object. * * @param url URL having its hostanme * @return account name. */ public static String getAccountName(URL url) { UrlBuilder builder = UrlBuilder.parse(url); String accountName = null; String host = builder.getHost(); if (!ImplUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { accountName = host; } else { accountName = host.substring(0, accountNameIndex); } } return accountName; } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
https://github.com/Azure/azure-sdk-for-java/issues/5754 An issue to track the simplification.
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { Pair pair = new Pair(); final long[] currentTotalLength = new long[1]; return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[blockSize]; try { int numBytes = data.read(buffer); if (numBytes > 0) { currentTotalLength[0] += numBytes; return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .flatMap(p -> { if (currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else if (currentTotalLength[0] > length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else { return Flux.just(p.buffer()); } }); }
int numBytes = data.read(buffer);
public static Flux<ByteBuffer> convertStreamToByteBuffer(InputStream data, long length, int blockSize) { Pair pair = new Pair(); final long[] currentTotalLength = new long[1]; return Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[blockSize]; try { int numBytes = data.read(buffer); if (numBytes > 0) { currentTotalLength[0] += numBytes; return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }) .takeUntil(p -> p.readBytes() == -1 || currentTotalLength[0] > length) .filter(p -> p.readBytes() > 0) .flatMap(p -> { if (currentTotalLength[0] < length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, less than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else if (currentTotalLength[0] > length) { throw LOGGER.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes, more than the expected %d bytes.", currentTotalLength[0], length), currentTotalLength[0], length)); } else { return Flux.just(p.buffer()); } }); }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> Map<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws NullPointerException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new NullPointerException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(String baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the account name from host part of the URL object. * * @param url URL having its hostanme * @return account name. */ public static String getAccountName(URL url) { UrlBuilder builder = UrlBuilder.parse(url); String accountName = null; String host = builder.getHost(); if (!ImplUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { accountName = host; } else { accountName = host.substring(0, accountNameIndex); } } return accountName; } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
class Utility { private static final ClientLogger LOGGER = new ClientLogger(Utility.class); private static final String DESERIALIZED_HEADERS = "deserializedHeaders"; private static final String ETAG = "eTag"; public static final DateTimeFormatter ISO_8601_UTC_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT).withZone(ZoneId.of("UTC")); /** * Stores a reference to the date/time pattern with the greatest precision Java.util.Date is capable of expressing. */ private static final String MAX_PRECISION_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss'Z'"; /** * Stores a reference to the ISO8601 date/time pattern. */ private static final String ISO8601_PATTERN_NO_SECONDS = "yyyy-MM-dd'T'HH:mm'Z'"; /** * The length of a datestring that matches the MAX_PRECISION_PATTERN. */ private static final int MAX_PRECISION_DATESTRING_LENGTH = MAX_PRECISION_PATTERN.replaceAll("'", "").length(); /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a string (ex. key=val1,val2,val3 instead of key=[val1, val2, val3]). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String> parseQueryString(final String queryString) { return parseQueryStringHelper(queryString, Utility::urlDecode); } /** * Parses the query string into a key-value pair map that maintains key, query parameter key, order. The value is * stored as a parsed array (ex. key=[val1, val2, val3] instead of key=val1,val2,val3). * * @param queryString Query string to parse * @return a mapping of query string pieces as key-value pairs. */ public static Map<String, String[]> parseQueryStringSplitValues(final String queryString) { return parseQueryStringHelper(queryString, (value) -> urlDecode(value).split(",")); } private static <T> Map<String, T> parseQueryStringHelper(final String queryString, Function<String, T> valueParser) { TreeMap<String, T> pieces = new TreeMap<>(); if (ImplUtils.isNullOrEmpty(queryString)) { return pieces; } for (String kvp : queryString.split("&")) { int equalIndex = kvp.indexOf("="); String key = urlDecode(kvp.substring(0, equalIndex).toLowerCase(Locale.ROOT)); T value = valueParser.apply(kvp.substring(equalIndex + 1)); pieces.putIfAbsent(key, value); } return pieces; } /** * Performs a safe decoding of the passed string, taking care to preserve each {@code +} character rather than * replacing it with a space character. * * @param stringToDecode String value to decode * @return the decoded string value * @throws RuntimeException If the UTF-8 charset isn't supported */ public static String urlDecode(final String stringToDecode) { if (ImplUtils.isNullOrEmpty(stringToDecode)) { return ""; } if (stringToDecode.contains("+")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToDecode.length(); m++) { if (stringToDecode.charAt(m) == '+') { if (m > startDex) { outBuilder.append(decode(stringToDecode.substring(startDex, m))); } outBuilder.append("+"); startDex = m + 1; } } if (startDex != stringToDecode.length()) { outBuilder.append(decode(stringToDecode.substring(startDex))); } return outBuilder.toString(); } else { return decode(stringToDecode); } } /* * Helper method to reduce duplicate calls of URLDecoder.decode */ private static String decode(final String stringToDecode) { try { return URLDecoder.decode(stringToDecode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Performs a safe encoding of the specified string, taking care to insert %20 for each space character instead of * inserting the {@code +} character. * * @param stringToEncode String value to encode * @return the encoded string value * @throws RuntimeException If the UTF-8 charset ins't supported */ public static String urlEncode(final String stringToEncode) { if (stringToEncode == null) { return null; } if (stringToEncode.length() == 0) { return Constants.EMPTY_STRING; } if (stringToEncode.contains(" ")) { StringBuilder outBuilder = new StringBuilder(); int startDex = 0; for (int m = 0; m < stringToEncode.length(); m++) { if (stringToEncode.charAt(m) == ' ') { if (m > startDex) { outBuilder.append(encode(stringToEncode.substring(startDex, m))); } outBuilder.append("%20"); startDex = m + 1; } } if (startDex != stringToEncode.length()) { outBuilder.append(encode(stringToEncode.substring(startDex))); } return outBuilder.toString(); } else { return encode(stringToEncode); } } /* * Helper method to reduce duplicate calls of URLEncoder.encode */ private static String encode(final String stringToEncode) { try { return URLEncoder.encode(stringToEncode, Constants.UTF8_CHARSET); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } /** * Parses the connection string into key-value pair map. * * @param connectionString Connection string to parse * @return a mapping of connection string pieces as key-value pairs. */ public static Map<String, String> parseConnectionString(final String connectionString) { Map<String, String> parts = new HashMap<>(); for (String part : connectionString.split(";")) { String[] kvp = part.split("=", 2); parts.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]); } return parts; } /** * Blocks an asynchronous response with an optional timeout. * * @param response Asynchronous response to block * @param timeout Optional timeout * @param <T> Return type of the asynchronous response * @return the value of the asynchronous response * @throws RuntimeException If the asynchronous response doesn't complete before the timeout expires. */ public static <T> T blockWithOptionalTimeout(Mono<T> response, Duration timeout) { if (timeout == null) { return response.block(); } else { return response.block(timeout); } } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Mono to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Mono. * @return Mono with an applied timeout, if any. */ public static <T> Mono<T> applyOptionalTimeout(Mono<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Applies a timeout to a publisher if the given timeout is not null. * * @param publisher Flux to apply optional timeout to. * @param timeout Optional timeout. * @param <T> Return type of the Flux. * @return Flux with an applied timeout, if any. */ public static <T> Flux<T> applyOptionalTimeout(Flux<T> publisher, Duration timeout) { return timeout == null ? publisher : publisher.timeout(timeout); } /** * Asserts that a value is not {@code null}. * * @param param Name of the parameter * @param value Value of the parameter * @throws NullPointerException If {@code value} is {@code null} */ public static void assertNotNull(final String param, final Object value) { if (value == null) { throw new NullPointerException(String.format(Locale.ROOT, Constants.MessageConstants.ARGUMENT_NULL_OR_EMPTY, param)); } } /** * Asserts that the specified number is in the valid range. The range is inclusive. * * @param param Name of the parameter * @param value Value of the parameter * @param min The minimum allowed value * @param max The maximum allowed value * @throws IllegalArgumentException If {@code value} is less than {@code min} or {@code value} is greater than * {@code max}. */ public static void assertInBounds(final String param, final long value, final long min, final long max) { if (value < min || value > max) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.PARAMETER_NOT_IN_RANGE, param, min, max)); } } /** * Given a String representing a date in a form of the ISO8601 pattern, generates a Date representing it with up to * millisecond precision. * * @param dateString the {@code String} to be interpreted as a <code>Date</code> * @return the corresponding <code>Date</code> object * @throws IllegalArgumentException If {@code dateString} doesn't match an ISO8601 pattern */ public static OffsetDateTime parseDate(String dateString) { String pattern = MAX_PRECISION_PATTERN; switch (dateString.length()) { case 28: case 27: case 26: case 25: case 24: dateString = dateString.substring(0, MAX_PRECISION_DATESTRING_LENGTH); break; case 23: dateString = dateString.replace("Z", "0"); break; case 22: dateString = dateString.replace("Z", "00"); break; case 20: pattern = Utility.ISO8601_PATTERN; break; case 17: pattern = Utility.ISO8601_PATTERN_NO_SECONDS; break; default: throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.INVALID_DATE_STRING, dateString)); } DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ROOT); return LocalDateTime.parse(dateString, formatter).atZone(ZoneOffset.UTC).toOffsetDateTime(); } /** * Wraps any potential error responses from the service and applies post processing of the response's eTag header to * standardize the value. * * @param response Response from a service call * @param errorWrapper Error wrapping function that is applied to the response * @param <T> Value type of the response * @return an updated response with post processing steps applied. */ public static <T> Mono<T> postProcessResponse(Mono<T> response, Function<Mono<T>, Mono<T>> errorWrapper) { return scrubETagHeader(errorWrapper.apply(response)); } /* The service is inconsistent in whether or not the etag header value has quotes. This method will check if the response returns an etag value, and if it does, remove any quotes that may be present to give the user a more predictable format to work with. */ private static <T> Mono<T> scrubETagHeader(Mono<T> unprocessedResponse) { return unprocessedResponse.map(response -> { String eTag = null; try { Object headers = response.getClass().getMethod(DESERIALIZED_HEADERS).invoke(response); Method eTagGetterMethod = headers.getClass().getMethod(ETAG); eTag = (String) eTagGetterMethod.invoke(headers); if (eTag == null) { return response; } eTag = eTag.replace("\"", ""); headers.getClass().getMethod(ETAG, String.class).invoke(headers, eTag); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException | InvocationTargetException ex) { } try { HttpHeaders rawHeaders = (HttpHeaders) response.getClass().getMethod("getHeaders").invoke(response); if (eTag != null) { rawHeaders.put(ETAG, eTag); } else { HttpHeader eTagHeader = rawHeaders.get(ETAG); if (eTagHeader != null && eTagHeader.getValue() != null) { eTag = eTagHeader.getValue().replace("\"", ""); rawHeaders.put(ETAG, eTag); } } } catch (NoSuchMethodException e) { } catch (IllegalAccessException | InvocationTargetException e) { } return response; }); } /** * Computes a signature for the specified string using the HMAC-SHA256 algorithm. * * @param base64Key Base64 encoded key used to sign the string * @param stringToSign UTF-8 encoded string to sign * @return the HMAC-SHA256 encoded signature * @throws RuntimeException If the HMAC-SHA256 algorithm isn't support, if the key isn't a valid Base64 encoded * string, or the UTF-8 charset isn't supported. */ public static String computeHMac256(final String base64Key, final String stringToSign) { try { byte[] key = Base64.getDecoder().decode(base64Key); Mac hmacSHA256 = Mac.getInstance("HmacSHA256"); hmacSHA256.init(new SecretKeySpec(key, "HmacSHA256")); byte[] utf8Bytes = stringToSign.getBytes(StandardCharsets.UTF_8); return Base64.getEncoder().encodeToString(hmacSHA256.doFinal(utf8Bytes)); } catch (NoSuchAlgorithmException | InvalidKeyException ex) { throw new RuntimeException(ex); } } /** * Appends a string to the end of the passed URL's path. * * @param baseURL URL having a path appended * @param name Name of the path * @return a URL with the path appended. * @throws IllegalArgumentException If {@code name} causes the URL to become malformed. */ public static URL appendToURLPath(String baseURL, String name) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null) { builder.setPath("/"); } else if (!builder.getPath().endsWith("/")) { builder.setPath(builder.getPath() + "/"); } builder.setPath(builder.getPath() + name); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Strips the account name from host part of the URL object. * * @param url URL having its hostanme * @return account name. */ public static String getAccountName(URL url) { UrlBuilder builder = UrlBuilder.parse(url); String accountName = null; String host = builder.getHost(); if (!ImplUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { accountName = host; } else { accountName = host.substring(0, accountNameIndex); } } return accountName; } /** * Strips the last path segment from the passed URL. * * @param baseURL URL having its last path segment stripped * @return a URL with the path segment stripped. * @throws IllegalArgumentException If stripping the last path segment causes the URL to become malformed or it * doesn't contain any path segments. */ public static URL stripLastPathSegment(URL baseURL) { UrlBuilder builder = UrlBuilder.parse(baseURL); if (builder.getPath() == null || !builder.getPath().contains("/")) { throw new IllegalArgumentException(String.format(Locale.ROOT, Constants.MessageConstants.NO_PATH_SEGMENTS, baseURL)); } builder.setPath(builder.getPath().substring(0, builder.getPath().lastIndexOf("/"))); try { return builder.toURL(); } catch (MalformedURLException ex) { throw new IllegalArgumentException(ex); } } /** * Searches for a {@link SharedKeyCredential} in the passed {@link HttpPipeline}. * * @param httpPipeline Pipeline being searched * @return a SharedKeyCredential if the pipeline contains one, otherwise null. */ public static SharedKeyCredential getSharedKeyCredential(HttpPipeline httpPipeline) { for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy httpPipelinePolicy = httpPipeline.getPolicy(i); if (httpPipelinePolicy instanceof SharedKeyCredentialPolicy) { SharedKeyCredentialPolicy sharedKeyCredentialPolicy = (SharedKeyCredentialPolicy) httpPipelinePolicy; return sharedKeyCredentialPolicy.sharedKeyCredential(); } } return null; } /** * A utility method for converting the input stream to Flux of ByteBuffer. Will check the equality of entity length * and the input length. * * @param data The input data which needs to convert to ByteBuffer. * @param length The expected input data length. * @param blockSize The size of each ByteBuffer. * @return {@link ByteBuffer} which contains the input data. * @throws UnexpectedLengthException when input data length mismatch input length. * @throws RuntimeException When I/O error occurs. */ private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
I would replace Objects.requireNotNull to fit the java SDK guidelines.
public Context(Object key, Object value) { if (key == null) { throw new IllegalArgumentException("key cannot be null."); } this.parent = null; this.key = key; this.value = value; }
if (key == null) {
public Context(Object key, Object value) { this.parent = null; this.key = Objects.requireNonNull(key, "'key' cannot be null."); this.value = value; }
class Context { private final ClientLogger logger = new ClientLogger(Context.class); /** * Signifies that no data need be passed to the pipeline. */ public static final Context NONE = new Context(null, null, null); private final Context parent; private final Object key; private final Object value; /** * Constructs a new {@link Context} object. * * @param key the key * @param value the value * @throws IllegalArgumentException If {@code key} is {@code null}. */ private Context(Context parent, Object key, Object value) { this.parent = parent; this.key = key; this.value = value; } /** * Adds a new immutable {@link Context} object with the specified key-value pair to * the existing {@link Context} chain. * * @param key the key * @param value the value * @return the new {@link Context} object containing the specified pair added to the set of pairs * @throws IllegalArgumentException If {@code key} is {@code null}. */ public Context addData(Object key, Object value) { if (key == null) { throw logger.logExceptionAsError(new IllegalArgumentException("key cannot be null")); } return new Context(this, key, value); } /** * Creates a new immutable {@link Context} object with all the keys and values provided by * the input {@link Map} * * @param keyValues The input key value pairs that will be added to this context * @return Context object containing all the key-value pairs in the input map * @throws IllegalArgumentException If {@code keyValues} is {@code null} or empty */ public static Context of(Map<Object, Object> keyValues) { if (ImplUtils.isNullOrEmpty(keyValues)) { throw new IllegalArgumentException("Key value map cannot be null or empty"); } Context context = null; for (Map.Entry<Object, Object> entry : keyValues.entrySet()) { if (context == null) { context = new Context(entry.getKey(), entry.getValue()); } else { context = context.addData(entry.getKey(), entry.getValue()); } } return context; } /** * Scans the linked-list of {@link Context} objects looking for one with the specified key. * Note that the first key found, i.e. the most recently added, will be returned. * * @param key the key to search for * @return the value of the key if it exists * @throws IllegalArgumentException If {@code key} is {@code null}. */ public Optional<Object> getData(Object key) { if (key == null) { throw logger.logExceptionAsError(new IllegalArgumentException("key cannot be null")); } for (Context c = this; c != null; c = c.parent) { if (key.equals(c.key)) { return Optional.of(c.value); } } return Optional.empty(); } }
class Context { private final ClientLogger logger = new ClientLogger(Context.class); /** * Signifies that no data need be passed to the pipeline. */ public static final Context NONE = new Context(null, null, null); private final Context parent; private final Object key; private final Object value; /** * Constructs a new {@link Context} object. * * @param key the key * @param value the value * @throws IllegalArgumentException If {@code key} is {@code null}. */ private Context(Context parent, Object key, Object value) { this.parent = parent; this.key = key; this.value = value; } /** * Adds a new immutable {@link Context} object with the specified key-value pair to * the existing {@link Context} chain. * * @param key the key * @param value the value * @return the new {@link Context} object containing the specified pair added to the set of pairs * @throws IllegalArgumentException If {@code key} is {@code null}. */ public Context addData(Object key, Object value) { if (key == null) { throw logger.logExceptionAsError(new IllegalArgumentException("key cannot be null")); } return new Context(this, key, value); } /** * Creates a new immutable {@link Context} object with all the keys and values provided by * the input {@link Map} * * @param keyValues The input key value pairs that will be added to this context * @return Context object containing all the key-value pairs in the input map * @throws IllegalArgumentException If {@code keyValues} is {@code null} or empty */ public static Context of(Map<Object, Object> keyValues) { if (ImplUtils.isNullOrEmpty(keyValues)) { throw new IllegalArgumentException("Key value map cannot be null or empty"); } Context context = null; for (Map.Entry<Object, Object> entry : keyValues.entrySet()) { if (context == null) { context = new Context(entry.getKey(), entry.getValue()); } else { context = context.addData(entry.getKey(), entry.getValue()); } } return context; } /** * Scans the linked-list of {@link Context} objects looking for one with the specified key. * Note that the first key found, i.e. the most recently added, will be returned. * * @param key the key to search for * @return the value of the key if it exists * @throws IllegalArgumentException If {@code key} is {@code null}. */ public Optional<Object> getData(Object key) { if (key == null) { throw logger.logExceptionAsError(new IllegalArgumentException("key cannot be null")); } for (Context c = this; c != null; c = c.parent) { if (key.equals(c.key)) { return Optional.of(c.value); } } return Optional.empty(); } }
I just noticed the package name this change exists in. The packages that start with `microsoft-azure-*` are owned by the service team rather than us. We own the ones that are start with `azure-*` (ie. azure-core, azure-messaging-eventhubs). Consequently, we try not to change existing behaviour of their client libraries. Could you please revert this?
public void putCustomEventMapping(final String eventType, final Type eventDataType) { Objects.requireNonNull(eventType, "'eventType' cannot be null."); if ( eventType.isEmpty()) { throw new IllegalArgumentException("eventType parameter is required and cannot be empty"); } Objects.requireNonNull(eventType, "'eventDataType' cannot be null."); this.eventTypeToEventDataMapping.put(canonicalizeEventType(eventType), eventDataType); }
Objects.requireNonNull(eventType, "'eventType' cannot be null.");
public void putCustomEventMapping(final String eventType, final Type eventDataType) { if (eventType == null || eventType.isEmpty()) { throw new IllegalArgumentException("eventType parameter is required and cannot be null or empty"); } if (eventDataType == null) { throw new IllegalArgumentException("eventDataType parameter is required and cannot be null"); } this.eventTypeToEventDataMapping.put(canonicalizeEventType(eventType), eventDataType); }
class EventGridSubscriber { /** * The default adapter to be used for de-serializing the events. */ private final AzureJacksonAdapter defaultSerializerAdapter; /** * The map containing user defined mapping of eventType to Java model type. */ private Map<String, Type> eventTypeToEventDataMapping; /** * Creates EventGridSubscriber with default de-serializer. */ @Beta public EventGridSubscriber() { this.defaultSerializerAdapter = new AzureJacksonAdapter(); this.eventTypeToEventDataMapping = new HashMap<>(); } /** * Add a custom event mapping. If a mapping with same eventType exists then the old eventDataType is replaced by * the specified eventDataType. * * @param eventType the event type name. * @param eventDataType type of the Java model that the event type name mapped to. */ @Beta /** * Get type of the Java model that is mapped to the given eventType. * * @param eventType the event type name. * @return type of the Java model if mapping exists, null otherwise. */ @Beta public Type getCustomEventMapping(final String eventType) { if (!containsCustomEventMappingFor(eventType)) { return null; } else { return this.eventTypeToEventDataMapping.get(canonicalizeEventType(eventType)); } } /** * @return get all registered custom event mappings. */ @Beta public Set<Map.Entry<String, Type>> getAllCustomEventMappings() { return Collections.unmodifiableSet(this.eventTypeToEventDataMapping.entrySet()); } /** * Removes the mapping with the given eventType. * * @param eventType the event type name. * @return true if the mapping exists and removed, false if mapping does not exists. */ @Beta public boolean removeCustomEventMapping(final String eventType) { if (!containsCustomEventMappingFor(eventType)) { return false; } else { this.eventTypeToEventDataMapping.remove(canonicalizeEventType(eventType)); return true; } } /** * Checks if an event mapping with the given eventType exists. * * @param eventType the event type name. * @return true if the mapping exists, false otherwise. */ @Beta public boolean containsCustomEventMappingFor(final String eventType) { if (eventType == null || eventType.isEmpty()) { return false; } else { return this.eventTypeToEventDataMapping.containsKey(canonicalizeEventType(eventType)); } } /** * De-serialize the events in the given requested content using default de-serializer. * * @param requestContent the request content in string format. * @return De-serialized events. * * @throws IOException */ @Beta public EventGridEvent[] deserializeEventGridEvents(final String requestContent) throws IOException { return this.deserializeEventGridEvents(requestContent, this.defaultSerializerAdapter); } /** * De-serialize the events in the given requested content using the provided de-serializer. * * @param requestContent the request content as string. * @param serializerAdapter the de-serializer. * @return de-serialized events. * @throws IOException */ @Beta public EventGridEvent[] deserializeEventGridEvents(final String requestContent, final SerializerAdapter<ObjectMapper> serializerAdapter) throws IOException { EventGridEvent[] eventGridEvents = serializerAdapter.<EventGridEvent[]>deserialize(requestContent, EventGridEvent[].class); for (EventGridEvent receivedEvent : eventGridEvents) { if (receivedEvent.data() == null) { continue; } else { final String eventType = receivedEvent.eventType(); final Type eventDataType; if (SystemEventTypeMappings.containsMappingFor(eventType)) { eventDataType = SystemEventTypeMappings.getMapping(eventType); } else if (containsCustomEventMappingFor(eventType)) { eventDataType = getCustomEventMapping(eventType); } else { eventDataType = null; } if (eventDataType != null) { final String eventDataAsString = serializerAdapter.serializeRaw(receivedEvent.data()); final Object eventData = serializerAdapter.<Object>deserialize(eventDataAsString, eventDataType); setEventData(receivedEvent, eventData); } } } return eventGridEvents; } private static void setEventData(EventGridEvent event, final Object data) { try { Field dataField = event.getClass().getDeclaredField("data"); dataField.setAccessible(true); dataField.set(event, data); } catch (NoSuchFieldException nsfe) { throw new RuntimeException(nsfe); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } private static String canonicalizeEventType(final String eventType) { if (eventType == null) { return null; } else { return eventType.toLowerCase(); } } }
class EventGridSubscriber { /** * The default adapter to be used for de-serializing the events. */ private final AzureJacksonAdapter defaultSerializerAdapter; /** * The map containing user defined mapping of eventType to Java model type. */ private Map<String, Type> eventTypeToEventDataMapping; /** * Creates EventGridSubscriber with default de-serializer. */ @Beta public EventGridSubscriber() { this.defaultSerializerAdapter = new AzureJacksonAdapter(); this.eventTypeToEventDataMapping = new HashMap<>(); } /** * Add a custom event mapping. If a mapping with same eventType exists then the old eventDataType is replaced by * the specified eventDataType. * * @param eventType the event type name. * @param eventDataType type of the Java model that the event type name mapped to. */ @Beta /** * Get type of the Java model that is mapped to the given eventType. * * @param eventType the event type name. * @return type of the Java model if mapping exists, null otherwise. */ @Beta public Type getCustomEventMapping(final String eventType) { if (!containsCustomEventMappingFor(eventType)) { return null; } else { return this.eventTypeToEventDataMapping.get(canonicalizeEventType(eventType)); } } /** * @return get all registered custom event mappings. */ @Beta public Set<Map.Entry<String, Type>> getAllCustomEventMappings() { return Collections.unmodifiableSet(this.eventTypeToEventDataMapping.entrySet()); } /** * Removes the mapping with the given eventType. * * @param eventType the event type name. * @return true if the mapping exists and removed, false if mapping does not exists. */ @Beta public boolean removeCustomEventMapping(final String eventType) { if (!containsCustomEventMappingFor(eventType)) { return false; } else { this.eventTypeToEventDataMapping.remove(canonicalizeEventType(eventType)); return true; } } /** * Checks if an event mapping with the given eventType exists. * * @param eventType the event type name. * @return true if the mapping exists, false otherwise. */ @Beta public boolean containsCustomEventMappingFor(final String eventType) { if (eventType == null || eventType.isEmpty()) { return false; } else { return this.eventTypeToEventDataMapping.containsKey(canonicalizeEventType(eventType)); } } /** * De-serialize the events in the given requested content using default de-serializer. * * @param requestContent the request content in string format. * @return De-serialized events. * * @throws IOException */ @Beta public EventGridEvent[] deserializeEventGridEvents(final String requestContent) throws IOException { return this.deserializeEventGridEvents(requestContent, this.defaultSerializerAdapter); } /** * De-serialize the events in the given requested content using the provided de-serializer. * * @param requestContent the request content as string. * @param serializerAdapter the de-serializer. * @return de-serialized events. * @throws IOException */ @Beta public EventGridEvent[] deserializeEventGridEvents(final String requestContent, final SerializerAdapter<ObjectMapper> serializerAdapter) throws IOException { EventGridEvent[] eventGridEvents = serializerAdapter.<EventGridEvent[]>deserialize(requestContent, EventGridEvent[].class); for (EventGridEvent receivedEvent : eventGridEvents) { if (receivedEvent.data() == null) { continue; } else { final String eventType = receivedEvent.eventType(); final Type eventDataType; if (SystemEventTypeMappings.containsMappingFor(eventType)) { eventDataType = SystemEventTypeMappings.getMapping(eventType); } else if (containsCustomEventMappingFor(eventType)) { eventDataType = getCustomEventMapping(eventType); } else { eventDataType = null; } if (eventDataType != null) { final String eventDataAsString = serializerAdapter.serializeRaw(receivedEvent.data()); final Object eventData = serializerAdapter.<Object>deserialize(eventDataAsString, eventDataType); setEventData(receivedEvent, eventData); } } } return eventGridEvents; } private static void setEventData(EventGridEvent event, final Object data) { try { Field dataField = event.getClass().getDeclaredField("data"); dataField.setAccessible(true); dataField.set(event, data); } catch (NoSuchFieldException nsfe) { throw new RuntimeException(nsfe); } catch (IllegalAccessException iae) { throw new RuntimeException(iae); } } private static String canonicalizeEventType(final String eventType) { if (eventType == null) { return null; } else { return eventType.toLowerCase(); } } }
Could you please revert this change in behaviour?
private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { Objects.requireNonNull(queueDescription, "'queueDescription' cannot be null."); QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; }
Objects.requireNonNull(queueDescription, "'queueDescription' cannot be null.");
private CompletableFuture<QueueDescription> putQueueAsync(QueueDescription queueDescription, boolean isUpdate) { if (queueDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } QueueDescriptionSerializer.normalizeDescription(queueDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = QueueDescriptionSerializer.serialize(queueDescription); } catch (ServiceBusException e) { final CompletableFuture<QueueDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<QueueDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(queueDescription.path, atomRequest, isUpdate, queueDescription.getForwardTo(), queueDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); this.asyncHttpClient = asyncHttpClient(clientBuilder); } /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null."); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null."); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null."); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
class ManagementClientAsync { private static final Logger TRACE_LOGGER = LoggerFactory.getLogger(ManagementClientAsync.class); private static final int ONE_BOX_HTTPS_PORT = 4446; private static final String API_VERSION_QUERY = "api-version=2017-04"; private static final String USER_AGENT_HEADER_NAME = "User-Agent"; private static final String AUTHORIZATION_HEADER_NAME = "Authorization"; private static final String CONTENT_TYPE_HEADER_NAME = "Content-Type"; private static final String CONTENT_TYPE = "application/atom+xml"; private static final Duration CONNECTION_TIMEOUT = Duration.ofMinutes(1); private static final String USER_AGENT = String.format("%s/%s(%s)", ClientConstants.PRODUCT_NAME, ClientConstants.CURRENT_JAVACLIENT_VERSION, ClientConstants.PLATFORM_INFO); private ClientSettings clientSettings; private URI namespaceEndpointURI; private AsyncHttpClient asyncHttpClient; /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param connectionStringBuilder - connectionStringBuilder containing namespace information and client settings. */ public ManagementClientAsync(ConnectionStringBuilder connectionStringBuilder) { this(connectionStringBuilder.getEndpoint(), Util.getClientSettingsFromConnectionStringBuilder(connectionStringBuilder)); } /** * Creates a new {@link ManagementClientAsync}. * User should call {@link ManagementClientAsync * @param namespaceEndpointURI - URI of the namespace connecting to. * @param clientSettings - client settings. */ public ManagementClientAsync(URI namespaceEndpointURI, ClientSettings clientSettings) { this.namespaceEndpointURI = namespaceEndpointURI; this.clientSettings = clientSettings; DefaultAsyncHttpClientConfig.Builder clientBuilder = Dsl.config() .setConnectTimeout((int) CONNECTION_TIMEOUT.toMillis()) .setRequestTimeout((int) this.clientSettings.getOperationTimeout().toMillis()); this.asyncHttpClient = asyncHttpClient(clientBuilder); } /** * Retrieves information related to the namespace. * Works with any claim (Send/Listen/Manage). * @return - {@link NamespaceInfo} containing namespace information. */ public CompletableFuture<NamespaceInfo> getNamespaceInfoAsync() { CompletableFuture<String> contentFuture = getEntityAsync("$namespaceinfo", null, false); CompletableFuture<NamespaceInfo> nsInfoFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { nsInfoFuture.completeExceptionally(ex); } else { try { nsInfoFuture.complete(NamespaceInfoSerializer.parseFromContent(content)); } catch (ServiceBusException e) { nsInfoFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return nsInfoFuture; } /** * Retrieves a queue from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - QueueDescription containing information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueDescription> getQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<QueueDescription> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the runtime information of a queue. * @param path - The path of the queue relative to service bus namespace. * @return - QueueRuntimeInfo containing runtime information about the queue. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<QueueRuntimeInfo> getQueueRuntimeInfoAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<QueueRuntimeInfo> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { try { qdFuture.complete(QueueRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { qdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves a topic from the service namespace * @param path - The path of the queue relative to service bus namespace. * @return - Description containing information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicDescription> getTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<TopicDescription> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the runtime information of a topic * @param path - The path of the queue relative to service bus namespace. * @return - TopicRuntimeInfo containing runtime information about the topic. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<TopicRuntimeInfo> getTopicRuntimeInfoAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<TopicRuntimeInfo> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { try { tdFuture.complete(TopicRuntimeInfoSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { tdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves a subscription for a given topic from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionDescription> getSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<SubscriptionDescription> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the runtime information of a subscription in a given topic * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription * @return - SubscriptionRuntimeInfo containing the runtime information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<SubscriptionRuntimeInfo> getSubscriptionRuntimeInfoAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, true); CompletableFuture<SubscriptionRuntimeInfo> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { try { sdFuture.complete(SubscriptionRuntimeInfoSerializer.parseFromContent(topicPath, content)); } catch (MessagingEntityNotFoundException e) { sdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves a rule for a given topic and subscription from the service namespace * @param topicPath - The path of the topic relative to service bus namespace. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return - RuleDescription containing information about the subscription. * @throws IllegalArgumentException - Thrown if path is null, empty, or not in right format or length. */ public CompletableFuture<RuleDescription> getRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); CompletableFuture<String> contentFuture = getEntityAsync(path, null, false); CompletableFuture<RuleDescription> rdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rdFuture.completeExceptionally(ex); } else { try { rdFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { rdFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rdFuture; } /** * Retrieves the list of queues present in the namespace. * @return the first 100 queues. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync() { return getQueuesAsync(100, 0); } /** * Retrieves the list of queues present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of queues. * @param count - The number of queues to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of queues to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<QueueDescription>> getQueuesAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/queues", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<QueueDescription>> qdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { qdFuture.completeExceptionally(ex); } else { qdFuture.complete(QueueDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return qdFuture; } /** * Retrieves the list of topics present in the namespace. * @return the first 100 topics. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync() { return getTopicsAsync(100, 0); } /** * Retrieves the list of topics present in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of topics. * @param count - The number of topics to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of topics to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<TopicDescription>> getTopicsAsync(int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } CompletableFuture<String> contentFuture = getEntityAsync("$Resources/topics", String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<TopicDescription>> tdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { tdFuture.completeExceptionally(ex); } else { tdFuture.complete(TopicDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return tdFuture; } /** * Retrieves the list of subscriptions for a given topic in the namespace. * @param topicName - The name of the topic. * @return the first 100 subscriptions. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName) { return getSubscriptionsAsync(topicName, 100, 0); } /** * Retrieves the list of subscriptions for a given topic in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of subscriptions. * @param topicName - The name of the topic. * @param count - The number of subscriptions to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of subscriptions to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<SubscriptionDescription>> getSubscriptionsAsync(String topicName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); CompletableFuture<String> contentFuture = getEntityAsync(String.format("%s/Subscriptions", topicName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<SubscriptionDescription>> sdFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { sdFuture.completeExceptionally(ex); } else { sdFuture.complete(SubscriptionDescriptionSerializer.parseCollectionFromContent(topicName, content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return sdFuture; } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @return the first 100 rules. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName) { return getRulesAsync(topicName, subscriptionName, 100, 0); } /** * Retrieves the list of rules for a given topic-subscription in the namespace. * You can simulate pages of list of entities by manipulating count and skip parameters. * skip(0)+count(100) gives first 100 entities. skip(100)+count(100) gives the next 100 entities. * @return the list of rules. * @param topicName - The name of the topic. * @param subscriptionName - The name of the subscription. * @param count - The number of rules to fetch. Defaults to 100. Maximum value allowed is 100. * @param skip - The number of rules to skip. Defaults to 0. Cannot be negative. */ public CompletableFuture<List<RuleDescription>> getRulesAsync(String topicName, String subscriptionName, int count, int skip) { if (count > 100 || count < 1) { throw new IllegalArgumentException("Count should be between 1 and 100"); } if (skip < 0) { throw new IllegalArgumentException("Skip cannot be negative"); } EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<String> contentFuture = getEntityAsync( String.format("%s/Subscriptions/%s/rules", topicName, subscriptionName), String.format("$skip=%d&$top=%d", skip, count), false); CompletableFuture<List<RuleDescription>> rulesFuture = new CompletableFuture<>(); contentFuture.handleAsync((content, ex) -> { if (ex != null) { rulesFuture.completeExceptionally(ex); } else { rulesFuture.complete(RuleDescriptionSerializer.parseCollectionFromContent(content)); } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return rulesFuture; } private CompletableFuture<String> getEntityAsync(String path, String query, boolean enrich) { String queryString = API_VERSION_QUERY + "&enrich=" + enrich; if (query != null) { queryString = queryString + "&" + query; } URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, queryString); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.GET, entityURL, null, null); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queuePath - The name of the queue relative to the service namespace base address. * @return {@link QueueDescription} of the newly created queue. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<QueueDescription> createQueueAsync(String queuePath) { return this.createQueueAsync(new QueueDescription(queuePath)); } /** * Creates a new queue in the service namespace with the given name. * See {@link QueueDescription} for default values of queue properties. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the new queue will be created. * @return {@link QueueDescription} of the newly created queue. */ public CompletableFuture<QueueDescription> createQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, false); } /** * Updates an existing queue. * @param queueDescription - A {@link QueueDescription} object describing the attributes with which the queue will be updated. * @return {@link QueueDescription} of the updated queue. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<QueueDescription> updateQueueAsync(QueueDescription queueDescription) { return putQueueAsync(queueDescription, true); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @return {@link TopicDescription} of the newly created topic. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<TopicDescription> createTopicAsync(String topicPath) { return this.createTopicAsync(new TopicDescription(topicPath)); } /** * Creates a new topic in the service namespace with the given name. * See {@link TopicDescription} for default values of topic properties. * @param topicDescription - A {@link QueueDescription} object describing the attributes with which the new topic will be created. * @return {@link TopicDescription} of the newly created topic. */ public CompletableFuture<TopicDescription> createTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, false); } /** * Updates an existing topic. * @param topicDescription - A {@link TopicDescription} object describing the attributes with which the topic will be updated. * @return {@link TopicDescription} of the updated topic. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<TopicDescription> updateTopicAsync(TopicDescription topicDescription) { return putTopicAsync(topicDescription, true); } private CompletableFuture<TopicDescription> putTopicAsync(TopicDescription topicDescription, boolean isUpdate) { if (topicDescription == null) { throw new IllegalArgumentException("topicDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = TopicDescriptionSerializer.serialize(topicDescription); } catch (ServiceBusException e) { final CompletableFuture<TopicDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<TopicDescription> responseFuture = new CompletableFuture<>(); putEntityAsync(topicDescription.path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(TopicDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new subscription for a given topic in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param topicPath - The name of the topic relative to the service namespace base address. * @param subscriptionName - The name of the subscription. * @return {@link SubscriptionDescription} of the newly created subscription. * @throws IllegalArgumentException - Entity name is null, empty, too long or uses illegal characters. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(String topicPath, String subscriptionName) { return this.createSubscriptionAsync(new SubscriptionDescription(topicPath, subscriptionName)); } /** * Creates a new subscription in the service namespace with the given name. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return this.createSubscriptionAsync(subscriptionDescription, null); } /** * Creates a new subscription in the service namespace with the provided default rule. * See {@link SubscriptionDescription} for default values of subscription properties. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the new subscription will be created. * @param defaultRule - A {@link RuleDescription} object describing the default rule. If null, then pass-through filter will be created. * @return {@link SubscriptionDescription} of the newly created subscription. */ public CompletableFuture<SubscriptionDescription> createSubscriptionAsync(SubscriptionDescription subscriptionDescription, RuleDescription defaultRule) { subscriptionDescription.defaultRule = defaultRule; return putSubscriptionAsync(subscriptionDescription, false); } /** * Updates an existing subscription. * @param subscriptionDescription - A {@link SubscriptionDescription} object describing the attributes with which the subscription will be updated. * @return {@link SubscriptionDescription} of the updated subscription. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<SubscriptionDescription> updateSubscriptionAsync(SubscriptionDescription subscriptionDescription) { return putSubscriptionAsync(subscriptionDescription, true); } private CompletableFuture<SubscriptionDescription> putSubscriptionAsync(SubscriptionDescription subscriptionDescription, boolean isUpdate) { if (subscriptionDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } SubscriptionDescriptionSerializer.normalizeDescription(subscriptionDescription, this.namespaceEndpointURI); String atomRequest = null; try { atomRequest = SubscriptionDescriptionSerializer.serialize(subscriptionDescription); } catch (ServiceBusException e) { final CompletableFuture<SubscriptionDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<SubscriptionDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatSubscriptionPath(subscriptionDescription.getTopicPath(), subscriptionDescription.getSubscriptionName()); putEntityAsync(path, atomRequest, isUpdate, subscriptionDescription.getForwardTo(), subscriptionDescription.getForwardDeadLetteredMessagesTo()) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(SubscriptionDescriptionSerializer.parseFromContent(subscriptionDescription.getTopicPath(), content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } /** * Creates a new rule for a given topic - subscription. * See {@link RuleDescription} for default values of subscription properties. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the new rule will be created. * @return {@link RuleDescription} of the newly created rule. */ public CompletableFuture<RuleDescription> createRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, false); } /** * Updates an existing rule. * @param topicName - Name of the topic. * @param subscriptionName - Name of the subscription. * @param ruleDescription - A {@link RuleDescription} object describing the attributes with which the rule will be updated. * @return {@link RuleDescription} of the updated rule. * @throws IllegalArgumentException - descriptor is null. */ public CompletableFuture<RuleDescription> updateRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription) { return putRuleAsync(topicName, subscriptionName, ruleDescription, true); } private CompletableFuture<RuleDescription> putRuleAsync(String topicName, String subscriptionName, RuleDescription ruleDescription, boolean isUpdate) { EntityNameHelper.checkValidTopicName(topicName); EntityNameHelper.checkValidSubscriptionName(subscriptionName); if (ruleDescription == null) { throw new IllegalArgumentException("queueDescription passed cannot be null"); } String atomRequest = null; try { atomRequest = RuleDescriptionSerializer.serialize(ruleDescription); } catch (ServiceBusException e) { final CompletableFuture<RuleDescription> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } CompletableFuture<RuleDescription> responseFuture = new CompletableFuture<>(); String path = EntityNameHelper.formatRulePath(topicName, subscriptionName, ruleDescription.getName()); putEntityAsync(path, atomRequest, isUpdate, null, null) .handleAsync((content, ex) -> { if (ex != null) { responseFuture.completeExceptionally(ex); } else { try { responseFuture.complete(RuleDescriptionSerializer.parseFromContent(content)); } catch (MessagingEntityNotFoundException e) { responseFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return responseFuture; } private CompletableFuture<String> putEntityAsync(String path, String requestBody, boolean isUpdate, String forwardTo, String fwdDeadLetterTo) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } HashMap<String, String> additionalHeaders = new HashMap<>(); if (isUpdate) { additionalHeaders.put("If-Match", "*"); } if (forwardTo != null && !forwardTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), forwardTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } if (fwdDeadLetterTo != null && !fwdDeadLetterTo.isEmpty()) { try { String securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), fwdDeadLetterTo); additionalHeaders.put(ManagementClientConstants.SERVICEBUS_DLQ_SUPPLEMENTARTY_AUTHORIZATION_HEADER_NAME, securityToken); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } } return sendManagementHttpRequestAsync(HttpConstants.Methods.PUT, entityURL, requestBody, additionalHeaders); } /** * Checks whether a given queue exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> queueExistsAsync(String path) { EntityNameHelper.checkValidQueueName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getQueueAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given topic exists or not. * @param path - Path of the entity to check * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> topicExistsAsync(String path) { EntityNameHelper.checkValidTopicName(path); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getTopicAsync(path).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given subscription exists or not. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> subscriptionExistsAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getSubscriptionAsync(topicPath, subscriptionName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Checks whether a given rule exists or not for a given subscription. * @param topicPath - Path of the topic * @param subscriptionName - Name of the subscription. * @param ruleName - Name of the rule * @return - True if the entity exists. False otherwise. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Boolean> ruleExistsAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); CompletableFuture<Boolean> existsFuture = new CompletableFuture<>(); this.getRuleAsync(topicPath, subscriptionName, ruleName).handleAsync((qd, ex) -> { if (ex != null) { if (ex instanceof MessagingEntityNotFoundException) { existsFuture.complete(Boolean.FALSE); return false; } existsFuture.completeExceptionally(ex); return false; } existsFuture.complete(Boolean.TRUE); return true; }, MessagingFactory.INTERNAL_THREAD_POOL); return existsFuture; } /** * Deletes the queue described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the queue is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteQueueAsync(String path) { EntityNameHelper.checkValidQueueName(path); return deleteEntityAsync(path); } /** * Deletes the topic described by the path relative to the service namespace base address. * @param path - The name of the entity relative to the service namespace base address. * @return A completable future that completes when the topic is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteTopicAsync(String path) { EntityNameHelper.checkValidTopicName(path); return deleteEntityAsync(path); } /** * Deletes the subscription described by the topicPath and the subscriptionName. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @return A completable future that completes when the subscription is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteSubscriptionAsync(String topicPath, String subscriptionName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); String path = EntityNameHelper.formatSubscriptionPath(topicPath, subscriptionName); return deleteEntityAsync(path); } /** * Deletes the rule for a given topic-subscription. * @param topicPath - The name of the topic. * @param subscriptionName - The name of the subscription. * @param ruleName - The name of the rule. * @return A completable future that completes when the rule is deleted. * @throws IllegalArgumentException - path is not null / empty / too long / invalid. */ public CompletableFuture<Void> deleteRuleAsync(String topicPath, String subscriptionName, String ruleName) { EntityNameHelper.checkValidTopicName(topicPath); EntityNameHelper.checkValidSubscriptionName(subscriptionName); EntityNameHelper.checkValidRuleName(ruleName); String path = EntityNameHelper.formatRulePath(topicPath, subscriptionName, ruleName); return deleteEntityAsync(path); } private CompletableFuture<Void> deleteEntityAsync(String path) { URL entityURL = null; try { entityURL = getManagementURL(this.namespaceEndpointURI, path, API_VERSION_QUERY); } catch (ServiceBusException e) { final CompletableFuture<Void> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } return sendManagementHttpRequestAsync(HttpConstants.Methods.DELETE, entityURL, null, null).thenAccept(c -> { }); } /** * Disposes and closes the managementClient. * @throws IOException if an I/O error occurs */ public void close() throws IOException { this.asyncHttpClient.close(); } private static URL getManagementURL(URI namespaceEndpontURI, String entityPath, String query) throws ServiceBusException { try { URI httpURI = new URI("https", null, namespaceEndpontURI.getHost(), getPortNumberFromHost(namespaceEndpontURI.getHost()), "/" + entityPath, query, null); return httpURI.toURL(); } catch (URISyntaxException | MalformedURLException e) { throw new ServiceBusException(false, e); } } private CompletableFuture<String> sendManagementHttpRequestAsync(String httpMethod, URL url, String atomEntryString, HashMap<String, String> additionalHeaders) { String securityToken = null; try { securityToken = getSecurityToken(this.clientSettings.getTokenProvider(), url.toString()); } catch (InterruptedException | ExecutionException e) { final CompletableFuture<String> exceptionFuture = new CompletableFuture<>(); exceptionFuture.completeExceptionally(e); return exceptionFuture; } RequestBuilder requestBuilder = new RequestBuilder(httpMethod) .setUrl(url.toString()) .setBody(atomEntryString) .addHeader(USER_AGENT_HEADER_NAME, USER_AGENT) .addHeader(AUTHORIZATION_HEADER_NAME, securityToken) .addHeader(CONTENT_TYPE_HEADER_NAME, CONTENT_TYPE); if (additionalHeaders != null) { for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) { requestBuilder.addHeader(entry.getKey(), entry.getValue()); } } Request unboundRequest = requestBuilder.build(); ListenableFuture<Response> listenableFuture = this.asyncHttpClient .executeRequest(unboundRequest); CompletableFuture<String> outputFuture = new CompletableFuture<>(); listenableFuture.toCompletableFuture() .handleAsync((response, ex) -> { if (ex != null) { outputFuture.completeExceptionally(ex); } else { try { validateHttpResponse(unboundRequest, response); outputFuture.complete(response.getResponseBody()); } catch (ServiceBusException e) { outputFuture.completeExceptionally(e); } } return null; }, MessagingFactory.INTERNAL_THREAD_POOL); return outputFuture; } private static void validateHttpResponse(Request request, Response response) throws ServiceBusException, UnsupportedOperationException { if (response.hasResponseStatus() && response.getStatusCode() >= 200 && response.getStatusCode() < 300) { return; } String exceptionMessage = response.getResponseBody(); exceptionMessage = parseDetailIfAvailable(exceptionMessage); if (exceptionMessage == null) { exceptionMessage = response.getStatusText(); } ServiceBusException exception = null; switch (response.getStatusCode()) { case 401: /*UnAuthorized*/ exception = new AuthorizationFailedException(exceptionMessage); break; case 404: /*NotFound*/ case 204: /*NoContent*/ exception = new MessagingEntityNotFoundException(exceptionMessage); break; case 409: /*Conflict*/ if (HttpConstants.Methods.DELETE.equals(request.getMethod())) { exception = new ServiceBusException(true, exceptionMessage); break; } if (HttpConstants.Methods.PUT.equals(request.getMethod()) && request.getHeaders().contains("IfMatch")) { /*Update request*/ exception = new ServiceBusException(true, exceptionMessage); break; } if (exceptionMessage.contains(ManagementClientConstants.CONFLICT_OPERATION_IN_PROGRESS_SUB_CODE)) { exception = new ServiceBusException(true, exceptionMessage); break; } exception = new MessagingEntityAlreadyExistsException(exceptionMessage); break; case 403: /*Forbidden*/ if (exceptionMessage.contains(ManagementClientConstants.FORBIDDEN_INVALID_OPERATION_SUB_CODE)) { throw new UnsupportedOperationException(exceptionMessage); } else { exception = new QuotaExceededException(exceptionMessage); } break; case 400: /*BadRequest*/ exception = new ServiceBusException(false, new IllegalArgumentException(exceptionMessage)); break; case 503: /*ServiceUnavailable*/ exception = new ServerBusyException(exceptionMessage); break; default: exception = new ServiceBusException(true, exceptionMessage + "; Status code: " + response.getStatusCode()); } throw exception; } private static String parseDetailIfAvailable(String content) { if (content == null || content.isEmpty()) { return null; } DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(new ByteArrayInputStream(content.getBytes("utf-8"))); Element doc = dom.getDocumentElement(); doc.normalize(); NodeList entries = doc.getChildNodes(); for (int i = 0; i < entries.getLength(); i++) { Node node = entries.item(i); if (node.getNodeName().equals("Detail")) { return node.getFirstChild().getTextContent(); } } } catch (ParserConfigurationException | IOException | SAXException e) { if (TRACE_LOGGER.isErrorEnabled()) { TRACE_LOGGER.info("Exception while parsing response.", e); } if (TRACE_LOGGER.isDebugEnabled()) { TRACE_LOGGER.debug("XML which failed to parse: \n %s", content); } } return null; } private static String getSecurityToken(TokenProvider tokenProvider, String url) throws InterruptedException, ExecutionException { SecurityToken token = tokenProvider.getSecurityTokenAsync(url).get(); return token.getTokenValue(); } private static int getPortNumberFromHost(String host) { if (host.endsWith("onebox.windows-int.net")) { return ONE_BOX_HTTPS_PORT; } else { return -1; } } }
Should this use the provided `charset`?
private HttpResponse initResponse(HttpRequest request, int statusCode, HttpHeaders headers, String body) { return new HttpResponse(request) { @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.just(ByteBuffer.wrap(body.getBytes(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.just(body.getBytes(StandardCharsets.UTF_8)); } @Override public Mono<String> getBodyAsString() { return Mono.just(body); } @Override public Mono<String> getBodyAsString(Charset charset) { return Mono.just(body); } }; }
return Mono.just(body);
private HttpResponse initResponse(HttpRequest request, int statusCode, HttpHeaders headers, String body) { return new HttpResponse(request) { @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.just(ByteBuffer.wrap(body.getBytes(StandardCharsets.UTF_8))); } @Override public Mono<byte[]> getBodyAsByteArray() { return Mono.just(body.getBytes(StandardCharsets.UTF_8)); } @Override public Mono<String> getBodyAsString() { return Mono.just(body); } @Override public Mono<String> getBodyAsString(Charset charset) { return getBodyAsByteArray().map(body -> new String(body, charset)); } }; }
class BlobBatchOperationResponse<T> implements Response<T> { private final ClientLogger logger = new ClientLogger(BlobBatchOperationResponse.class); private final Set<Integer> expectedStatusCodes; private int statusCode; private HttpHeaders headers; private HttpRequest request; private T value; private StorageException exception; private boolean responseReceived = false; BlobBatchOperationResponse(int... expectedStatusCodes) { this.expectedStatusCodes = new HashSet<>(); for (int expectedStatusCode : expectedStatusCodes) { this.expectedStatusCodes.add(expectedStatusCode); } } @Override public int getStatusCode() { assertResponseReceived(); return statusCode; } BlobBatchOperationResponse<T> setStatusCode(int statusCode) { this.statusCode = statusCode; return this; } @Override public HttpHeaders getHeaders() { assertResponseReceived(); return headers; } BlobBatchOperationResponse<T> setHeaders(HttpHeaders headers) { this.headers = headers; return this; } @Override public HttpRequest getRequest() { assertResponseReceived(); return request; } BlobBatchOperationResponse<T> setRequest(HttpRequest request) { this.request = request; return this; } @Override public T getValue() { assertResponseReceived(); return value; } BlobBatchOperationResponse<T> setValue(T value) { this.value = value; return this; } BlobBatchOperationResponse<T> setResponseReceived() { this.responseReceived = true; return this; } BlobBatchOperationResponse<T> setException(StorageException exception) { this.exception = exception; return this; } boolean wasExpectedResponse() { return expectedStatusCodes.contains(statusCode); } HttpResponse asHttpResponse(String body) { return initResponse(request, statusCode, headers, body); } private void assertResponseReceived() { if (!responseReceived) { throw logger.logExceptionAsWarning(new UnsupportedOperationException("Batch request has not been sent.")); } if (!expectedStatusCodes.contains(statusCode)) { throw logger.logExceptionAsError(exception); } } }
class BlobBatchOperationResponse<T> implements Response<T> { private final ClientLogger logger = new ClientLogger(BlobBatchOperationResponse.class); private final Set<Integer> expectedStatusCodes; private int statusCode; private HttpHeaders headers; private HttpRequest request; private T value; private StorageException exception; private boolean responseReceived = false; BlobBatchOperationResponse(int... expectedStatusCodes) { this.expectedStatusCodes = new HashSet<>(); for (int expectedStatusCode : expectedStatusCodes) { this.expectedStatusCodes.add(expectedStatusCode); } } @Override public int getStatusCode() { assertResponseReceived(); return statusCode; } BlobBatchOperationResponse<T> setStatusCode(int statusCode) { this.statusCode = statusCode; return this; } @Override public HttpHeaders getHeaders() { assertResponseReceived(); return headers; } BlobBatchOperationResponse<T> setHeaders(HttpHeaders headers) { this.headers = headers; return this; } @Override public HttpRequest getRequest() { assertResponseReceived(); return request; } BlobBatchOperationResponse<T> setRequest(HttpRequest request) { this.request = request; return this; } @Override public T getValue() { assertResponseReceived(); return value; } BlobBatchOperationResponse<T> setValue(T value) { this.value = value; return this; } BlobBatchOperationResponse<T> setResponseReceived() { this.responseReceived = true; return this; } BlobBatchOperationResponse<T> setException(StorageException exception) { this.exception = exception; return this; } boolean wasExpectedResponse() { return expectedStatusCodes.contains(statusCode); } HttpResponse asHttpResponse(String body) { return initResponse(request, statusCode, headers, body); } private void assertResponseReceived() { if (!responseReceived) { throw logger.logExceptionAsWarning(new UnsupportedOperationException("Batch request has not been sent.")); } if (!expectedStatusCodes.contains(statusCode)) { throw logger.logExceptionAsError(exception); } } }
Think I left a comment on the other PR, but this I think can just be .blockLast or equivalent
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer .wrap(String.format("--%s--NEWLINE", batchBoundary).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
}
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
class BlobBatch { private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String CONTENT_TYPE = "Content-Type: application/http"; private static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; private static final String NEWLINE = "\r\n"; private static final int[] EXPECTED_DELETE_STATUS_CODES = { 202 }; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = { 200, 202 }; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient batchClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private BlobBatchType batchType; /** * Constructs a {@link BlobBatch} using the {@link BlobServiceClient * BlobServiceClient's HttpPipeline} to build a modified {@link HttpPipeline} that is used to prepare the requests * in the batch. * * @param client {@link BlobServiceClient} used to construct the batch. */ public BlobBatch(BlobServiceClient client) { this(client.getAccountUrl(), client.getHttpPipeline()); } /** * Constructs a {@link BlobBatch} using the {@link BlobServiceAsyncClient * BlobServiceAsyncClient's HttpPipeline} to build a modified {@link HttpPipeline} that is used to prepare the * requests in the batch. * * @param client {@link BlobServiceAsyncClient} used to construct the batch. */ public BlobBatch(BlobServiceAsyncClient client) { this(client.getAccountUrl(), client.getHttpPipeline()); } BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders); } this.batchClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(pipeline) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String containerName, String blobName) { return deleteHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String blobUrl) { return deleteHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(batchClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String containerName, String blobName, AccessTier accessTier) { return setTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String blobUrl, AccessTier accessTier) { return setTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(batchClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return String.format("multipart/mixed; boundary=%s", batchBoundary); } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * Enum class that indicates which type of operation this batch is using. */ private enum BlobBatchType { DELETE, SET_TIER } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(Constants.HeaderConstants.VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw Exceptions.propagate(logger.logExceptionAsError(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, CONTENT_TYPE); appendWithNewline(batchRequestBuilder, CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !Constants.HeaderConstants.VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(NEWLINE); } }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); } /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
It could but I went with this approach as it is safer for use inside Reactor threads, they will throw an exception by default if a blocking call is made in them.
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer .wrap(String.format("--%s--NEWLINE", batchBoundary).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
}
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
class BlobBatch { private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String CONTENT_TYPE = "Content-Type: application/http"; private static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; private static final String NEWLINE = "\r\n"; private static final int[] EXPECTED_DELETE_STATUS_CODES = { 202 }; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = { 200, 202 }; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient batchClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private BlobBatchType batchType; /** * Constructs a {@link BlobBatch} using the {@link BlobServiceClient * BlobServiceClient's HttpPipeline} to build a modified {@link HttpPipeline} that is used to prepare the requests * in the batch. * * @param client {@link BlobServiceClient} used to construct the batch. */ public BlobBatch(BlobServiceClient client) { this(client.getAccountUrl(), client.getHttpPipeline()); } /** * Constructs a {@link BlobBatch} using the {@link BlobServiceAsyncClient * BlobServiceAsyncClient's HttpPipeline} to build a modified {@link HttpPipeline} that is used to prepare the * requests in the batch. * * @param client {@link BlobServiceAsyncClient} used to construct the batch. */ public BlobBatch(BlobServiceAsyncClient client) { this(client.getAccountUrl(), client.getHttpPipeline()); } BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders); } this.batchClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(pipeline) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String containerName, String blobName) { return deleteHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String blobUrl) { return deleteHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(batchClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String containerName, String blobName, AccessTier accessTier) { return setTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String blobUrl, AccessTier accessTier) { return setTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(batchClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return String.format("multipart/mixed; boundary=%s", batchBoundary); } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * Enum class that indicates which type of operation this batch is using. */ private enum BlobBatchType { DELETE, SET_TIER } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(Constants.HeaderConstants.VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw Exceptions.propagate(logger.logExceptionAsError(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, CONTENT_TYPE); appendWithNewline(batchRequestBuilder, CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !Constants.HeaderConstants.VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(NEWLINE); } }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); } /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
This doesn't belong in a cleanseHeaders method. Can you either rename or refactor?
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(Constants.HeaderConstants.VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw Exceptions.propagate(logger.logExceptionAsError(new IllegalStateException(ex))); } return next.process(); }
}
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); }
class that indicates which type of operation this batch is using. */ private enum BlobBatchType { DELETE, SET_TIER }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
Made a new private method name `setRequestUrl`
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(Constants.HeaderConstants.VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw Exceptions.propagate(logger.logExceptionAsError(new IllegalStateException(ex))); } return next.process(); }
}
private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); }
class that indicates which type of operation this batch is using. */ private enum BlobBatchType { DELETE, SET_TIER }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
XD you sneaky mom! --- In reply to: [333121225](https://github.com/Azure/azure-sdk-for-java/pull/5734#discussion_r333121225) [](ancestors = 333121225)
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer .wrap(String.format("--%s--NEWLINE", batchBoundary).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
}
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
class BlobBatch { private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String CONTENT_TYPE = "Content-Type: application/http"; private static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; private static final String NEWLINE = "\r\n"; private static final int[] EXPECTED_DELETE_STATUS_CODES = { 202 }; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = { 200, 202 }; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient batchClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private BlobBatchType batchType; /** * Constructs a {@link BlobBatch} using the {@link BlobServiceClient * BlobServiceClient's HttpPipeline} to build a modified {@link HttpPipeline} that is used to prepare the requests * in the batch. * * @param client {@link BlobServiceClient} used to construct the batch. */ public BlobBatch(BlobServiceClient client) { this(client.getAccountUrl(), client.getHttpPipeline()); } /** * Constructs a {@link BlobBatch} using the {@link BlobServiceAsyncClient * BlobServiceAsyncClient's HttpPipeline} to build a modified {@link HttpPipeline} that is used to prepare the * requests in the batch. * * @param client {@link BlobServiceAsyncClient} used to construct the batch. */ public BlobBatch(BlobServiceAsyncClient client) { this(client.getAccountUrl(), client.getHttpPipeline()); } BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders); } this.batchClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(pipeline) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String containerName, String blobName) { return deleteHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String blobUrl) { return deleteHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.delete * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> delete(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(batchClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String containerName, String blobName, AccessTier accessTier) { return setTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String blobUrl, AccessTier accessTier) { return setTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.BlobBatch.setTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(batchClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return String.format("multipart/mixed; boundary=%s", batchBoundary); } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * Enum class that indicates which type of operation this batch is using. */ private enum BlobBatchType { DELETE, SET_TIER } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(Constants.HeaderConstants.VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw Exceptions.propagate(logger.logExceptionAsError(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, CONTENT_TYPE); appendWithNewline(batchRequestBuilder, CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !Constants.HeaderConstants.VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(NEWLINE); } }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); } /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
This feels weird, runs in a tight loop, and could consume unnecessary CPU cycles. What about: ```java return Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .then(Mono.fromRunnable(() -> { batchRequest.add(ByteBuffer.wrap(String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); })) .thenMany(Flux.fromIterable(batchRequest)); ```
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
while (!disposable.isDisposed()) {
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); } /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); } /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
I've tried using this and it doesn't work for some reason. Given this is implementation detail and there is more work for batching next preview I'll write up an issue.
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
while (!disposable.isDisposed()) {
Flux<ByteBuffer> getBody() { if (batchOperationQueue.isEmpty()) { throw logger.logExceptionAsError(new UnsupportedOperationException("Empty batch requests aren't allowed.")); } Disposable disposable = Flux.fromStream(batchOperationQueue.stream()) .flatMap(batchOperation -> batchOperation) .subscribe(); /* Wait until the 'Flux' is disposed of (aka complete) instead of blocking as this will prevent Reactor from * throwing an exception if this was ran in a Reactor thread. */ while (!disposable.isDisposed()) { } this.batchRequest.add(ByteBuffer.wrap( String.format("--%s--%s", batchBoundary, BlobBatchHelper.HTTP_NEWLINE).getBytes(StandardCharsets.UTF_8))); return Flux.fromIterable(batchRequest); }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); } /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
class BlobBatch { private static final String X_MS_VERSION = "x-ms-version"; private static final String BATCH_REQUEST_CONTENT_ID = "Batch-Request-Content-Id"; private static final String BATCH_REQUEST_URL_PATH = "Batch-Request-Url-Path"; private static final String CONTENT_ID = "Content-Id"; private static final String BATCH_BOUNDARY_TEMPLATE = "batch_%s"; private static final String REQUEST_CONTENT_TYPE_TEMPLATE = "multipart/mixed; boundary=%s"; private static final String BATCH_OPERATION_CONTENT_TYPE = "Content-Type: application/http"; private static final String BATCH_OPERATION_CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary"; private static final String BATCH_OPERATION_CONTENT_ID_TEMPLATE = "Content-ID: %d"; private static final String HTTP_VERSION = "HTTP/1.1"; private static final String OPERATION_TEMPLATE = "%s %s %s"; private static final String HEADER_TEMPLATE = "%s: %s"; /* * Track the status codes expected for the batching operations here as the batch body does not get parsed in * Azure Core where this information is maintained. */ private static final int[] EXPECTED_DELETE_STATUS_CODES = {202}; private static final int[] EXPECTED_SET_TIER_STATUS_CODES = {200, 202}; private final ClientLogger logger = new ClientLogger(BlobBatch.class); private final BlobAsyncClient blobAsyncClient; private final Deque<Mono<? extends Response<?>>> batchOperationQueue; private final List<ByteBuffer> batchRequest; private final Map<Integer, BlobBatchOperationResponse<?>> batchMapping; private final AtomicInteger contentId; private final String batchBoundary; private final String contentType; private BlobBatchType batchType; BlobBatch(String accountUrl, HttpPipeline pipeline) { this.contentId = new AtomicInteger(0); this.batchBoundary = String.format(BATCH_BOUNDARY_TEMPLATE, UUID.randomUUID()); this.contentType = String.format(REQUEST_CONTENT_TYPE_TEMPLATE, batchBoundary); boolean batchHeadersPolicySet = false; HttpPipelineBuilder batchPipelineBuilder = new HttpPipelineBuilder().httpClient(this::setupBatchOperation); for (int i = 0; i < pipeline.getPolicyCount(); i++) { HttpPipelinePolicy policy = pipeline.getPolicy(i); if (policy instanceof SharedKeyCredentialPolicy) { batchHeadersPolicySet = true; batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } batchPipelineBuilder.policies(pipeline.getPolicy(i)); } if (!batchHeadersPolicySet) { batchPipelineBuilder.policies(this::cleanseHeaders, this::setRequestUrl); } this.blobAsyncClient = new BlobClientBuilder() .endpoint(accountUrl) .blobName("") .pipeline(batchPipelineBuilder.build()) .buildAsyncClient(); this.batchOperationQueue = new ConcurrentLinkedDeque<>(); this.batchRequest = new ArrayList<>(); this.batchMapping = new ConcurrentHashMap<>(); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String containerName, String blobName, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(String.format("%s/%s", containerName, blobName), deleteOptions, blobAccessConditions); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl) { return deleteBlobHelper(getUrlPath(blobUrl), null, null); } /** * Adds a delete blob operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.deleteBlob * * @param blobUrl URI of the blob. * @param deleteOptions Delete options for the blob and its snapshots. * @param blobAccessConditions Additional access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> deleteBlob(String blobUrl, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { return deleteBlobHelper(getUrlPath(blobUrl), deleteOptions, blobAccessConditions); } private Response<Void> deleteBlobHelper(String urlPath, DeleteSnapshotsOptionType deleteOptions, BlobAccessConditions blobAccessConditions) { setBatchType(BlobBatchType.DELETE); return createBatchOperation(blobAsyncClient.deleteWithResponse(deleteOptions, blobAccessConditions), urlPath, EXPECTED_DELETE_STATUS_CODES); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param containerName The container of the blob. * @param blobName The name of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String containerName, String blobName, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(String.format("%s/%s", containerName, blobName), accessTier, leaseAccessConditions); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, null); } /** * Adds a set tier operation to the batch. * * <p><strong>Code sample</strong></p> * * {@codesnippet com.azure.storage.blob.batch.BlobBatch.setBlobAccessTier * * @param blobUrl URI of the blob. * @param accessTier The tier to set on the blob. * @param leaseAccessConditions Lease access conditions that must be met to allow this operation. * @return a {@link Response} that will be used to associate this operation to the response when the batch is * submitted. * @throws UnsupportedOperationException If this batch has already added an operation of another type. */ public Response<Void> setBlobAccessTier(String blobUrl, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { return setBlobAccessTierHelper(getUrlPath(blobUrl), accessTier, leaseAccessConditions); } private Response<Void> setBlobAccessTierHelper(String urlPath, AccessTier accessTier, LeaseAccessConditions leaseAccessConditions) { setBatchType(BlobBatchType.SET_TIER); return createBatchOperation(blobAsyncClient.setAccessTierWithResponse(accessTier, null, leaseAccessConditions), urlPath, EXPECTED_SET_TIER_STATUS_CODES); } private <T> Response<T> createBatchOperation(Mono<Response<T>> response, String urlPath, int... expectedStatusCodes) { int id = contentId.getAndIncrement(); batchOperationQueue.add(response .subscriberContext(Context.of(BATCH_REQUEST_CONTENT_ID, id, BATCH_REQUEST_URL_PATH, urlPath))); BlobBatchOperationResponse<T> batchOperationResponse = new BlobBatchOperationResponse<>(expectedStatusCodes); batchMapping.put(id, batchOperationResponse); return batchOperationResponse; } private String getUrlPath(String url) { return UrlBuilder.parse(url).getPath(); } private void setBatchType(BlobBatchType batchType) { if (this.batchType == null) { this.batchType = batchType; } else if (this.batchType != batchType) { throw logger.logExceptionAsError(new UnsupportedOperationException(String.format(Locale.ROOT, "'BlobBatch' only supports homogeneous operations and is a %s batch.", this.batchType))); } } long getContentLength() { long contentLength = 0; for (ByteBuffer request : batchRequest) { contentLength += request.remaining(); } return contentLength; } String getContentType() { return contentType; } BlobBatchOperationResponse<?> getBatchRequest(int contentId) { return batchMapping.get(contentId); } /* * This performs a cleanup operation that would be handled when the request is sent through Netty or OkHttp. * Additionally, it removes the "x-ms-version" header from the request as batch operation requests cannot have this * and it adds the header "Content-Id" that allows the request to be mapped to the response. */ private Mono<HttpResponse> cleanseHeaders(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { context.getHttpRequest().getHeaders().remove(X_MS_VERSION); Map<String, String> headers = context.getHttpRequest().getHeaders().toMap(); headers.entrySet().removeIf(header -> header.getValue() == null); context.getHttpRequest().setHeaders(new HttpHeaders(headers)); context.getHttpRequest().setHeader(CONTENT_ID, context.getData(BATCH_REQUEST_CONTENT_ID).get().toString()); return next.process(); } /* * This performs changing the request URL to the value passed through the pipeline context. This policy is used in * place of constructing a new client for each batch request that is being sent. */ private Mono<HttpResponse> setRequestUrl(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { try { UrlBuilder requestUrl = UrlBuilder.parse(context.getHttpRequest().getUrl()); requestUrl.setPath(context.getData(BATCH_REQUEST_URL_PATH).get().toString()); context.getHttpRequest().setUrl(requestUrl.toURL()); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(Exceptions.propagate(new IllegalStateException(ex))); } return next.process(); } /* * This will "send" the batch operation request when triggered, it simply acts as a way to build and write the * batch operation into the overall request and then returns nothing as the response. */ private Mono<HttpResponse> setupBatchOperation(HttpRequest request) { int contentId = Integer.parseInt(request.getHeaders().remove(CONTENT_ID).getValue()); StringBuilder batchRequestBuilder = new StringBuilder(); appendWithNewline(batchRequestBuilder, "--" + batchBoundary); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TYPE); appendWithNewline(batchRequestBuilder, BATCH_OPERATION_CONTENT_TRANSFER_ENCODING); appendWithNewline(batchRequestBuilder, String.format(BATCH_OPERATION_CONTENT_ID_TEMPLATE, contentId)); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); String method = request.getHttpMethod().toString(); String urlPath = request.getUrl().getPath(); String urlQuery = request.getUrl().getQuery(); if (!ImplUtils.isNullOrEmpty(urlQuery)) { urlPath = urlPath + "?" + urlQuery; } appendWithNewline(batchRequestBuilder, String.format(OPERATION_TEMPLATE, method, urlPath, HTTP_VERSION)); request.getHeaders().stream() .filter(header -> !X_MS_VERSION.equalsIgnoreCase(header.getName())) .forEach(header -> appendWithNewline(batchRequestBuilder, String.format(HEADER_TEMPLATE, header.getName(), header.getValue()))); batchRequestBuilder.append(BlobBatchHelper.HTTP_NEWLINE); batchRequest.add(ByteBuffer.wrap(batchRequestBuilder.toString().getBytes(StandardCharsets.UTF_8))); batchMapping.get(contentId).setRequest(request); return Mono.empty(); } private void appendWithNewline(StringBuilder stringBuilder, String value) { stringBuilder.append(value).append(BlobBatchHelper.HTTP_NEWLINE); } }
just curious, why check for null kind?
public void startSpanParentContextFlowTest() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); }
Assert.assertNull(recordEventsSpan.getKind());
public void startSpanParentContextFlowTest() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); }
class OpenCensusTracerTest { private static final String METHOD_NAME = "Azure.eventhubs.send"; private static final String HOSTNAME_VALUE = "testEventDataNameSpace.servicebus.windows.net"; private static final String ENTITY_PATH_VALUE = "test"; private static final String COMPONENT_VALUE = "eventhubs"; private OpenCensusTracer openCensusTracer; private Tracer tracer; private Context tracingContext; private Span parentSpan; private io.opencensus.common.Scope scope; @Before public void setUp() { System.out.println("Running: setUp"); openCensusTracer = new OpenCensusTracer(); final TraceConfig traceConfig = Tracing.getTraceConfig(); final TraceParams activeTraceParams = traceConfig.getActiveTraceParams(); traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build()); tracer = Tracing.getTracer(); scope = tracer.spanBuilder(PARENT_SPAN_KEY).startScopedSpan(); parentSpan = tracer.getCurrentSpan(); tracingContext = new Context(PARENT_SPAN_KEY, parentSpan); } @After public void tearDown() { System.out.println("Running: tearDown"); tracer = null; tracingContext = null; Assert.assertNull(tracer); Assert.assertNull(tracingContext); scope.close(); } @Test(expected = NullPointerException.class) public void startSpanNullPointerException() { openCensusTracer.start("", null); } @Test @Test public void startSpanTestNoUserParent() { final Context updatedContext = openCensusTracer.start(METHOD_NAME, Context.NONE); Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertNotNull(recordEventsSpan.toSpanData().getParentSpanId()); } @Test public void startSpanProcessKindSend() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(ENTITY_PATH_KEY, ENTITY_PATH_VALUE) .addData(HOST_NAME_KEY, HOSTNAME_VALUE); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.SEND); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.CLIENT, recordEventsSpan.getKind()); final Map<String, AttributeValue> attributeMap = recordEventsSpan.toSpanData().getAttributes() .getAttributeMap(); Assert.assertEquals(attributeMap.get(COMPONENT), AttributeValue.stringAttributeValue(COMPONENT_VALUE)); Assert.assertEquals(attributeMap.get(MESSAGE_BUS_DESTINATION), AttributeValue.stringAttributeValue(ENTITY_PATH_VALUE)); Assert.assertEquals(attributeMap.get(PEER_ENDPOINT), AttributeValue.stringAttributeValue(HOSTNAME_VALUE)); } @Test public void startSpanProcessKindReceive() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.RECEIVE); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); Assert.assertNotNull(updatedContext.getData(SPAN_CONTEXT_KEY).get()); Assert.assertNotNull(updatedContext.getData(DIAGNOSTIC_ID_KEY).get()); } @Test public void startSpanProcessKindProcess() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.PROCESS); Assert.assertFalse("When no parent span passed in context information", tracingContext.getData(SPAN_CONTEXT_KEY).isPresent()); assertSpanWithExplicitParent(updatedContext, parentSpanId); Assert.assertNotNull(updatedContext.getData("scope").get()); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); } @Test public void startProcessSpanWithRemoteParent() { final Span testSpan = tracer.spanBuilder("child-span").startSpan(); final SpanId testSpanId = testSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.PROCESS); Assert.assertNotNull(updatedContext.getData("scope").get()); assertSpanWithRemoteParent(updatedContext, testSpanId); } @Test(expected = NullPointerException.class) public void startSpanOverloadNullPointerException() { openCensusTracer.start("", Context.NONE, null); } @Test public void addLinkTest() { final RecordEventsSpanImpl testSpan = (RecordEventsSpanImpl) tracer.spanBuilder("new-test-span").startSpan(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final RecordEventsSpanImpl parentSpanImpl = (RecordEventsSpanImpl) parentSpan; openCensusTracer.addLink(traceContext); Assert.assertEquals(parentSpanImpl.toSpanData().getContext().getTraceId(), testSpan.toSpanData().getContext().getTraceId()); } @Test public void endSpanNoSuccessErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, null, tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); } @Test public void endSpanErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "custom error message"; final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } @Test public void endSpanTestThrowableResponseCode() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "Resource not found"; final String expectedStatus = "NOT_FOUND"; openCensusTracer.end(404, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } private static void assertSpanWithExplicitParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } private static void assertSpanWithRemoteParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); Assert.assertTrue(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } }
class OpenCensusTracerTest { private static final String METHOD_NAME = "Azure.eventhubs.send"; private static final String HOSTNAME_VALUE = "testEventDataNameSpace.servicebus.windows.net"; private static final String ENTITY_PATH_VALUE = "test"; private static final String COMPONENT_VALUE = "eventhubs"; private OpenCensusTracer openCensusTracer; private Tracer tracer; private Context tracingContext; private Span parentSpan; private io.opencensus.common.Scope scope; @Before public void setUp() { System.out.println("Running: setUp"); openCensusTracer = new OpenCensusTracer(); final TraceConfig traceConfig = Tracing.getTraceConfig(); final TraceParams activeTraceParams = traceConfig.getActiveTraceParams(); traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build()); tracer = Tracing.getTracer(); scope = tracer.spanBuilder(PARENT_SPAN_KEY).startScopedSpan(); parentSpan = tracer.getCurrentSpan(); tracingContext = new Context(PARENT_SPAN_KEY, parentSpan); } @After public void tearDown() { System.out.println("Running: tearDown"); tracer = null; tracingContext = null; Assert.assertNull(tracer); Assert.assertNull(tracingContext); scope.close(); } @Test(expected = NullPointerException.class) public void startSpanNullPointerException() { openCensusTracer.start("", null); } @Test @Test public void startSpanTestNoUserParent() { final Context updatedContext = openCensusTracer.start(METHOD_NAME, Context.NONE); Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertNotNull(recordEventsSpan.toSpanData().getParentSpanId()); } @Test public void startSpanProcessKindSend() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(ENTITY_PATH_KEY, ENTITY_PATH_VALUE) .addData(HOST_NAME_KEY, HOSTNAME_VALUE); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.SEND); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.CLIENT, recordEventsSpan.getKind()); final Map<String, AttributeValue> attributeMap = recordEventsSpan.toSpanData().getAttributes() .getAttributeMap(); Assert.assertEquals(attributeMap.get(COMPONENT), AttributeValue.stringAttributeValue(COMPONENT_VALUE)); Assert.assertEquals(attributeMap.get(MESSAGE_BUS_DESTINATION), AttributeValue.stringAttributeValue(ENTITY_PATH_VALUE)); Assert.assertEquals(attributeMap.get(PEER_ENDPOINT), AttributeValue.stringAttributeValue(HOSTNAME_VALUE)); } @Test public void startSpanProcessKindMessage() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.MESSAGE); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); Assert.assertNotNull(updatedContext.getData(SPAN_CONTEXT_KEY).get()); Assert.assertNotNull(updatedContext.getData(DIAGNOSTIC_ID_KEY).get()); } @Test public void startSpanProcessKindProcess() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.PROCESS); Assert.assertFalse("When no parent span passed in context information", tracingContext.getData(SPAN_CONTEXT_KEY).isPresent()); assertSpanWithExplicitParent(updatedContext, parentSpanId); Assert.assertNotNull(updatedContext.getData("scope").get()); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); } @Test public void startProcessSpanWithRemoteParent() { final Span testSpan = tracer.spanBuilder("child-span").startSpan(); final SpanId testSpanId = testSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.PROCESS); Assert.assertNotNull(updatedContext.getData("scope").get()); assertSpanWithRemoteParent(updatedContext, testSpanId); } @Test(expected = NullPointerException.class) public void startSpanOverloadNullPointerException() { openCensusTracer.start("", Context.NONE, null); } @Test public void addLinkTest() { final RecordEventsSpanImpl testSpan = (RecordEventsSpanImpl) tracer.spanBuilder("new-test-span").startSpan(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final RecordEventsSpanImpl parentSpanImpl = (RecordEventsSpanImpl) parentSpan; final Link expectedLink = Link.fromSpanContext(testSpan.getContext(), Link.Type.PARENT_LINKED_SPAN); openCensusTracer.addLink(traceContext); Link createdLink = parentSpanImpl.toSpanData().getLinks().getLinks().get(0); Assert.assertEquals(expectedLink.getTraceId(), createdLink.getTraceId()); Assert.assertEquals(expectedLink.getSpanId(), createdLink.getSpanId()); } @Test public void endSpanNoSuccessErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, null, tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); } @Test public void endSpanErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "custom error message"; final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } @Test public void endSpanTestThrowableResponseCode() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "Resource not found"; final String expectedStatus = "NOT_FOUND"; openCensusTracer.end(404, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } private static void assertSpanWithExplicitParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } private static void assertSpanWithRemoteParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); Assert.assertTrue(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } }
may be we can pass logger to assertInBounds and let it use to log err, this way we use a client logger attached to the correct class it's gets called from
private void validateFilePermissionAndKey(String filePermission, String filePermissionKey) { if (filePermission != null && filePermissionKey != null) { throw logger.logExceptionAsError(new IllegalArgumentException( FileConstants.MessageConstants.FILE_PERMISSION_FILE_PERMISSION_KEY_INVALID)); } if (filePermission != null) { Utility.assertInBounds("filePermission", filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB); } }
filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB);
private void validateFilePermissionAndKey(String filePermission, String filePermissionKey) { if (filePermission != null && filePermissionKey != null) { throw logger.logExceptionAsError(new IllegalArgumentException( FileConstants.MessageConstants.FILE_PERMISSION_FILE_PERMISSION_KEY_INVALID)); } if (filePermission != null) { Utility.assertInBounds("filePermission", filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB); } }
class FileAsyncClient { private final ClientLogger logger = new ClientLogger(FileAsyncClient.class); private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L; private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300; private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String filePath; private final String snapshot; private final String accountName; /** * Creates a FileAsyncClient that sends requests to the storage file at {@link AzureFileStorageImpl * endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the {@code client}. * * @param azureFileStorageClient Client that interacts with the service interfaces * @param shareName Name of the share * @param filePath Path to the file * @param snapshot The snapshot of the share */ FileAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String filePath, String snapshot, String accountName) { Objects.requireNonNull(shareName, "'shareName' cannot be null."); Objects.requireNonNull(filePath, "'filePath' cannot be null."); this.shareName = shareName; this.filePath = filePath; this.snapshot = snapshot; this.azureFileStorageClient = azureFileStorageClient; this.accountName = accountName; } /** * Get the url of the storage file client. * * @return the URL of the storage file client */ public String getFileUrl() { StringBuilder fileUrlstring = new StringBuilder(azureFileStorageClient.getUrl()).append("/") .append(shareName).append("/").append(filePath); if (snapshot != null) { fileUrlstring.append("?snapshot=").append(snapshot); } return fileUrlstring.toString(); } /** * Creates a file in the storage account and returns a response of {@link FileInfo} to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with size 1KB.</p> * * {@codesnippet com.azure.storage.file.fileClient.create} * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @return A response containing the file info and the status of creating the file. * @throws StorageException If the file has already existed, the parent directory does not exist or fileName is an * invalid resource name. */ public Mono<FileInfo> create(long maxSize) { return createWithResponse(maxSize, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Creates a file in the storage account and returns a response of FileInfo to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with length of 1024 bytes, some headers, file smb properties and metadata.</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.createWithResponse * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @param metadata Optional name-value pairs associated with the file as metadata. * @return A response containing the {@link FileInfo file info} and the status of creating the file. * @throws StorageException If the directory has already existed, the parent directory does not exist or directory * is an invalid resource name. */ public Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata) { return withContext(context -> createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, metadata, context)); } Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); return postProcessResponse(azureFileStorageClient.files() .createWithRestResponseAsync(shareName, filePath, maxSize, fileAttributes, fileCreationTime, fileLastWriteTime, null, metadata, filePermission, filePermissionKey, httpHeaders, context)) .map(this::createFileInfoResponse); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return The {@link FileCopyInfo file copy info}. * @see <a href="https: */ public Mono<FileCopyInfo> startCopy(String sourceUrl, Map<String, String> metadata) { return startCopyWithResponse(sourceUrl, metadata).flatMap(FluxUtil::toMono); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return A response containing the {@link FileCopyInfo file copy info} and the status of copying the file. * @see <a href="https: */ public Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata) { return withContext(context -> startCopyWithResponse(sourceUrl, metadata, context)); } Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .startCopyWithRestResponseAsync(shareName, filePath, sourceUrl, null, metadata, context)) .map(this::startCopyResponse); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopy * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return An empty response. */ public Mono<Void> abortCopy(String copyId) { return abortCopyWithResponse(copyId).flatMap(FluxUtil::toMono); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return A response containing the status of aborting copy the file. */ public Mono<Response<Void>> abortCopyWithResponse(String copyId) { return withContext(context -> abortCopyWithResponse(copyId, context)); } Mono<Response<Void>> abortCopyWithResponse(String copyId, Context context) { return postProcessResponse(azureFileStorageClient.files() .abortCopyWithRestResponseAsync(shareName, filePath, copyId, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFile * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @return An empty response. */ public Mono<FileProperties> downloadToFile(String downloadFilePath) { return downloadToFileWithResponse(downloadFilePath, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @param range Optional byte range which returns file data only from the specified range. * @return An empty response. */ public Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range) { return withContext(context -> downloadToFileWithResponse(downloadFilePath, range, context)); } Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range, Context context) { return Mono.using(() -> channelSetup(downloadFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW), channel -> getPropertiesWithResponse(context).flatMap(response -> downloadResponseInChunk(response, channel, range, context)), this::channelCleanUp); } private Mono<Response<FileProperties>> downloadResponseInChunk(Response<FileProperties> response, AsynchronousFileChannel channel, FileRange range, Context context) { return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new FileRange(0, response.getValue() .getContentLength()))) .map(currentRange -> { List<FileRange> chunks = new ArrayList<>(); for (long pos = currentRange.getStart(); pos < currentRange.getEnd(); pos += FILE_DEFAULT_BLOCK_SIZE) { long count = FILE_DEFAULT_BLOCK_SIZE; if (pos + count > currentRange.getEnd()) { count = currentRange.getEnd() - pos; } chunks.add(new FileRange(pos, pos + count - 1)); } return chunks; }).flatMapMany(Flux::fromIterable).flatMap(chunk -> downloadWithPropertiesWithResponse(chunk, false, context) .map(dar -> dar.getValue().getBody()) .subscribeOn(Schedulers.elastic()) .flatMap(fbb -> FluxUtil .writeFile(fbb, channel, chunk.getStart() - (range == null ? 0 : range.getStart())) .subscribeOn(Schedulers.elastic()) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException))) .then(Mono.just(response)); } private AsynchronousFileChannel channelSetup(String filePath, OpenOption... options) { try { return AsynchronousFileChannel.open(Paths.get(filePath), options); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private void channelCleanUp(AsynchronousFileChannel channel) { try { channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(e))); } } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file with its metadata and properties. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithProperties} * * <p>For more information, see the * <a href="https: * * @return The {@link FileDownloadInfo file download Info} */ public Mono<FileDownloadInfo> downloadWithProperties() { return downloadWithPropertiesWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param range Optional byte range which returns file data only from the specified range. * @param rangeGetContentMD5 Optional boolean which the service returns the MD5 hash for the range when it sets to * true, as long as the range is less than or equal to 4 MB in size. * @return A response containing the {@link FileDownloadInfo file download Info} with headers and response status * code */ public Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5) { return withContext(context -> downloadWithPropertiesWithResponse(range, rangeGetContentMD5, context)); } Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5, Context context) { String rangeString = range == null ? null : range.toString(); return postProcessResponse(azureFileStorageClient.files() .downloadWithRestResponseAsync(shareName, filePath, null, rangeString, rangeGetContentMD5, context)) .map(this::downloadWithPropertiesResponse); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.delete} * * <p>For more information, see the * <a href="https: * * @return An empty response * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Void> delete() { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.deleteWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response that only contains headers and response status code * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Response<Void>> deleteWithResponse() { return withContext(this::deleteWithResponse); } Mono<Response<Void>> deleteWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .deleteWithRestResponseAsync(shareName, filePath, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getProperties} * * <p>For more information, see the * <a href="https: * * @return {@link FileProperties Storage file properties} */ public Mono<FileProperties> getProperties() { return getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getPropertiesWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response containing the {@link FileProperties storage file properties} and response status code */ public Mono<Response<FileProperties>> getPropertiesWithResponse() { return withContext(this::getPropertiesWithResponse); } Mono<Response<FileProperties>> getPropertiesWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .getPropertiesWithRestResponseAsync(shareName, filePath, snapshot, null, context)) .map(this::getPropertiesResponse); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the fileProperties.httpHeaders it will clear the httpHeaders associated to the * file. * If {@code null} is passed for the fileProperties.filesmbproperties it will preserve the filesmb properties * associated with the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file * @return The {@link FileInfo file info} * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<FileInfo> setProperties(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission) .flatMap(FluxUtil::toMono); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the httpHeaders it will clear the httpHeaders associated to the file. * If {@code null} is passed for the filesmbproperties it will preserve the filesmbproperties associated with the * file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @return Response containing the {@link FileInfo file info} and response status code. * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return withContext(context -> setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission, context)); } Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); return postProcessResponse(azureFileStorageClient.files() .setHTTPHeadersWithRestResponseAsync(shareName, filePath, fileAttributes, fileCreationTime, fileLastWriteTime, null, newFileSize, filePermission, filePermissionKey, httpHeaders, context)) .map(this::setPropertiesResponse); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadata * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return {@link FileMetadataInfo file meta info} * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<FileMetadataInfo> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return A response containing the {@link FileMetadataInfo file meta info} and status code * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata) { return withContext(context -> setMetadataWithResponse(metadata, context)); } Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .setMetadataWithRestResponseAsync(shareName, filePath, null, metadata, context)) .map(this::setMetadataResponse); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" to the file in Storage File Service. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @return A response that only contains headers and response status code */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length) { return uploadWithResponse(data, length).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload "default" to the file. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero.. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length) { return withContext(context -> uploadWithResponse(data, length, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, Context context) { FileRange range = new FileRange(0, length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" starting from 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return The {@link FileUploadInfo file upload info} * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length, long offset) { return uploadWithResponse(data, length, offset).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset) { return withContext(context -> uploadWithResponse(data, length, offset, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrl * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return The {@link FileUploadRangeFromUrlInfo file upload range from url info} */ public Mono<FileUploadRangeFromUrlInfo> uploadRangeFromUrl(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI) .flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return A response containing the {@link FileUploadRangeFromUrlInfo file upload range from url info} with headers * and response status code. */ public Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return withContext(context -> uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI, context)); } Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI, Context context) { FileRange destinationRange = new FileRange(destinationOffset, destinationOffset + length - 1); FileRange sourceRange = new FileRange(sourceOffset, sourceOffset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeFromURLWithRestResponseAsync(shareName, filePath, destinationRange.toString(), sourceURI.toString(), 0, null, sourceRange.toString(), null, null, context)) .map(this::uploadRangeFromUrlResponse); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clears the first 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared. * @return The {@link FileUploadInfo file upload info} */ public Mono<FileUploadInfo> clearRange(long length) { return clearRangeWithResponse(length, 0).flatMap(FluxUtil::toMono); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clear the range starting from 1024 with length of 1024. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return A response of {@link FileUploadInfo file upload info} that only contains headers and response status code */ public Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset) { return withContext(context -> clearRangeWithResponse(length, offset, context)); } Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, context)) .map(this::uploadResponse); } /** * Uploads file to storage file service. * * <p><strong>Code Samples</strong></p> * * <p> Upload the file from the source file path. </p> * * (@codesnippet com.azure.storage.file.fileAsyncClient.uploadFromFile
class FileAsyncClient { private final ClientLogger logger = new ClientLogger(FileAsyncClient.class); private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L; private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300; private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String filePath; private final String snapshot; private final String accountName; /** * Creates a FileAsyncClient that sends requests to the storage file at {@link AzureFileStorageImpl * endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the {@code client}. * * @param azureFileStorageClient Client that interacts with the service interfaces * @param shareName Name of the share * @param filePath Path to the file * @param snapshot The snapshot of the share */ FileAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String filePath, String snapshot, String accountName) { Objects.requireNonNull(shareName, "'shareName' cannot be null."); Objects.requireNonNull(filePath, "'filePath' cannot be null."); this.shareName = shareName; this.filePath = filePath; this.snapshot = snapshot; this.azureFileStorageClient = azureFileStorageClient; this.accountName = accountName; } /** * Get the url of the storage file client. * * @return the URL of the storage file client */ public String getFileUrl() { StringBuilder fileUrlstring = new StringBuilder(azureFileStorageClient.getUrl()).append("/") .append(shareName).append("/").append(filePath); if (snapshot != null) { fileUrlstring.append("?snapshot=").append(snapshot); } return fileUrlstring.toString(); } /** * Creates a file in the storage account and returns a response of {@link FileInfo} to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with size 1KB.</p> * * {@codesnippet com.azure.storage.file.fileClient.create} * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @return A response containing the file info and the status of creating the file. * @throws StorageException If the file has already existed, the parent directory does not exist or fileName is an * invalid resource name. */ public Mono<FileInfo> create(long maxSize) { return createWithResponse(maxSize, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Creates a file in the storage account and returns a response of FileInfo to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with length of 1024 bytes, some headers, file smb properties and metadata.</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.createWithResponse * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @param metadata Optional name-value pairs associated with the file as metadata. * @return A response containing the {@link FileInfo file info} and the status of creating the file. * @throws StorageException If the directory has already existed, the parent directory does not exist or directory * is an invalid resource name. */ public Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata) { return withContext(context -> createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, metadata, context)); } Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); return postProcessResponse(azureFileStorageClient.files() .createWithRestResponseAsync(shareName, filePath, maxSize, fileAttributes, fileCreationTime, fileLastWriteTime, null, metadata, filePermission, filePermissionKey, httpHeaders, context)) .map(this::createFileInfoResponse); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return The {@link FileCopyInfo file copy info}. * @see <a href="https: */ public Mono<FileCopyInfo> startCopy(String sourceUrl, Map<String, String> metadata) { return startCopyWithResponse(sourceUrl, metadata).flatMap(FluxUtil::toMono); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return A response containing the {@link FileCopyInfo file copy info} and the status of copying the file. * @see <a href="https: */ public Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata) { return withContext(context -> startCopyWithResponse(sourceUrl, metadata, context)); } Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .startCopyWithRestResponseAsync(shareName, filePath, sourceUrl, null, metadata, context)) .map(this::startCopyResponse); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopy * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return An empty response. */ public Mono<Void> abortCopy(String copyId) { return abortCopyWithResponse(copyId).flatMap(FluxUtil::toMono); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return A response containing the status of aborting copy the file. */ public Mono<Response<Void>> abortCopyWithResponse(String copyId) { return withContext(context -> abortCopyWithResponse(copyId, context)); } Mono<Response<Void>> abortCopyWithResponse(String copyId, Context context) { return postProcessResponse(azureFileStorageClient.files() .abortCopyWithRestResponseAsync(shareName, filePath, copyId, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFile * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @return An empty response. */ public Mono<FileProperties> downloadToFile(String downloadFilePath) { return downloadToFileWithResponse(downloadFilePath, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @param range Optional byte range which returns file data only from the specified range. * @return An empty response. */ public Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range) { return withContext(context -> downloadToFileWithResponse(downloadFilePath, range, context)); } Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range, Context context) { return Mono.using(() -> channelSetup(downloadFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW), channel -> getPropertiesWithResponse(context).flatMap(response -> downloadResponseInChunk(response, channel, range, context)), this::channelCleanUp); } private Mono<Response<FileProperties>> downloadResponseInChunk(Response<FileProperties> response, AsynchronousFileChannel channel, FileRange range, Context context) { return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new FileRange(0, response.getValue() .getContentLength()))) .map(currentRange -> { List<FileRange> chunks = new ArrayList<>(); for (long pos = currentRange.getStart(); pos < currentRange.getEnd(); pos += FILE_DEFAULT_BLOCK_SIZE) { long count = FILE_DEFAULT_BLOCK_SIZE; if (pos + count > currentRange.getEnd()) { count = currentRange.getEnd() - pos; } chunks.add(new FileRange(pos, pos + count - 1)); } return chunks; }).flatMapMany(Flux::fromIterable).flatMap(chunk -> downloadWithPropertiesWithResponse(chunk, false, context) .map(dar -> dar.getValue().getBody()) .subscribeOn(Schedulers.elastic()) .flatMap(fbb -> FluxUtil .writeFile(fbb, channel, chunk.getStart() - (range == null ? 0 : range.getStart())) .subscribeOn(Schedulers.elastic()) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException))) .then(Mono.just(response)); } private AsynchronousFileChannel channelSetup(String filePath, OpenOption... options) { try { return AsynchronousFileChannel.open(Paths.get(filePath), options); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private void channelCleanUp(AsynchronousFileChannel channel) { try { channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(e))); } } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file with its metadata and properties. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithProperties} * * <p>For more information, see the * <a href="https: * * @return The {@link FileDownloadInfo file download Info} */ public Mono<FileDownloadInfo> downloadWithProperties() { return downloadWithPropertiesWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param range Optional byte range which returns file data only from the specified range. * @param rangeGetContentMD5 Optional boolean which the service returns the MD5 hash for the range when it sets to * true, as long as the range is less than or equal to 4 MB in size. * @return A response containing the {@link FileDownloadInfo file download Info} with headers and response status * code */ public Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5) { return withContext(context -> downloadWithPropertiesWithResponse(range, rangeGetContentMD5, context)); } Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5, Context context) { String rangeString = range == null ? null : range.toString(); return postProcessResponse(azureFileStorageClient.files() .downloadWithRestResponseAsync(shareName, filePath, null, rangeString, rangeGetContentMD5, context)) .map(this::downloadWithPropertiesResponse); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.delete} * * <p>For more information, see the * <a href="https: * * @return An empty response * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Void> delete() { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.deleteWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response that only contains headers and response status code * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Response<Void>> deleteWithResponse() { return withContext(this::deleteWithResponse); } Mono<Response<Void>> deleteWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .deleteWithRestResponseAsync(shareName, filePath, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getProperties} * * <p>For more information, see the * <a href="https: * * @return {@link FileProperties Storage file properties} */ public Mono<FileProperties> getProperties() { return getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getPropertiesWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response containing the {@link FileProperties storage file properties} and response status code */ public Mono<Response<FileProperties>> getPropertiesWithResponse() { return withContext(this::getPropertiesWithResponse); } Mono<Response<FileProperties>> getPropertiesWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .getPropertiesWithRestResponseAsync(shareName, filePath, snapshot, null, context)) .map(this::getPropertiesResponse); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the fileProperties.httpHeaders it will clear the httpHeaders associated to the * file. * If {@code null} is passed for the fileProperties.filesmbproperties it will preserve the filesmb properties * associated with the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file * @return The {@link FileInfo file info} * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<FileInfo> setProperties(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission) .flatMap(FluxUtil::toMono); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the httpHeaders it will clear the httpHeaders associated to the file. * If {@code null} is passed for the filesmbproperties it will preserve the filesmbproperties associated with the * file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @return Response containing the {@link FileInfo file info} and response status code. * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return withContext(context -> setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission, context)); } Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); return postProcessResponse(azureFileStorageClient.files() .setHTTPHeadersWithRestResponseAsync(shareName, filePath, fileAttributes, fileCreationTime, fileLastWriteTime, null, newFileSize, filePermission, filePermissionKey, httpHeaders, context)) .map(this::setPropertiesResponse); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadata * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return {@link FileMetadataInfo file meta info} * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<FileMetadataInfo> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return A response containing the {@link FileMetadataInfo file meta info} and status code * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata) { return withContext(context -> setMetadataWithResponse(metadata, context)); } Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .setMetadataWithRestResponseAsync(shareName, filePath, null, metadata, context)) .map(this::setMetadataResponse); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" to the file in Storage File Service. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @return A response that only contains headers and response status code */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length) { return uploadWithResponse(data, length).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload "default" to the file. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero.. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length) { return withContext(context -> uploadWithResponse(data, length, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, Context context) { FileRange range = new FileRange(0, length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" starting from 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return The {@link FileUploadInfo file upload info} * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length, long offset) { return uploadWithResponse(data, length, offset).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset) { return withContext(context -> uploadWithResponse(data, length, offset, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrl * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return The {@link FileUploadRangeFromUrlInfo file upload range from url info} */ public Mono<FileUploadRangeFromUrlInfo> uploadRangeFromUrl(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI) .flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return A response containing the {@link FileUploadRangeFromUrlInfo file upload range from url info} with headers * and response status code. */ public Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return withContext(context -> uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI, context)); } Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI, Context context) { FileRange destinationRange = new FileRange(destinationOffset, destinationOffset + length - 1); FileRange sourceRange = new FileRange(sourceOffset, sourceOffset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeFromURLWithRestResponseAsync(shareName, filePath, destinationRange.toString(), sourceURI.toString(), 0, null, sourceRange.toString(), null, null, context)) .map(this::uploadRangeFromUrlResponse); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clears the first 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared. * @return The {@link FileUploadInfo file upload info} */ public Mono<FileUploadInfo> clearRange(long length) { return clearRangeWithResponse(length, 0).flatMap(FluxUtil::toMono); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clear the range starting from 1024 with length of 1024. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return A response of {@link FileUploadInfo file upload info} that only contains headers and response status code */ public Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset) { return withContext(context -> clearRangeWithResponse(length, offset, context)); } Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, context)) .map(this::uploadResponse); } /** * Uploads file to storage file service. * * <p><strong>Code Samples</strong></p> * * <p> Upload the file from the source file path. </p> * * (@codesnippet com.azure.storage.file.fileAsyncClient.uploadFromFile
this seems to be an incorrect validation. Links do not flow into trace-id. So i guess what happens in this test: setUp creates parent span testSpan will get same TraceId - because it's a child traceContext gets context from traceSpan link is created from traceContext (which shares trace-id with parentSpan and testSpan Then you check if parentSpan has the same traceId as link What should be tested: link should have random context - new one you add it to the span and then compare links on the parent span to what you've added
public void addLinkTest() { final RecordEventsSpanImpl testSpan = (RecordEventsSpanImpl) tracer.spanBuilder("new-test-span").startSpan(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final RecordEventsSpanImpl parentSpanImpl = (RecordEventsSpanImpl) parentSpan; openCensusTracer.addLink(traceContext); Assert.assertEquals(parentSpanImpl.toSpanData().getContext().getTraceId(), testSpan.toSpanData().getContext().getTraceId()); }
Assert.assertEquals(parentSpanImpl.toSpanData().getContext().getTraceId(),
public void addLinkTest() { final RecordEventsSpanImpl testSpan = (RecordEventsSpanImpl) tracer.spanBuilder("new-test-span").startSpan(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final RecordEventsSpanImpl parentSpanImpl = (RecordEventsSpanImpl) parentSpan; final Link expectedLink = Link.fromSpanContext(testSpan.getContext(), Link.Type.PARENT_LINKED_SPAN); openCensusTracer.addLink(traceContext); Link createdLink = parentSpanImpl.toSpanData().getLinks().getLinks().get(0); Assert.assertEquals(expectedLink.getTraceId(), createdLink.getTraceId()); Assert.assertEquals(expectedLink.getSpanId(), createdLink.getSpanId()); }
class OpenCensusTracerTest { private static final String METHOD_NAME = "Azure.eventhubs.send"; private static final String HOSTNAME_VALUE = "testEventDataNameSpace.servicebus.windows.net"; private static final String ENTITY_PATH_VALUE = "test"; private static final String COMPONENT_VALUE = "eventhubs"; private OpenCensusTracer openCensusTracer; private Tracer tracer; private Context tracingContext; private Span parentSpan; private io.opencensus.common.Scope scope; @Before public void setUp() { System.out.println("Running: setUp"); openCensusTracer = new OpenCensusTracer(); final TraceConfig traceConfig = Tracing.getTraceConfig(); final TraceParams activeTraceParams = traceConfig.getActiveTraceParams(); traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build()); tracer = Tracing.getTracer(); scope = tracer.spanBuilder(PARENT_SPAN_KEY).startScopedSpan(); parentSpan = tracer.getCurrentSpan(); tracingContext = new Context(PARENT_SPAN_KEY, parentSpan); } @After public void tearDown() { System.out.println("Running: tearDown"); tracer = null; tracingContext = null; Assert.assertNull(tracer); Assert.assertNull(tracingContext); scope.close(); } @Test(expected = NullPointerException.class) public void startSpanNullPointerException() { openCensusTracer.start("", null); } @Test public void startSpanParentContextFlowTest() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); } @Test public void startSpanTestNoUserParent() { final Context updatedContext = openCensusTracer.start(METHOD_NAME, Context.NONE); Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertNotNull(recordEventsSpan.toSpanData().getParentSpanId()); } @Test public void startSpanProcessKindSend() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(ENTITY_PATH_KEY, ENTITY_PATH_VALUE) .addData(HOST_NAME_KEY, HOSTNAME_VALUE); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.SEND); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.CLIENT, recordEventsSpan.getKind()); final Map<String, AttributeValue> attributeMap = recordEventsSpan.toSpanData().getAttributes() .getAttributeMap(); Assert.assertEquals(attributeMap.get(COMPONENT), AttributeValue.stringAttributeValue(COMPONENT_VALUE)); Assert.assertEquals(attributeMap.get(MESSAGE_BUS_DESTINATION), AttributeValue.stringAttributeValue(ENTITY_PATH_VALUE)); Assert.assertEquals(attributeMap.get(PEER_ENDPOINT), AttributeValue.stringAttributeValue(HOSTNAME_VALUE)); } @Test public void startSpanProcessKindReceive() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.RECEIVE); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); Assert.assertNotNull(updatedContext.getData(SPAN_CONTEXT_KEY).get()); Assert.assertNotNull(updatedContext.getData(DIAGNOSTIC_ID_KEY).get()); } @Test public void startSpanProcessKindProcess() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.PROCESS); Assert.assertFalse("When no parent span passed in context information", tracingContext.getData(SPAN_CONTEXT_KEY).isPresent()); assertSpanWithExplicitParent(updatedContext, parentSpanId); Assert.assertNotNull(updatedContext.getData("scope").get()); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); } @Test public void startProcessSpanWithRemoteParent() { final Span testSpan = tracer.spanBuilder("child-span").startSpan(); final SpanId testSpanId = testSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.PROCESS); Assert.assertNotNull(updatedContext.getData("scope").get()); assertSpanWithRemoteParent(updatedContext, testSpanId); } @Test(expected = NullPointerException.class) public void startSpanOverloadNullPointerException() { openCensusTracer.start("", Context.NONE, null); } @Test @Test public void endSpanNoSuccessErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, null, tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); } @Test public void endSpanErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "custom error message"; final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } @Test public void endSpanTestThrowableResponseCode() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "Resource not found"; final String expectedStatus = "NOT_FOUND"; openCensusTracer.end(404, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } private static void assertSpanWithExplicitParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } private static void assertSpanWithRemoteParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); Assert.assertTrue(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } }
class OpenCensusTracerTest { private static final String METHOD_NAME = "Azure.eventhubs.send"; private static final String HOSTNAME_VALUE = "testEventDataNameSpace.servicebus.windows.net"; private static final String ENTITY_PATH_VALUE = "test"; private static final String COMPONENT_VALUE = "eventhubs"; private OpenCensusTracer openCensusTracer; private Tracer tracer; private Context tracingContext; private Span parentSpan; private io.opencensus.common.Scope scope; @Before public void setUp() { System.out.println("Running: setUp"); openCensusTracer = new OpenCensusTracer(); final TraceConfig traceConfig = Tracing.getTraceConfig(); final TraceParams activeTraceParams = traceConfig.getActiveTraceParams(); traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build()); tracer = Tracing.getTracer(); scope = tracer.spanBuilder(PARENT_SPAN_KEY).startScopedSpan(); parentSpan = tracer.getCurrentSpan(); tracingContext = new Context(PARENT_SPAN_KEY, parentSpan); } @After public void tearDown() { System.out.println("Running: tearDown"); tracer = null; tracingContext = null; Assert.assertNull(tracer); Assert.assertNull(tracingContext); scope.close(); } @Test(expected = NullPointerException.class) public void startSpanNullPointerException() { openCensusTracer.start("", null); } @Test public void startSpanParentContextFlowTest() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); } @Test public void startSpanTestNoUserParent() { final Context updatedContext = openCensusTracer.start(METHOD_NAME, Context.NONE); Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertNotNull(recordEventsSpan.toSpanData().getParentSpanId()); } @Test public void startSpanProcessKindSend() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(ENTITY_PATH_KEY, ENTITY_PATH_VALUE) .addData(HOST_NAME_KEY, HOSTNAME_VALUE); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.SEND); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.CLIENT, recordEventsSpan.getKind()); final Map<String, AttributeValue> attributeMap = recordEventsSpan.toSpanData().getAttributes() .getAttributeMap(); Assert.assertEquals(attributeMap.get(COMPONENT), AttributeValue.stringAttributeValue(COMPONENT_VALUE)); Assert.assertEquals(attributeMap.get(MESSAGE_BUS_DESTINATION), AttributeValue.stringAttributeValue(ENTITY_PATH_VALUE)); Assert.assertEquals(attributeMap.get(PEER_ENDPOINT), AttributeValue.stringAttributeValue(HOSTNAME_VALUE)); } @Test public void startSpanProcessKindMessage() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.MESSAGE); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); Assert.assertNotNull(updatedContext.getData(SPAN_CONTEXT_KEY).get()); Assert.assertNotNull(updatedContext.getData(DIAGNOSTIC_ID_KEY).get()); } @Test public void startSpanProcessKindProcess() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.PROCESS); Assert.assertFalse("When no parent span passed in context information", tracingContext.getData(SPAN_CONTEXT_KEY).isPresent()); assertSpanWithExplicitParent(updatedContext, parentSpanId); Assert.assertNotNull(updatedContext.getData("scope").get()); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); } @Test public void startProcessSpanWithRemoteParent() { final Span testSpan = tracer.spanBuilder("child-span").startSpan(); final SpanId testSpanId = testSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.PROCESS); Assert.assertNotNull(updatedContext.getData("scope").get()); assertSpanWithRemoteParent(updatedContext, testSpanId); } @Test(expected = NullPointerException.class) public void startSpanOverloadNullPointerException() { openCensusTracer.start("", Context.NONE, null); } @Test @Test public void endSpanNoSuccessErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, null, tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); } @Test public void endSpanErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "custom error message"; final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } @Test public void endSpanTestThrowableResponseCode() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "Resource not found"; final String expectedStatus = "NOT_FOUND"; openCensusTracer.end(404, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } private static void assertSpanWithExplicitParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } private static void assertSpanWithRemoteParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); Assert.assertTrue(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } }
Just to validate it isn't getting set anywhere in the workflow.
public void startSpanParentContextFlowTest() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); }
Assert.assertNull(recordEventsSpan.getKind());
public void startSpanParentContextFlowTest() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); }
class OpenCensusTracerTest { private static final String METHOD_NAME = "Azure.eventhubs.send"; private static final String HOSTNAME_VALUE = "testEventDataNameSpace.servicebus.windows.net"; private static final String ENTITY_PATH_VALUE = "test"; private static final String COMPONENT_VALUE = "eventhubs"; private OpenCensusTracer openCensusTracer; private Tracer tracer; private Context tracingContext; private Span parentSpan; private io.opencensus.common.Scope scope; @Before public void setUp() { System.out.println("Running: setUp"); openCensusTracer = new OpenCensusTracer(); final TraceConfig traceConfig = Tracing.getTraceConfig(); final TraceParams activeTraceParams = traceConfig.getActiveTraceParams(); traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build()); tracer = Tracing.getTracer(); scope = tracer.spanBuilder(PARENT_SPAN_KEY).startScopedSpan(); parentSpan = tracer.getCurrentSpan(); tracingContext = new Context(PARENT_SPAN_KEY, parentSpan); } @After public void tearDown() { System.out.println("Running: tearDown"); tracer = null; tracingContext = null; Assert.assertNull(tracer); Assert.assertNull(tracingContext); scope.close(); } @Test(expected = NullPointerException.class) public void startSpanNullPointerException() { openCensusTracer.start("", null); } @Test @Test public void startSpanTestNoUserParent() { final Context updatedContext = openCensusTracer.start(METHOD_NAME, Context.NONE); Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertNotNull(recordEventsSpan.toSpanData().getParentSpanId()); } @Test public void startSpanProcessKindSend() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(ENTITY_PATH_KEY, ENTITY_PATH_VALUE) .addData(HOST_NAME_KEY, HOSTNAME_VALUE); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.SEND); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.CLIENT, recordEventsSpan.getKind()); final Map<String, AttributeValue> attributeMap = recordEventsSpan.toSpanData().getAttributes() .getAttributeMap(); Assert.assertEquals(attributeMap.get(COMPONENT), AttributeValue.stringAttributeValue(COMPONENT_VALUE)); Assert.assertEquals(attributeMap.get(MESSAGE_BUS_DESTINATION), AttributeValue.stringAttributeValue(ENTITY_PATH_VALUE)); Assert.assertEquals(attributeMap.get(PEER_ENDPOINT), AttributeValue.stringAttributeValue(HOSTNAME_VALUE)); } @Test public void startSpanProcessKindReceive() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.RECEIVE); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); Assert.assertNotNull(updatedContext.getData(SPAN_CONTEXT_KEY).get()); Assert.assertNotNull(updatedContext.getData(DIAGNOSTIC_ID_KEY).get()); } @Test public void startSpanProcessKindProcess() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.PROCESS); Assert.assertFalse("When no parent span passed in context information", tracingContext.getData(SPAN_CONTEXT_KEY).isPresent()); assertSpanWithExplicitParent(updatedContext, parentSpanId); Assert.assertNotNull(updatedContext.getData("scope").get()); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); } @Test public void startProcessSpanWithRemoteParent() { final Span testSpan = tracer.spanBuilder("child-span").startSpan(); final SpanId testSpanId = testSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.PROCESS); Assert.assertNotNull(updatedContext.getData("scope").get()); assertSpanWithRemoteParent(updatedContext, testSpanId); } @Test(expected = NullPointerException.class) public void startSpanOverloadNullPointerException() { openCensusTracer.start("", Context.NONE, null); } @Test public void addLinkTest() { final RecordEventsSpanImpl testSpan = (RecordEventsSpanImpl) tracer.spanBuilder("new-test-span").startSpan(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final RecordEventsSpanImpl parentSpanImpl = (RecordEventsSpanImpl) parentSpan; openCensusTracer.addLink(traceContext); Assert.assertEquals(parentSpanImpl.toSpanData().getContext().getTraceId(), testSpan.toSpanData().getContext().getTraceId()); } @Test public void endSpanNoSuccessErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, null, tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); } @Test public void endSpanErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "custom error message"; final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } @Test public void endSpanTestThrowableResponseCode() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "Resource not found"; final String expectedStatus = "NOT_FOUND"; openCensusTracer.end(404, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } private static void assertSpanWithExplicitParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } private static void assertSpanWithRemoteParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); Assert.assertTrue(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } }
class OpenCensusTracerTest { private static final String METHOD_NAME = "Azure.eventhubs.send"; private static final String HOSTNAME_VALUE = "testEventDataNameSpace.servicebus.windows.net"; private static final String ENTITY_PATH_VALUE = "test"; private static final String COMPONENT_VALUE = "eventhubs"; private OpenCensusTracer openCensusTracer; private Tracer tracer; private Context tracingContext; private Span parentSpan; private io.opencensus.common.Scope scope; @Before public void setUp() { System.out.println("Running: setUp"); openCensusTracer = new OpenCensusTracer(); final TraceConfig traceConfig = Tracing.getTraceConfig(); final TraceParams activeTraceParams = traceConfig.getActiveTraceParams(); traceConfig.updateActiveTraceParams(activeTraceParams.toBuilder().setSampler(Samplers.alwaysSample()).build()); tracer = Tracing.getTracer(); scope = tracer.spanBuilder(PARENT_SPAN_KEY).startScopedSpan(); parentSpan = tracer.getCurrentSpan(); tracingContext = new Context(PARENT_SPAN_KEY, parentSpan); } @After public void tearDown() { System.out.println("Running: tearDown"); tracer = null; tracingContext = null; Assert.assertNull(tracer); Assert.assertNull(tracingContext); scope.close(); } @Test(expected = NullPointerException.class) public void startSpanNullPointerException() { openCensusTracer.start("", null); } @Test @Test public void startSpanTestNoUserParent() { final Context updatedContext = openCensusTracer.start(METHOD_NAME, Context.NONE); Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertNotNull(recordEventsSpan.toSpanData().getParentSpanId()); } @Test public void startSpanProcessKindSend() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(ENTITY_PATH_KEY, ENTITY_PATH_VALUE) .addData(HOST_NAME_KEY, HOSTNAME_VALUE); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.SEND); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.CLIENT, recordEventsSpan.getKind()); final Map<String, AttributeValue> attributeMap = recordEventsSpan.toSpanData().getAttributes() .getAttributeMap(); Assert.assertEquals(attributeMap.get(COMPONENT), AttributeValue.stringAttributeValue(COMPONENT_VALUE)); Assert.assertEquals(attributeMap.get(MESSAGE_BUS_DESTINATION), AttributeValue.stringAttributeValue(ENTITY_PATH_VALUE)); Assert.assertEquals(attributeMap.get(PEER_ENDPOINT), AttributeValue.stringAttributeValue(HOSTNAME_VALUE)); } @Test public void startSpanProcessKindMessage() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.MESSAGE); assertSpanWithExplicitParent(updatedContext, parentSpanId); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertNull(recordEventsSpan.getKind()); Assert.assertNotNull(updatedContext.getData(SPAN_CONTEXT_KEY).get()); Assert.assertNotNull(updatedContext.getData(DIAGNOSTIC_ID_KEY).get()); } @Test public void startSpanProcessKindProcess() { final SpanId parentSpanId = parentSpan.getContext().getSpanId(); final Context updatedContext = openCensusTracer.start(METHOD_NAME, tracingContext, ProcessKind.PROCESS); Assert.assertFalse("When no parent span passed in context information", tracingContext.getData(SPAN_CONTEXT_KEY).isPresent()); assertSpanWithExplicitParent(updatedContext, parentSpanId); Assert.assertNotNull(updatedContext.getData("scope").get()); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); } @Test public void startProcessSpanWithRemoteParent() { final Span testSpan = tracer.spanBuilder("child-span").startSpan(); final SpanId testSpanId = testSpan.getContext().getSpanId(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final Context updatedContext = openCensusTracer.start(METHOD_NAME, traceContext, ProcessKind.PROCESS); Assert.assertNotNull(updatedContext.getData("scope").get()); assertSpanWithRemoteParent(updatedContext, testSpanId); } @Test(expected = NullPointerException.class) public void startSpanOverloadNullPointerException() { openCensusTracer.start("", Context.NONE, null); } @Test public void addLinkTest() { final RecordEventsSpanImpl testSpan = (RecordEventsSpanImpl) tracer.spanBuilder("new-test-span").startSpan(); final Context traceContext = tracingContext.addData(SPAN_CONTEXT_KEY, testSpan.getContext()); final RecordEventsSpanImpl parentSpanImpl = (RecordEventsSpanImpl) parentSpan; final Link expectedLink = Link.fromSpanContext(testSpan.getContext(), Link.Type.PARENT_LINKED_SPAN); openCensusTracer.addLink(traceContext); Link createdLink = parentSpanImpl.toSpanData().getLinks().getLinks().get(0); Assert.assertEquals(expectedLink.getTraceId(), createdLink.getTraceId()); Assert.assertEquals(expectedLink.getSpanId(), createdLink.getSpanId()); } @Test public void endSpanNoSuccessErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, null, tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); } @Test public void endSpanErrorMessageTest() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "custom error message"; final String expectedStatus = "UNKNOWN"; openCensusTracer.end(null, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } @Test public void endSpanTestThrowableResponseCode() { final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) tracer.getCurrentSpan(); final String throwableMessage = "Resource not found"; final String expectedStatus = "NOT_FOUND"; openCensusTracer.end(404, new Throwable(throwableMessage), tracingContext); Assert.assertEquals(expectedStatus, recordEventsSpan.getStatus().getCanonicalCode().toString()); Assert.assertEquals(throwableMessage, recordEventsSpan.getStatus().getDescription()); } private static void assertSpanWithExplicitParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertFalse(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } private static void assertSpanWithRemoteParent(Context updatedContext, SpanId parentSpanId) { Assert.assertNotNull(updatedContext.getData(PARENT_SPAN_KEY)); Assert.assertTrue(updatedContext.getData(PARENT_SPAN_KEY).get() instanceof RecordEventsSpanImpl); final RecordEventsSpanImpl recordEventsSpan = (RecordEventsSpanImpl) updatedContext.getData(PARENT_SPAN_KEY).get(); Assert.assertEquals(METHOD_NAME, recordEventsSpan.getName()); Assert.assertEquals(Span.Kind.SERVER, recordEventsSpan.getKind()); Assert.assertTrue(recordEventsSpan.toSpanData().getHasRemoteParent()); Assert.assertEquals(parentSpanId, recordEventsSpan.toSpanData().getParentSpanId()); } }
AtomicBoolean is sufficient. Then you can do: ```java if (!isFirst.getAndSet(true)) { // update sendSpanContext only once Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } // add span context on event data return setSpanContext(eventData, parentContext); ```
private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE); return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); final AtomicReference<Boolean> isFirst = new AtomicReference<>(true); return events.map(eventData -> { Context parentContext = eventData.getContext(); if (isFirst.get()) { Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider .startSpan(entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } isFirst.set(false); return setSpanContext(eventData, parentContext); }).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))) .doOnEach(signal -> { tracerProvider.endSpan(sendSpanContext.get(), signal); }); }); }
final AtomicReference<Boolean> isFirst = new AtomicReference<>(true);
private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE); return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); final AtomicReference<Boolean> isFirst = new AtomicReference<>(true); return events.map(eventData -> { Context parentContext = eventData.getContext(); if (isFirst.getAndSet(false)) { Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } return setSpanContext(eventData, parentContext); }).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))) .doOnEach(signal -> { tracerProvider.endSpan(sendSpanContext.get(), signal); }); }); }
class EventHubAsyncProducer implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions(); private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final EventHubProducerOptions senderOptions; private final Mono<AmqpSendLink> sendLinkMono; private final boolean isPartitionSender; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; /** * Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link * EventHubProducerOptions * otherwise, allows the service to load balance the messages amongst available partitions. */ EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.sendLinkMono = amqpSendLinkMono.cache(); this.senderOptions = options; this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId()); this.tracerProvider = tracerProvider; this.messageSerializer = messageSerializer; } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @param options A set of options used to configure the {@link EventDataBatch}. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch(BatchOptions options) { Objects.requireNonNull(options, "'options' cannot be null."); final BatchOptions clone = options.clone(); verifyPartitionKey(clone.getPartitionKey()); return sendLinkMono.flatMap(link -> link.getLinkSize() .flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (clone.getMaximumSizeInBytes() > maximumLinkSize) { return Mono.error(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).", clone.getMaximumSizeInBytes(), maximumLinkSize))); } final int batchSize = clone.getMaximumSizeInBytes() > 0 ? clone.getMaximumSizeInBytes() : maximumLinkSize; return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext)); })); } /** * Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size * allowed, an exception will be triggered and the send will fail. * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * * @param event Event to send to the service. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event) { Objects.requireNonNull(event, "'event' cannot be null."); return send(Flux.just(event)); } /** * Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds * the maximum size allowed, an exception will be triggered and the send will fail. * * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * @param event Event to send to the service. * @param options The set of options to consider when sending this event. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event, SendOptions options) { Objects.requireNonNull(event, "'event' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return send(Flux.just(event), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(Flux.fromIterable(events)); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'options' cannot be null."); return send(Flux.fromIterable(events), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(events, DEFAULT_SEND_OPTIONS); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'events' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return sendInternal(events, options); } /** * Sends the batch to the associated Event Hub. * * @param batch The batch to send to the service. * @return A {@link Mono} that completes when the batch is pushed to the service. * @throws NullPointerException if {@code batch} is {@code null}. * @see EventHubAsyncProducer * @see EventHubAsyncProducer */ public Mono<Void> send(EventDataBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); if (batch.getEvents().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) { logger.info("Sending batch with size[{}].", batch.getSize()); } else { logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey()); } final String partitionKey = batch.getPartitionKey(); final List<Message> messages = batch.getEvents().stream().map(event -> { final Message message = messageSerializer.serialize(event); if (!ImplUtils.isNullOrEmpty(partitionKey)) { final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey); message.setMessageAnnotations(messageAnnotations); } return message; }).collect(Collectors.toList()); return sendLinkMono.flatMap(link -> messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages)); } private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); verifyPartitionKey(partitionKey); if (tracerProvider.isEnabled()) { return sendInternalTracingEnabled(events, partitionKey); } else { return sendInternalTracingDisabled(events, partitionKey); } } private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))); }); } private EventData setSpanContext(EventData event, Context parentContext) { Optional<Object> eventContextData = event.getContext().getData(SPAN_CONTEXT); if (eventContextData.isPresent()) { Object spanContextObject = eventContextData.get(); if (spanContextObject instanceof Context) { tracerProvider.addSpanLinks((Context) eventContextData.get()); } else { logger.warning(String.format(Locale.US, "Event Data context type is not of type Context, but type: %s. Not adding span links.", spanContextObject != null ? spanContextObject.getClass() : "null")); } return event; } else { Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE); if (eventSpanContext != null) { Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { event.addProperty(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get().toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); event.addContext(SPAN_CONTEXT, eventSpanContext); } } } return event; } private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private void verifyPartitionKey(String partitionKey) { if (ImplUtils.isNullOrEmpty(partitionKey)) { return; } if (isPartitionSender) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with" + "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to " + "partition '%s'.", senderOptions.getPartitionId()))); } else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey, MAX_PARTITION_KEY_LENGTH))); } } /** * Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service. * @throws IOException if the underlying transport could not be closed and its resources could not be * disposed. */ @Override public void close() throws IOException { if (!isDisposed.getAndSet(true)) { final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout()); if (block != null) { block.close(); } } } /** * Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then * it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code * maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link * ErrorCondition */ private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>, List<EventDataBatch>> { private final String partitionKey; private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private volatile EventDataBatch currentBatch; EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.partitionKey = options.getPartitionKey(); this.contextProvider = contextProvider; currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider); } @Override public Supplier<List<EventDataBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<EventDataBatch>, EventData> accumulator() { return (list, event) -> { EventDataBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<EventDataBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() { return list -> { EventDataBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
class EventHubAsyncProducer implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions(); private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final EventHubProducerOptions senderOptions; private final Mono<AmqpSendLink> sendLinkMono; private final boolean isPartitionSender; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; /** * Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link * EventHubProducerOptions * otherwise, allows the service to load balance the messages amongst available partitions. */ EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.sendLinkMono = amqpSendLinkMono.cache(); this.senderOptions = options; this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId()); this.tracerProvider = tracerProvider; this.messageSerializer = messageSerializer; } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @param options A set of options used to configure the {@link EventDataBatch}. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch(BatchOptions options) { Objects.requireNonNull(options, "'options' cannot be null."); final BatchOptions clone = options.clone(); verifyPartitionKey(clone.getPartitionKey()); return sendLinkMono.flatMap(link -> link.getLinkSize() .flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (clone.getMaximumSizeInBytes() > maximumLinkSize) { return Mono.error(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).", clone.getMaximumSizeInBytes(), maximumLinkSize))); } final int batchSize = clone.getMaximumSizeInBytes() > 0 ? clone.getMaximumSizeInBytes() : maximumLinkSize; return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext)); })); } /** * Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size * allowed, an exception will be triggered and the send will fail. * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * * @param event Event to send to the service. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event) { Objects.requireNonNull(event, "'event' cannot be null."); return send(Flux.just(event)); } /** * Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds * the maximum size allowed, an exception will be triggered and the send will fail. * * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * @param event Event to send to the service. * @param options The set of options to consider when sending this event. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event, SendOptions options) { Objects.requireNonNull(event, "'event' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return send(Flux.just(event), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(Flux.fromIterable(events)); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'options' cannot be null."); return send(Flux.fromIterable(events), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(events, DEFAULT_SEND_OPTIONS); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'events' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return sendInternal(events, options); } /** * Sends the batch to the associated Event Hub. * * @param batch The batch to send to the service. * @return A {@link Mono} that completes when the batch is pushed to the service. * @throws NullPointerException if {@code batch} is {@code null}. * @see EventHubAsyncProducer * @see EventHubAsyncProducer */ public Mono<Void> send(EventDataBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); if (batch.getEvents().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) { logger.info("Sending batch with size[{}].", batch.getSize()); } else { logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey()); } final String partitionKey = batch.getPartitionKey(); final List<Message> messages = batch.getEvents().stream().map(event -> { final Message message = messageSerializer.serialize(event); if (!ImplUtils.isNullOrEmpty(partitionKey)) { final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey); message.setMessageAnnotations(messageAnnotations); } return message; }).collect(Collectors.toList()); return sendLinkMono.flatMap(link -> messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages)); } private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); verifyPartitionKey(partitionKey); if (tracerProvider.isEnabled()) { return sendInternalTracingEnabled(events, partitionKey); } else { return sendInternalTracingDisabled(events, partitionKey); } } private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))); }); } private EventData setSpanContext(EventData event, Context parentContext) { Optional<Object> eventContextData = event.getContext().getData(SPAN_CONTEXT); if (eventContextData.isPresent()) { Object spanContextObject = eventContextData.get(); if (spanContextObject instanceof Context) { tracerProvider.addSpanLinks((Context) eventContextData.get()); } else { logger.warning(String.format(Locale.US, "Event Data context type is not of type Context, but type: %s. Not adding span links.", spanContextObject != null ? spanContextObject.getClass() : "null")); } return event; } else { Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE); if (eventSpanContext != null) { Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { event.addProperty(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get().toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); event.addContext(SPAN_CONTEXT, eventSpanContext); } } } return event; } private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private void verifyPartitionKey(String partitionKey) { if (ImplUtils.isNullOrEmpty(partitionKey)) { return; } if (isPartitionSender) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with" + "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to " + "partition '%s'.", senderOptions.getPartitionId()))); } else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey, MAX_PARTITION_KEY_LENGTH))); } } /** * Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service. * @throws IOException if the underlying transport could not be closed and its resources could not be * disposed. */ @Override public void close() throws IOException { if (!isDisposed.getAndSet(true)) { final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout()); if (block != null) { block.close(); } } } /** * Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then * it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code * maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link * ErrorCondition */ private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>, List<EventDataBatch>> { private final String partitionKey; private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private volatile EventDataBatch currentBatch; EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.partitionKey = options.getPartitionKey(); this.contextProvider = contextProvider; currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider); } @Override public Supplier<List<EventDataBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<EventDataBatch>, EventData> accumulator() { return (list, event) -> { EventDataBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<EventDataBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() { return list -> { EventDataBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
Would suggest writing a test for this, too.
private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE); return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); final AtomicReference<Boolean> isFirst = new AtomicReference<>(true); return events.map(eventData -> { Context parentContext = eventData.getContext(); if (isFirst.get()) { Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider .startSpan(entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } isFirst.set(false); return setSpanContext(eventData, parentContext); }).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))) .doOnEach(signal -> { tracerProvider.endSpan(sendSpanContext.get(), signal); }); }); }
final AtomicReference<Boolean> isFirst = new AtomicReference<>(true);
private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE); return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); final AtomicReference<Boolean> isFirst = new AtomicReference<>(true); return events.map(eventData -> { Context parentContext = eventData.getContext(); if (isFirst.getAndSet(false)) { Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } return setSpanContext(eventData, parentContext); }).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))) .doOnEach(signal -> { tracerProvider.endSpan(sendSpanContext.get(), signal); }); }); }
class EventHubAsyncProducer implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions(); private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final EventHubProducerOptions senderOptions; private final Mono<AmqpSendLink> sendLinkMono; private final boolean isPartitionSender; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; /** * Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link * EventHubProducerOptions * otherwise, allows the service to load balance the messages amongst available partitions. */ EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.sendLinkMono = amqpSendLinkMono.cache(); this.senderOptions = options; this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId()); this.tracerProvider = tracerProvider; this.messageSerializer = messageSerializer; } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @param options A set of options used to configure the {@link EventDataBatch}. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch(BatchOptions options) { Objects.requireNonNull(options, "'options' cannot be null."); final BatchOptions clone = options.clone(); verifyPartitionKey(clone.getPartitionKey()); return sendLinkMono.flatMap(link -> link.getLinkSize() .flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (clone.getMaximumSizeInBytes() > maximumLinkSize) { return Mono.error(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).", clone.getMaximumSizeInBytes(), maximumLinkSize))); } final int batchSize = clone.getMaximumSizeInBytes() > 0 ? clone.getMaximumSizeInBytes() : maximumLinkSize; return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext)); })); } /** * Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size * allowed, an exception will be triggered and the send will fail. * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * * @param event Event to send to the service. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event) { Objects.requireNonNull(event, "'event' cannot be null."); return send(Flux.just(event)); } /** * Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds * the maximum size allowed, an exception will be triggered and the send will fail. * * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * @param event Event to send to the service. * @param options The set of options to consider when sending this event. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event, SendOptions options) { Objects.requireNonNull(event, "'event' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return send(Flux.just(event), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(Flux.fromIterable(events)); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'options' cannot be null."); return send(Flux.fromIterable(events), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(events, DEFAULT_SEND_OPTIONS); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'events' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return sendInternal(events, options); } /** * Sends the batch to the associated Event Hub. * * @param batch The batch to send to the service. * @return A {@link Mono} that completes when the batch is pushed to the service. * @throws NullPointerException if {@code batch} is {@code null}. * @see EventHubAsyncProducer * @see EventHubAsyncProducer */ public Mono<Void> send(EventDataBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); if (batch.getEvents().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) { logger.info("Sending batch with size[{}].", batch.getSize()); } else { logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey()); } final String partitionKey = batch.getPartitionKey(); final List<Message> messages = batch.getEvents().stream().map(event -> { final Message message = messageSerializer.serialize(event); if (!ImplUtils.isNullOrEmpty(partitionKey)) { final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey); message.setMessageAnnotations(messageAnnotations); } return message; }).collect(Collectors.toList()); return sendLinkMono.flatMap(link -> messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages)); } private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); verifyPartitionKey(partitionKey); if (tracerProvider.isEnabled()) { return sendInternalTracingEnabled(events, partitionKey); } else { return sendInternalTracingDisabled(events, partitionKey); } } private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))); }); } private EventData setSpanContext(EventData event, Context parentContext) { Optional<Object> eventContextData = event.getContext().getData(SPAN_CONTEXT); if (eventContextData.isPresent()) { Object spanContextObject = eventContextData.get(); if (spanContextObject instanceof Context) { tracerProvider.addSpanLinks((Context) eventContextData.get()); } else { logger.warning(String.format(Locale.US, "Event Data context type is not of type Context, but type: %s. Not adding span links.", spanContextObject != null ? spanContextObject.getClass() : "null")); } return event; } else { Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE); if (eventSpanContext != null) { Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { event.addProperty(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get().toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); event.addContext(SPAN_CONTEXT, eventSpanContext); } } } return event; } private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private void verifyPartitionKey(String partitionKey) { if (ImplUtils.isNullOrEmpty(partitionKey)) { return; } if (isPartitionSender) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with" + "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to " + "partition '%s'.", senderOptions.getPartitionId()))); } else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey, MAX_PARTITION_KEY_LENGTH))); } } /** * Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service. * @throws IOException if the underlying transport could not be closed and its resources could not be * disposed. */ @Override public void close() throws IOException { if (!isDisposed.getAndSet(true)) { final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout()); if (block != null) { block.close(); } } } /** * Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then * it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code * maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link * ErrorCondition */ private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>, List<EventDataBatch>> { private final String partitionKey; private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private volatile EventDataBatch currentBatch; EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.partitionKey = options.getPartitionKey(); this.contextProvider = contextProvider; currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider); } @Override public Supplier<List<EventDataBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<EventDataBatch>, EventData> accumulator() { return (list, event) -> { EventDataBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<EventDataBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() { return list -> { EventDataBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
class EventHubAsyncProducer implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions(); private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final EventHubProducerOptions senderOptions; private final Mono<AmqpSendLink> sendLinkMono; private final boolean isPartitionSender; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; /** * Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link * EventHubProducerOptions * otherwise, allows the service to load balance the messages amongst available partitions. */ EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.sendLinkMono = amqpSendLinkMono.cache(); this.senderOptions = options; this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId()); this.tracerProvider = tracerProvider; this.messageSerializer = messageSerializer; } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @param options A set of options used to configure the {@link EventDataBatch}. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch(BatchOptions options) { Objects.requireNonNull(options, "'options' cannot be null."); final BatchOptions clone = options.clone(); verifyPartitionKey(clone.getPartitionKey()); return sendLinkMono.flatMap(link -> link.getLinkSize() .flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (clone.getMaximumSizeInBytes() > maximumLinkSize) { return Mono.error(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).", clone.getMaximumSizeInBytes(), maximumLinkSize))); } final int batchSize = clone.getMaximumSizeInBytes() > 0 ? clone.getMaximumSizeInBytes() : maximumLinkSize; return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext)); })); } /** * Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size * allowed, an exception will be triggered and the send will fail. * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * * @param event Event to send to the service. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event) { Objects.requireNonNull(event, "'event' cannot be null."); return send(Flux.just(event)); } /** * Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds * the maximum size allowed, an exception will be triggered and the send will fail. * * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * @param event Event to send to the service. * @param options The set of options to consider when sending this event. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event, SendOptions options) { Objects.requireNonNull(event, "'event' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return send(Flux.just(event), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(Flux.fromIterable(events)); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'options' cannot be null."); return send(Flux.fromIterable(events), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(events, DEFAULT_SEND_OPTIONS); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'events' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return sendInternal(events, options); } /** * Sends the batch to the associated Event Hub. * * @param batch The batch to send to the service. * @return A {@link Mono} that completes when the batch is pushed to the service. * @throws NullPointerException if {@code batch} is {@code null}. * @see EventHubAsyncProducer * @see EventHubAsyncProducer */ public Mono<Void> send(EventDataBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); if (batch.getEvents().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) { logger.info("Sending batch with size[{}].", batch.getSize()); } else { logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey()); } final String partitionKey = batch.getPartitionKey(); final List<Message> messages = batch.getEvents().stream().map(event -> { final Message message = messageSerializer.serialize(event); if (!ImplUtils.isNullOrEmpty(partitionKey)) { final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey); message.setMessageAnnotations(messageAnnotations); } return message; }).collect(Collectors.toList()); return sendLinkMono.flatMap(link -> messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages)); } private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); verifyPartitionKey(partitionKey); if (tracerProvider.isEnabled()) { return sendInternalTracingEnabled(events, partitionKey); } else { return sendInternalTracingDisabled(events, partitionKey); } } private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))); }); } private EventData setSpanContext(EventData event, Context parentContext) { Optional<Object> eventContextData = event.getContext().getData(SPAN_CONTEXT); if (eventContextData.isPresent()) { Object spanContextObject = eventContextData.get(); if (spanContextObject instanceof Context) { tracerProvider.addSpanLinks((Context) eventContextData.get()); } else { logger.warning(String.format(Locale.US, "Event Data context type is not of type Context, but type: %s. Not adding span links.", spanContextObject != null ? spanContextObject.getClass() : "null")); } return event; } else { Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE); if (eventSpanContext != null) { Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { event.addProperty(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get().toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); event.addContext(SPAN_CONTEXT, eventSpanContext); } } } return event; } private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private void verifyPartitionKey(String partitionKey) { if (ImplUtils.isNullOrEmpty(partitionKey)) { return; } if (isPartitionSender) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with" + "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to " + "partition '%s'.", senderOptions.getPartitionId()))); } else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey, MAX_PARTITION_KEY_LENGTH))); } } /** * Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service. * @throws IOException if the underlying transport could not be closed and its resources could not be * disposed. */ @Override public void close() throws IOException { if (!isDisposed.getAndSet(true)) { final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout()); if (block != null) { block.close(); } } } /** * Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then * it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code * maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link * ErrorCondition */ private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>, List<EventDataBatch>> { private final String partitionKey; private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private volatile EventDataBatch currentBatch; EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.partitionKey = options.getPartitionKey(); this.contextProvider = contextProvider; currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider); } @Override public Supplier<List<EventDataBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<EventDataBatch>, EventData> accumulator() { return (list, event) -> { EventDataBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<EventDataBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() { return list -> { EventDataBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
updated, with the above code and fixed the already existing test cases for this.
private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE); return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); final AtomicReference<Boolean> isFirst = new AtomicReference<>(true); return events.map(eventData -> { Context parentContext = eventData.getContext(); if (isFirst.get()) { Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider .startSpan(entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } isFirst.set(false); return setSpanContext(eventData, parentContext); }).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))) .doOnEach(signal -> { tracerProvider.endSpan(sendSpanContext.get(), signal); }); }); }
final AtomicReference<Boolean> isFirst = new AtomicReference<>(true);
private Mono<Void> sendInternalTracingEnabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { final AtomicReference<Context> sendSpanContext = new AtomicReference<>(Context.NONE); return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); final AtomicReference<Boolean> isFirst = new AtomicReference<>(true); return events.map(eventData -> { Context parentContext = eventData.getContext(); if (isFirst.getAndSet(false)) { Context entityContext = parentContext.addData(ENTITY_PATH, link.getEntityPath()); sendSpanContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME, link.getHostname()), ProcessKind.SEND)); } return setSpanContext(eventData, parentContext); }).collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))) .doOnEach(signal -> { tracerProvider.endSpan(sendSpanContext.get(), signal); }); }); }
class EventHubAsyncProducer implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions(); private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final EventHubProducerOptions senderOptions; private final Mono<AmqpSendLink> sendLinkMono; private final boolean isPartitionSender; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; /** * Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link * EventHubProducerOptions * otherwise, allows the service to load balance the messages amongst available partitions. */ EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.sendLinkMono = amqpSendLinkMono.cache(); this.senderOptions = options; this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId()); this.tracerProvider = tracerProvider; this.messageSerializer = messageSerializer; } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @param options A set of options used to configure the {@link EventDataBatch}. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch(BatchOptions options) { Objects.requireNonNull(options, "'options' cannot be null."); final BatchOptions clone = options.clone(); verifyPartitionKey(clone.getPartitionKey()); return sendLinkMono.flatMap(link -> link.getLinkSize() .flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (clone.getMaximumSizeInBytes() > maximumLinkSize) { return Mono.error(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).", clone.getMaximumSizeInBytes(), maximumLinkSize))); } final int batchSize = clone.getMaximumSizeInBytes() > 0 ? clone.getMaximumSizeInBytes() : maximumLinkSize; return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext)); })); } /** * Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size * allowed, an exception will be triggered and the send will fail. * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * * @param event Event to send to the service. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event) { Objects.requireNonNull(event, "'event' cannot be null."); return send(Flux.just(event)); } /** * Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds * the maximum size allowed, an exception will be triggered and the send will fail. * * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * @param event Event to send to the service. * @param options The set of options to consider when sending this event. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event, SendOptions options) { Objects.requireNonNull(event, "'event' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return send(Flux.just(event), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(Flux.fromIterable(events)); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'options' cannot be null."); return send(Flux.fromIterable(events), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(events, DEFAULT_SEND_OPTIONS); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'events' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return sendInternal(events, options); } /** * Sends the batch to the associated Event Hub. * * @param batch The batch to send to the service. * @return A {@link Mono} that completes when the batch is pushed to the service. * @throws NullPointerException if {@code batch} is {@code null}. * @see EventHubAsyncProducer * @see EventHubAsyncProducer */ public Mono<Void> send(EventDataBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); if (batch.getEvents().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) { logger.info("Sending batch with size[{}].", batch.getSize()); } else { logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey()); } final String partitionKey = batch.getPartitionKey(); final List<Message> messages = batch.getEvents().stream().map(event -> { final Message message = messageSerializer.serialize(event); if (!ImplUtils.isNullOrEmpty(partitionKey)) { final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey); message.setMessageAnnotations(messageAnnotations); } return message; }).collect(Collectors.toList()); return sendLinkMono.flatMap(link -> messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages)); } private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); verifyPartitionKey(partitionKey); if (tracerProvider.isEnabled()) { return sendInternalTracingEnabled(events, partitionKey); } else { return sendInternalTracingDisabled(events, partitionKey); } } private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))); }); } private EventData setSpanContext(EventData event, Context parentContext) { Optional<Object> eventContextData = event.getContext().getData(SPAN_CONTEXT); if (eventContextData.isPresent()) { Object spanContextObject = eventContextData.get(); if (spanContextObject instanceof Context) { tracerProvider.addSpanLinks((Context) eventContextData.get()); } else { logger.warning(String.format(Locale.US, "Event Data context type is not of type Context, but type: %s. Not adding span links.", spanContextObject != null ? spanContextObject.getClass() : "null")); } return event; } else { Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE); if (eventSpanContext != null) { Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { event.addProperty(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get().toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); event.addContext(SPAN_CONTEXT, eventSpanContext); } } } return event; } private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private void verifyPartitionKey(String partitionKey) { if (ImplUtils.isNullOrEmpty(partitionKey)) { return; } if (isPartitionSender) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with" + "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to " + "partition '%s'.", senderOptions.getPartitionId()))); } else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey, MAX_PARTITION_KEY_LENGTH))); } } /** * Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service. * @throws IOException if the underlying transport could not be closed and its resources could not be * disposed. */ @Override public void close() throws IOException { if (!isDisposed.getAndSet(true)) { final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout()); if (block != null) { block.close(); } } } /** * Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then * it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code * maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link * ErrorCondition */ private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>, List<EventDataBatch>> { private final String partitionKey; private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private volatile EventDataBatch currentBatch; EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.partitionKey = options.getPartitionKey(); this.contextProvider = contextProvider; currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider); } @Override public Supplier<List<EventDataBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<EventDataBatch>, EventData> accumulator() { return (list, event) -> { EventDataBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<EventDataBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() { return list -> { EventDataBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
class EventHubAsyncProducer implements Closeable { private static final int MAX_PARTITION_KEY_LENGTH = 128; private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final BatchOptions DEFAULT_BATCH_OPTIONS = new BatchOptions(); private final ClientLogger logger = new ClientLogger(EventHubAsyncProducer.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final EventHubProducerOptions senderOptions; private final Mono<AmqpSendLink> sendLinkMono; private final boolean isPartitionSender; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; /** * Creates a new instance of this {@link EventHubAsyncProducer} that sends messages to {@link * EventHubProducerOptions * otherwise, allows the service to load balance the messages amongst available partitions. */ EventHubAsyncProducer(Mono<AmqpSendLink> amqpSendLinkMono, EventHubProducerOptions options, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.sendLinkMono = amqpSendLinkMono.cache(); this.senderOptions = options; this.isPartitionSender = !ImplUtils.isNullOrEmpty(options.getPartitionId()); this.tracerProvider = tracerProvider; this.messageSerializer = messageSerializer; } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link EventDataBatch} that can fit as many events as the transport allows. * @param options A set of options used to configure the {@link EventDataBatch}. * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. */ public Mono<EventDataBatch> createBatch(BatchOptions options) { Objects.requireNonNull(options, "'options' cannot be null."); final BatchOptions clone = options.clone(); verifyPartitionKey(clone.getPartitionKey()); return sendLinkMono.flatMap(link -> link.getLinkSize() .flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (clone.getMaximumSizeInBytes() > maximumLinkSize) { return Mono.error(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.maximumSizeInBytes (%s bytes) is larger than the link size (%s bytes).", clone.getMaximumSizeInBytes(), maximumLinkSize))); } final int batchSize = clone.getMaximumSizeInBytes() > 0 ? clone.getMaximumSizeInBytes() : maximumLinkSize; return Mono.just(new EventDataBatch(batchSize, clone.getPartitionKey(), link::getErrorContext)); })); } /** * Sends a single event to the associated Event Hub. If the size of the single event exceeds the maximum size * allowed, an exception will be triggered and the send will fail. * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * * @param event Event to send to the service. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event) { Objects.requireNonNull(event, "'event' cannot be null."); return send(Flux.just(event)); } /** * Sends a single event to the associated Event Hub with the send options. If the size of the single event exceeds * the maximum size allowed, an exception will be triggered and the send will fail. * * <p> * For more information regarding the maximum event size allowed, see * <a href="https: * Limits</a>. * </p> * @param event Event to send to the service. * @param options The set of options to consider when sending this event. * * @return A {@link Mono} that completes when the event is pushed to the service. */ public Mono<Void> send(EventData event, SendOptions options) { Objects.requireNonNull(event, "'event' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return send(Flux.just(event), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(Flux.fromIterable(events)); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Iterable<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'options' cannot be null."); return send(Flux.fromIterable(events), options); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events) { Objects.requireNonNull(events, "'events' cannot be null."); return send(events, DEFAULT_SEND_OPTIONS); } /** * Sends a set of events to the associated Event Hub using a batched approach. If the size of events exceed the * maximum size of a single batch, an exception will be triggered and the send will fail. By default, the message * size is the max amount allowed on the link. * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. * @return A {@link Mono} that completes when all events are pushed to the service. */ public Mono<Void> send(Flux<EventData> events, SendOptions options) { Objects.requireNonNull(events, "'events' cannot be null."); Objects.requireNonNull(options, "'options' cannot be null."); return sendInternal(events, options); } /** * Sends the batch to the associated Event Hub. * * @param batch The batch to send to the service. * @return A {@link Mono} that completes when the batch is pushed to the service. * @throws NullPointerException if {@code batch} is {@code null}. * @see EventHubAsyncProducer * @see EventHubAsyncProducer */ public Mono<Void> send(EventDataBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); if (batch.getEvents().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } if (ImplUtils.isNullOrEmpty(batch.getPartitionKey())) { logger.info("Sending batch with size[{}].", batch.getSize()); } else { logger.info("Sending batch with size[{}], partitionKey[{}].", batch.getSize(), batch.getPartitionKey()); } final String partitionKey = batch.getPartitionKey(); final List<Message> messages = batch.getEvents().stream().map(event -> { final Message message = messageSerializer.serialize(event); if (!ImplUtils.isNullOrEmpty(partitionKey)) { final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); messageAnnotations.getValue().put(AmqpConstants.PARTITION_KEY, partitionKey); message.setMessageAnnotations(messageAnnotations); } return message; }).collect(Collectors.toList()); return sendLinkMono.flatMap(link -> messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages)); } private Mono<Void> sendInternal(Flux<EventData> events, SendOptions options) { final String partitionKey = options.getPartitionKey(); verifyPartitionKey(partitionKey); if (tracerProvider.isEnabled()) { return sendInternalTracingEnabled(events, partitionKey); } else { return sendInternalTracingDisabled(events, partitionKey); } } private Mono<Void> sendInternalTracingDisabled(Flux<EventData> events, String partitionKey) { return sendLinkMono.flatMap(link -> { return link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final BatchOptions batchOptions = new BatchOptions() .setPartitionKey(partitionKey) .setMaximumSizeInBytes(batchSize); return events.collect(new EventDataCollector(batchOptions, 1, link::getErrorContext)); }) .flatMap(list -> sendInternal(Flux.fromIterable(list))); }); } private EventData setSpanContext(EventData event, Context parentContext) { Optional<Object> eventContextData = event.getContext().getData(SPAN_CONTEXT); if (eventContextData.isPresent()) { Object spanContextObject = eventContextData.get(); if (spanContextObject instanceof Context) { tracerProvider.addSpanLinks((Context) eventContextData.get()); } else { logger.warning(String.format(Locale.US, "Event Data context type is not of type Context, but type: %s. Not adding span links.", spanContextObject != null ? spanContextObject.getClass() : "null")); } return event; } else { Context eventSpanContext = tracerProvider.startSpan(parentContext, ProcessKind.RECEIVE); if (eventSpanContext != null) { Optional<Object> eventDiagnosticIdOptional = eventSpanContext.getData(DIAGNOSTIC_ID_KEY); if (eventDiagnosticIdOptional.isPresent()) { event.addProperty(DIAGNOSTIC_ID_KEY, eventDiagnosticIdOptional.get().toString()); tracerProvider.endSpan(eventSpanContext, Signal.complete()); event.addContext(SPAN_CONTEXT, eventSpanContext); } } } return event; } private Mono<Void> sendInternal(Flux<EventDataBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private void verifyPartitionKey(String partitionKey) { if (ImplUtils.isNullOrEmpty(partitionKey)) { return; } if (isPartitionSender) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "BatchOptions.partitionKey() cannot be set when an EventHubProducer is created with" + "EventHubProducerOptions.partitionId() set. This EventHubProducer can only send events to " + "partition '%s'.", senderOptions.getPartitionId()))); } else if (partitionKey.length() > MAX_PARTITION_KEY_LENGTH) { throw logger.logExceptionAsError(new IllegalArgumentException(String.format(Locale.US, "PartitionKey '%s' exceeds the maximum allowed length: '%s'.", partitionKey, MAX_PARTITION_KEY_LENGTH))); } } /** * Disposes of the {@link EventHubAsyncProducer} by closing the underlying connection to the service. * @throws IOException if the underlying transport could not be closed and its resources could not be * disposed. */ @Override public void close() throws IOException { if (!isDisposed.getAndSet(true)) { final AmqpSendLink block = sendLinkMono.block(senderOptions.getRetry().getTryTimeout()); if (block != null) { block.close(); } } } /** * Collects EventData into EventDataBatch to send to Event Hubs. If {@code maxNumberOfBatches} is {@code null} then * it'll collect as many batches as possible. Otherwise, if there are more events than can fit into {@code * maxNumberOfBatches}, then the collector throws a {@link AmqpException} with {@link * ErrorCondition */ private static class EventDataCollector implements Collector<EventData, List<EventDataBatch>, List<EventDataBatch>> { private final String partitionKey; private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private volatile EventDataBatch currentBatch; EventDataCollector(BatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.partitionKey = options.getPartitionKey(); this.contextProvider = contextProvider; currentBatch = new EventDataBatch(this.maxMessageSize, options.getPartitionKey(), contextProvider); } @Override public Supplier<List<EventDataBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<EventDataBatch>, EventData> accumulator() { return (list, event) -> { EventDataBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, ErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new EventDataBatch(maxMessageSize, partitionKey, contextProvider); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<EventDataBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<EventDataBatch>, List<EventDataBatch>> finisher() { return list -> { EventDataBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
The `assertInBounds` is throwing an exception https://github.com/Azure/azure-sdk-for-java/blob/fec0fa1d35e7b13654815d927a338746e7582b9a/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/Utility.java#L300 but we're not logging it
private void validateFilePermissionAndKey(String filePermission, String filePermissionKey) { if (filePermission != null && filePermissionKey != null) { throw logger.logExceptionAsError(new IllegalArgumentException( FileConstants.MessageConstants.FILE_PERMISSION_FILE_PERMISSION_KEY_INVALID)); } if (filePermission != null) { Utility.assertInBounds("filePermission", filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB); } }
filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB);
private void validateFilePermissionAndKey(String filePermission, String filePermissionKey) { if (filePermission != null && filePermissionKey != null) { throw logger.logExceptionAsError(new IllegalArgumentException( FileConstants.MessageConstants.FILE_PERMISSION_FILE_PERMISSION_KEY_INVALID)); } if (filePermission != null) { Utility.assertInBounds("filePermission", filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB); } }
class FileAsyncClient { private final ClientLogger logger = new ClientLogger(FileAsyncClient.class); private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L; private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300; private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String filePath; private final String snapshot; private final String accountName; /** * Creates a FileAsyncClient that sends requests to the storage file at {@link AzureFileStorageImpl * endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the {@code client}. * * @param azureFileStorageClient Client that interacts with the service interfaces * @param shareName Name of the share * @param filePath Path to the file * @param snapshot The snapshot of the share */ FileAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String filePath, String snapshot, String accountName) { Objects.requireNonNull(shareName, "'shareName' cannot be null."); Objects.requireNonNull(filePath, "'filePath' cannot be null."); this.shareName = shareName; this.filePath = filePath; this.snapshot = snapshot; this.azureFileStorageClient = azureFileStorageClient; this.accountName = accountName; } /** * Get the url of the storage file client. * * @return the URL of the storage file client */ public String getFileUrl() { StringBuilder fileUrlstring = new StringBuilder(azureFileStorageClient.getUrl()).append("/") .append(shareName).append("/").append(filePath); if (snapshot != null) { fileUrlstring.append("?snapshot=").append(snapshot); } return fileUrlstring.toString(); } /** * Creates a file in the storage account and returns a response of {@link FileInfo} to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with size 1KB.</p> * * {@codesnippet com.azure.storage.file.fileClient.create} * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @return A response containing the file info and the status of creating the file. * @throws StorageException If the file has already existed, the parent directory does not exist or fileName is an * invalid resource name. */ public Mono<FileInfo> create(long maxSize) { return createWithResponse(maxSize, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Creates a file in the storage account and returns a response of FileInfo to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with length of 1024 bytes, some headers, file smb properties and metadata.</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.createWithResponse * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @param metadata Optional name-value pairs associated with the file as metadata. * @return A response containing the {@link FileInfo file info} and the status of creating the file. * @throws StorageException If the directory has already existed, the parent directory does not exist or directory * is an invalid resource name. */ public Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata) { return withContext(context -> createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, metadata, context)); } Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); return postProcessResponse(azureFileStorageClient.files() .createWithRestResponseAsync(shareName, filePath, maxSize, fileAttributes, fileCreationTime, fileLastWriteTime, null, metadata, filePermission, filePermissionKey, httpHeaders, context)) .map(this::createFileInfoResponse); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return The {@link FileCopyInfo file copy info}. * @see <a href="https: */ public Mono<FileCopyInfo> startCopy(String sourceUrl, Map<String, String> metadata) { return startCopyWithResponse(sourceUrl, metadata).flatMap(FluxUtil::toMono); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return A response containing the {@link FileCopyInfo file copy info} and the status of copying the file. * @see <a href="https: */ public Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata) { return withContext(context -> startCopyWithResponse(sourceUrl, metadata, context)); } Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .startCopyWithRestResponseAsync(shareName, filePath, sourceUrl, null, metadata, context)) .map(this::startCopyResponse); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopy * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return An empty response. */ public Mono<Void> abortCopy(String copyId) { return abortCopyWithResponse(copyId).flatMap(FluxUtil::toMono); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return A response containing the status of aborting copy the file. */ public Mono<Response<Void>> abortCopyWithResponse(String copyId) { return withContext(context -> abortCopyWithResponse(copyId, context)); } Mono<Response<Void>> abortCopyWithResponse(String copyId, Context context) { return postProcessResponse(azureFileStorageClient.files() .abortCopyWithRestResponseAsync(shareName, filePath, copyId, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFile * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @return An empty response. */ public Mono<FileProperties> downloadToFile(String downloadFilePath) { return downloadToFileWithResponse(downloadFilePath, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @param range Optional byte range which returns file data only from the specified range. * @return An empty response. */ public Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range) { return withContext(context -> downloadToFileWithResponse(downloadFilePath, range, context)); } Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range, Context context) { return Mono.using(() -> channelSetup(downloadFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW), channel -> getPropertiesWithResponse(context).flatMap(response -> downloadResponseInChunk(response, channel, range, context)), this::channelCleanUp); } private Mono<Response<FileProperties>> downloadResponseInChunk(Response<FileProperties> response, AsynchronousFileChannel channel, FileRange range, Context context) { return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new FileRange(0, response.getValue() .getContentLength()))) .map(currentRange -> { List<FileRange> chunks = new ArrayList<>(); for (long pos = currentRange.getStart(); pos < currentRange.getEnd(); pos += FILE_DEFAULT_BLOCK_SIZE) { long count = FILE_DEFAULT_BLOCK_SIZE; if (pos + count > currentRange.getEnd()) { count = currentRange.getEnd() - pos; } chunks.add(new FileRange(pos, pos + count - 1)); } return chunks; }).flatMapMany(Flux::fromIterable).flatMap(chunk -> downloadWithPropertiesWithResponse(chunk, false, context) .map(dar -> dar.getValue().getBody()) .subscribeOn(Schedulers.elastic()) .flatMap(fbb -> FluxUtil .writeFile(fbb, channel, chunk.getStart() - (range == null ? 0 : range.getStart())) .subscribeOn(Schedulers.elastic()) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException))) .then(Mono.just(response)); } private AsynchronousFileChannel channelSetup(String filePath, OpenOption... options) { try { return AsynchronousFileChannel.open(Paths.get(filePath), options); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private void channelCleanUp(AsynchronousFileChannel channel) { try { channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(e))); } } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file with its metadata and properties. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithProperties} * * <p>For more information, see the * <a href="https: * * @return The {@link FileDownloadInfo file download Info} */ public Mono<FileDownloadInfo> downloadWithProperties() { return downloadWithPropertiesWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param range Optional byte range which returns file data only from the specified range. * @param rangeGetContentMD5 Optional boolean which the service returns the MD5 hash for the range when it sets to * true, as long as the range is less than or equal to 4 MB in size. * @return A response containing the {@link FileDownloadInfo file download Info} with headers and response status * code */ public Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5) { return withContext(context -> downloadWithPropertiesWithResponse(range, rangeGetContentMD5, context)); } Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5, Context context) { String rangeString = range == null ? null : range.toString(); return postProcessResponse(azureFileStorageClient.files() .downloadWithRestResponseAsync(shareName, filePath, null, rangeString, rangeGetContentMD5, context)) .map(this::downloadWithPropertiesResponse); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.delete} * * <p>For more information, see the * <a href="https: * * @return An empty response * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Void> delete() { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.deleteWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response that only contains headers and response status code * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Response<Void>> deleteWithResponse() { return withContext(this::deleteWithResponse); } Mono<Response<Void>> deleteWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .deleteWithRestResponseAsync(shareName, filePath, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getProperties} * * <p>For more information, see the * <a href="https: * * @return {@link FileProperties Storage file properties} */ public Mono<FileProperties> getProperties() { return getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getPropertiesWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response containing the {@link FileProperties storage file properties} and response status code */ public Mono<Response<FileProperties>> getPropertiesWithResponse() { return withContext(this::getPropertiesWithResponse); } Mono<Response<FileProperties>> getPropertiesWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .getPropertiesWithRestResponseAsync(shareName, filePath, snapshot, null, context)) .map(this::getPropertiesResponse); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the fileProperties.httpHeaders it will clear the httpHeaders associated to the * file. * If {@code null} is passed for the fileProperties.filesmbproperties it will preserve the filesmb properties * associated with the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file * @return The {@link FileInfo file info} * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<FileInfo> setProperties(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission) .flatMap(FluxUtil::toMono); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the httpHeaders it will clear the httpHeaders associated to the file. * If {@code null} is passed for the filesmbproperties it will preserve the filesmbproperties associated with the * file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @return Response containing the {@link FileInfo file info} and response status code. * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return withContext(context -> setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission, context)); } Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); return postProcessResponse(azureFileStorageClient.files() .setHTTPHeadersWithRestResponseAsync(shareName, filePath, fileAttributes, fileCreationTime, fileLastWriteTime, null, newFileSize, filePermission, filePermissionKey, httpHeaders, context)) .map(this::setPropertiesResponse); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadata * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return {@link FileMetadataInfo file meta info} * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<FileMetadataInfo> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return A response containing the {@link FileMetadataInfo file meta info} and status code * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata) { return withContext(context -> setMetadataWithResponse(metadata, context)); } Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .setMetadataWithRestResponseAsync(shareName, filePath, null, metadata, context)) .map(this::setMetadataResponse); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" to the file in Storage File Service. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @return A response that only contains headers and response status code */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length) { return uploadWithResponse(data, length).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload "default" to the file. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero.. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length) { return withContext(context -> uploadWithResponse(data, length, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, Context context) { FileRange range = new FileRange(0, length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" starting from 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return The {@link FileUploadInfo file upload info} * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length, long offset) { return uploadWithResponse(data, length, offset).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset) { return withContext(context -> uploadWithResponse(data, length, offset, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrl * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return The {@link FileUploadRangeFromUrlInfo file upload range from url info} */ public Mono<FileUploadRangeFromUrlInfo> uploadRangeFromUrl(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI) .flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return A response containing the {@link FileUploadRangeFromUrlInfo file upload range from url info} with headers * and response status code. */ public Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return withContext(context -> uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI, context)); } Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI, Context context) { FileRange destinationRange = new FileRange(destinationOffset, destinationOffset + length - 1); FileRange sourceRange = new FileRange(sourceOffset, sourceOffset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeFromURLWithRestResponseAsync(shareName, filePath, destinationRange.toString(), sourceURI.toString(), 0, null, sourceRange.toString(), null, null, context)) .map(this::uploadRangeFromUrlResponse); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clears the first 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared. * @return The {@link FileUploadInfo file upload info} */ public Mono<FileUploadInfo> clearRange(long length) { return clearRangeWithResponse(length, 0).flatMap(FluxUtil::toMono); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clear the range starting from 1024 with length of 1024. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return A response of {@link FileUploadInfo file upload info} that only contains headers and response status code */ public Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset) { return withContext(context -> clearRangeWithResponse(length, offset, context)); } Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, context)) .map(this::uploadResponse); } /** * Uploads file to storage file service. * * <p><strong>Code Samples</strong></p> * * <p> Upload the file from the source file path. </p> * * (@codesnippet com.azure.storage.file.fileAsyncClient.uploadFromFile
class FileAsyncClient { private final ClientLogger logger = new ClientLogger(FileAsyncClient.class); private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L; private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300; private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String filePath; private final String snapshot; private final String accountName; /** * Creates a FileAsyncClient that sends requests to the storage file at {@link AzureFileStorageImpl * endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the {@code client}. * * @param azureFileStorageClient Client that interacts with the service interfaces * @param shareName Name of the share * @param filePath Path to the file * @param snapshot The snapshot of the share */ FileAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String filePath, String snapshot, String accountName) { Objects.requireNonNull(shareName, "'shareName' cannot be null."); Objects.requireNonNull(filePath, "'filePath' cannot be null."); this.shareName = shareName; this.filePath = filePath; this.snapshot = snapshot; this.azureFileStorageClient = azureFileStorageClient; this.accountName = accountName; } /** * Get the url of the storage file client. * * @return the URL of the storage file client */ public String getFileUrl() { StringBuilder fileUrlstring = new StringBuilder(azureFileStorageClient.getUrl()).append("/") .append(shareName).append("/").append(filePath); if (snapshot != null) { fileUrlstring.append("?snapshot=").append(snapshot); } return fileUrlstring.toString(); } /** * Creates a file in the storage account and returns a response of {@link FileInfo} to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with size 1KB.</p> * * {@codesnippet com.azure.storage.file.fileClient.create} * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @return A response containing the file info and the status of creating the file. * @throws StorageException If the file has already existed, the parent directory does not exist or fileName is an * invalid resource name. */ public Mono<FileInfo> create(long maxSize) { return createWithResponse(maxSize, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Creates a file in the storage account and returns a response of FileInfo to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with length of 1024 bytes, some headers, file smb properties and metadata.</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.createWithResponse * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @param metadata Optional name-value pairs associated with the file as metadata. * @return A response containing the {@link FileInfo file info} and the status of creating the file. * @throws StorageException If the directory has already existed, the parent directory does not exist or directory * is an invalid resource name. */ public Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata) { return withContext(context -> createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, metadata, context)); } Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); return postProcessResponse(azureFileStorageClient.files() .createWithRestResponseAsync(shareName, filePath, maxSize, fileAttributes, fileCreationTime, fileLastWriteTime, null, metadata, filePermission, filePermissionKey, httpHeaders, context)) .map(this::createFileInfoResponse); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return The {@link FileCopyInfo file copy info}. * @see <a href="https: */ public Mono<FileCopyInfo> startCopy(String sourceUrl, Map<String, String> metadata) { return startCopyWithResponse(sourceUrl, metadata).flatMap(FluxUtil::toMono); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return A response containing the {@link FileCopyInfo file copy info} and the status of copying the file. * @see <a href="https: */ public Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata) { return withContext(context -> startCopyWithResponse(sourceUrl, metadata, context)); } Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .startCopyWithRestResponseAsync(shareName, filePath, sourceUrl, null, metadata, context)) .map(this::startCopyResponse); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopy * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return An empty response. */ public Mono<Void> abortCopy(String copyId) { return abortCopyWithResponse(copyId).flatMap(FluxUtil::toMono); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return A response containing the status of aborting copy the file. */ public Mono<Response<Void>> abortCopyWithResponse(String copyId) { return withContext(context -> abortCopyWithResponse(copyId, context)); } Mono<Response<Void>> abortCopyWithResponse(String copyId, Context context) { return postProcessResponse(azureFileStorageClient.files() .abortCopyWithRestResponseAsync(shareName, filePath, copyId, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFile * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @return An empty response. */ public Mono<FileProperties> downloadToFile(String downloadFilePath) { return downloadToFileWithResponse(downloadFilePath, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @param range Optional byte range which returns file data only from the specified range. * @return An empty response. */ public Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range) { return withContext(context -> downloadToFileWithResponse(downloadFilePath, range, context)); } Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range, Context context) { return Mono.using(() -> channelSetup(downloadFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW), channel -> getPropertiesWithResponse(context).flatMap(response -> downloadResponseInChunk(response, channel, range, context)), this::channelCleanUp); } private Mono<Response<FileProperties>> downloadResponseInChunk(Response<FileProperties> response, AsynchronousFileChannel channel, FileRange range, Context context) { return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new FileRange(0, response.getValue() .getContentLength()))) .map(currentRange -> { List<FileRange> chunks = new ArrayList<>(); for (long pos = currentRange.getStart(); pos < currentRange.getEnd(); pos += FILE_DEFAULT_BLOCK_SIZE) { long count = FILE_DEFAULT_BLOCK_SIZE; if (pos + count > currentRange.getEnd()) { count = currentRange.getEnd() - pos; } chunks.add(new FileRange(pos, pos + count - 1)); } return chunks; }).flatMapMany(Flux::fromIterable).flatMap(chunk -> downloadWithPropertiesWithResponse(chunk, false, context) .map(dar -> dar.getValue().getBody()) .subscribeOn(Schedulers.elastic()) .flatMap(fbb -> FluxUtil .writeFile(fbb, channel, chunk.getStart() - (range == null ? 0 : range.getStart())) .subscribeOn(Schedulers.elastic()) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException))) .then(Mono.just(response)); } private AsynchronousFileChannel channelSetup(String filePath, OpenOption... options) { try { return AsynchronousFileChannel.open(Paths.get(filePath), options); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private void channelCleanUp(AsynchronousFileChannel channel) { try { channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(e))); } } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file with its metadata and properties. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithProperties} * * <p>For more information, see the * <a href="https: * * @return The {@link FileDownloadInfo file download Info} */ public Mono<FileDownloadInfo> downloadWithProperties() { return downloadWithPropertiesWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param range Optional byte range which returns file data only from the specified range. * @param rangeGetContentMD5 Optional boolean which the service returns the MD5 hash for the range when it sets to * true, as long as the range is less than or equal to 4 MB in size. * @return A response containing the {@link FileDownloadInfo file download Info} with headers and response status * code */ public Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5) { return withContext(context -> downloadWithPropertiesWithResponse(range, rangeGetContentMD5, context)); } Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5, Context context) { String rangeString = range == null ? null : range.toString(); return postProcessResponse(azureFileStorageClient.files() .downloadWithRestResponseAsync(shareName, filePath, null, rangeString, rangeGetContentMD5, context)) .map(this::downloadWithPropertiesResponse); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.delete} * * <p>For more information, see the * <a href="https: * * @return An empty response * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Void> delete() { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.deleteWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response that only contains headers and response status code * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Response<Void>> deleteWithResponse() { return withContext(this::deleteWithResponse); } Mono<Response<Void>> deleteWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .deleteWithRestResponseAsync(shareName, filePath, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getProperties} * * <p>For more information, see the * <a href="https: * * @return {@link FileProperties Storage file properties} */ public Mono<FileProperties> getProperties() { return getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getPropertiesWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response containing the {@link FileProperties storage file properties} and response status code */ public Mono<Response<FileProperties>> getPropertiesWithResponse() { return withContext(this::getPropertiesWithResponse); } Mono<Response<FileProperties>> getPropertiesWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .getPropertiesWithRestResponseAsync(shareName, filePath, snapshot, null, context)) .map(this::getPropertiesResponse); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the fileProperties.httpHeaders it will clear the httpHeaders associated to the * file. * If {@code null} is passed for the fileProperties.filesmbproperties it will preserve the filesmb properties * associated with the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file * @return The {@link FileInfo file info} * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<FileInfo> setProperties(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission) .flatMap(FluxUtil::toMono); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the httpHeaders it will clear the httpHeaders associated to the file. * If {@code null} is passed for the filesmbproperties it will preserve the filesmbproperties associated with the * file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @return Response containing the {@link FileInfo file info} and response status code. * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return withContext(context -> setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission, context)); } Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); return postProcessResponse(azureFileStorageClient.files() .setHTTPHeadersWithRestResponseAsync(shareName, filePath, fileAttributes, fileCreationTime, fileLastWriteTime, null, newFileSize, filePermission, filePermissionKey, httpHeaders, context)) .map(this::setPropertiesResponse); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadata * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return {@link FileMetadataInfo file meta info} * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<FileMetadataInfo> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return A response containing the {@link FileMetadataInfo file meta info} and status code * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata) { return withContext(context -> setMetadataWithResponse(metadata, context)); } Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .setMetadataWithRestResponseAsync(shareName, filePath, null, metadata, context)) .map(this::setMetadataResponse); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" to the file in Storage File Service. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @return A response that only contains headers and response status code */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length) { return uploadWithResponse(data, length).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload "default" to the file. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero.. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length) { return withContext(context -> uploadWithResponse(data, length, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, Context context) { FileRange range = new FileRange(0, length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" starting from 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return The {@link FileUploadInfo file upload info} * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length, long offset) { return uploadWithResponse(data, length, offset).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset) { return withContext(context -> uploadWithResponse(data, length, offset, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrl * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return The {@link FileUploadRangeFromUrlInfo file upload range from url info} */ public Mono<FileUploadRangeFromUrlInfo> uploadRangeFromUrl(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI) .flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return A response containing the {@link FileUploadRangeFromUrlInfo file upload range from url info} with headers * and response status code. */ public Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return withContext(context -> uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI, context)); } Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI, Context context) { FileRange destinationRange = new FileRange(destinationOffset, destinationOffset + length - 1); FileRange sourceRange = new FileRange(sourceOffset, sourceOffset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeFromURLWithRestResponseAsync(shareName, filePath, destinationRange.toString(), sourceURI.toString(), 0, null, sourceRange.toString(), null, null, context)) .map(this::uploadRangeFromUrlResponse); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clears the first 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared. * @return The {@link FileUploadInfo file upload info} */ public Mono<FileUploadInfo> clearRange(long length) { return clearRangeWithResponse(length, 0).flatMap(FluxUtil::toMono); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clear the range starting from 1024 with length of 1024. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return A response of {@link FileUploadInfo file upload info} that only contains headers and response status code */ public Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset) { return withContext(context -> clearRangeWithResponse(length, offset, context)); } Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, context)) .map(this::uploadResponse); } /** * Uploads file to storage file service. * * <p><strong>Code Samples</strong></p> * * <p> Upload the file from the source file path. </p> * * (@codesnippet com.azure.storage.file.fileAsyncClient.uploadFromFile
@sima-zhu since this is not a release blocker we can track this separately if you think so.
private void validateFilePermissionAndKey(String filePermission, String filePermissionKey) { if (filePermission != null && filePermissionKey != null) { throw logger.logExceptionAsError(new IllegalArgumentException( FileConstants.MessageConstants.FILE_PERMISSION_FILE_PERMISSION_KEY_INVALID)); } if (filePermission != null) { Utility.assertInBounds("filePermission", filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB); } }
filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB);
private void validateFilePermissionAndKey(String filePermission, String filePermissionKey) { if (filePermission != null && filePermissionKey != null) { throw logger.logExceptionAsError(new IllegalArgumentException( FileConstants.MessageConstants.FILE_PERMISSION_FILE_PERMISSION_KEY_INVALID)); } if (filePermission != null) { Utility.assertInBounds("filePermission", filePermission.getBytes(StandardCharsets.UTF_8).length, 0, 8 * Constants.KB); } }
class FileAsyncClient { private final ClientLogger logger = new ClientLogger(FileAsyncClient.class); private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L; private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300; private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String filePath; private final String snapshot; private final String accountName; /** * Creates a FileAsyncClient that sends requests to the storage file at {@link AzureFileStorageImpl * endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the {@code client}. * * @param azureFileStorageClient Client that interacts with the service interfaces * @param shareName Name of the share * @param filePath Path to the file * @param snapshot The snapshot of the share */ FileAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String filePath, String snapshot, String accountName) { Objects.requireNonNull(shareName, "'shareName' cannot be null."); Objects.requireNonNull(filePath, "'filePath' cannot be null."); this.shareName = shareName; this.filePath = filePath; this.snapshot = snapshot; this.azureFileStorageClient = azureFileStorageClient; this.accountName = accountName; } /** * Get the url of the storage file client. * * @return the URL of the storage file client */ public String getFileUrl() { StringBuilder fileUrlstring = new StringBuilder(azureFileStorageClient.getUrl()).append("/") .append(shareName).append("/").append(filePath); if (snapshot != null) { fileUrlstring.append("?snapshot=").append(snapshot); } return fileUrlstring.toString(); } /** * Creates a file in the storage account and returns a response of {@link FileInfo} to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with size 1KB.</p> * * {@codesnippet com.azure.storage.file.fileClient.create} * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @return A response containing the file info and the status of creating the file. * @throws StorageException If the file has already existed, the parent directory does not exist or fileName is an * invalid resource name. */ public Mono<FileInfo> create(long maxSize) { return createWithResponse(maxSize, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Creates a file in the storage account and returns a response of FileInfo to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with length of 1024 bytes, some headers, file smb properties and metadata.</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.createWithResponse * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @param metadata Optional name-value pairs associated with the file as metadata. * @return A response containing the {@link FileInfo file info} and the status of creating the file. * @throws StorageException If the directory has already existed, the parent directory does not exist or directory * is an invalid resource name. */ public Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata) { return withContext(context -> createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, metadata, context)); } Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); return postProcessResponse(azureFileStorageClient.files() .createWithRestResponseAsync(shareName, filePath, maxSize, fileAttributes, fileCreationTime, fileLastWriteTime, null, metadata, filePermission, filePermissionKey, httpHeaders, context)) .map(this::createFileInfoResponse); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return The {@link FileCopyInfo file copy info}. * @see <a href="https: */ public Mono<FileCopyInfo> startCopy(String sourceUrl, Map<String, String> metadata) { return startCopyWithResponse(sourceUrl, metadata).flatMap(FluxUtil::toMono); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return A response containing the {@link FileCopyInfo file copy info} and the status of copying the file. * @see <a href="https: */ public Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata) { return withContext(context -> startCopyWithResponse(sourceUrl, metadata, context)); } Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .startCopyWithRestResponseAsync(shareName, filePath, sourceUrl, null, metadata, context)) .map(this::startCopyResponse); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopy * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return An empty response. */ public Mono<Void> abortCopy(String copyId) { return abortCopyWithResponse(copyId).flatMap(FluxUtil::toMono); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return A response containing the status of aborting copy the file. */ public Mono<Response<Void>> abortCopyWithResponse(String copyId) { return withContext(context -> abortCopyWithResponse(copyId, context)); } Mono<Response<Void>> abortCopyWithResponse(String copyId, Context context) { return postProcessResponse(azureFileStorageClient.files() .abortCopyWithRestResponseAsync(shareName, filePath, copyId, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFile * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @return An empty response. */ public Mono<FileProperties> downloadToFile(String downloadFilePath) { return downloadToFileWithResponse(downloadFilePath, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @param range Optional byte range which returns file data only from the specified range. * @return An empty response. */ public Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range) { return withContext(context -> downloadToFileWithResponse(downloadFilePath, range, context)); } Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range, Context context) { return Mono.using(() -> channelSetup(downloadFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW), channel -> getPropertiesWithResponse(context).flatMap(response -> downloadResponseInChunk(response, channel, range, context)), this::channelCleanUp); } private Mono<Response<FileProperties>> downloadResponseInChunk(Response<FileProperties> response, AsynchronousFileChannel channel, FileRange range, Context context) { return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new FileRange(0, response.getValue() .getContentLength()))) .map(currentRange -> { List<FileRange> chunks = new ArrayList<>(); for (long pos = currentRange.getStart(); pos < currentRange.getEnd(); pos += FILE_DEFAULT_BLOCK_SIZE) { long count = FILE_DEFAULT_BLOCK_SIZE; if (pos + count > currentRange.getEnd()) { count = currentRange.getEnd() - pos; } chunks.add(new FileRange(pos, pos + count - 1)); } return chunks; }).flatMapMany(Flux::fromIterable).flatMap(chunk -> downloadWithPropertiesWithResponse(chunk, false, context) .map(dar -> dar.getValue().getBody()) .subscribeOn(Schedulers.elastic()) .flatMap(fbb -> FluxUtil .writeFile(fbb, channel, chunk.getStart() - (range == null ? 0 : range.getStart())) .subscribeOn(Schedulers.elastic()) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException))) .then(Mono.just(response)); } private AsynchronousFileChannel channelSetup(String filePath, OpenOption... options) { try { return AsynchronousFileChannel.open(Paths.get(filePath), options); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private void channelCleanUp(AsynchronousFileChannel channel) { try { channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(e))); } } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file with its metadata and properties. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithProperties} * * <p>For more information, see the * <a href="https: * * @return The {@link FileDownloadInfo file download Info} */ public Mono<FileDownloadInfo> downloadWithProperties() { return downloadWithPropertiesWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param range Optional byte range which returns file data only from the specified range. * @param rangeGetContentMD5 Optional boolean which the service returns the MD5 hash for the range when it sets to * true, as long as the range is less than or equal to 4 MB in size. * @return A response containing the {@link FileDownloadInfo file download Info} with headers and response status * code */ public Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5) { return withContext(context -> downloadWithPropertiesWithResponse(range, rangeGetContentMD5, context)); } Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5, Context context) { String rangeString = range == null ? null : range.toString(); return postProcessResponse(azureFileStorageClient.files() .downloadWithRestResponseAsync(shareName, filePath, null, rangeString, rangeGetContentMD5, context)) .map(this::downloadWithPropertiesResponse); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.delete} * * <p>For more information, see the * <a href="https: * * @return An empty response * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Void> delete() { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.deleteWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response that only contains headers and response status code * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Response<Void>> deleteWithResponse() { return withContext(this::deleteWithResponse); } Mono<Response<Void>> deleteWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .deleteWithRestResponseAsync(shareName, filePath, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getProperties} * * <p>For more information, see the * <a href="https: * * @return {@link FileProperties Storage file properties} */ public Mono<FileProperties> getProperties() { return getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getPropertiesWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response containing the {@link FileProperties storage file properties} and response status code */ public Mono<Response<FileProperties>> getPropertiesWithResponse() { return withContext(this::getPropertiesWithResponse); } Mono<Response<FileProperties>> getPropertiesWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .getPropertiesWithRestResponseAsync(shareName, filePath, snapshot, null, context)) .map(this::getPropertiesResponse); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the fileProperties.httpHeaders it will clear the httpHeaders associated to the * file. * If {@code null} is passed for the fileProperties.filesmbproperties it will preserve the filesmb properties * associated with the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file * @return The {@link FileInfo file info} * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<FileInfo> setProperties(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission) .flatMap(FluxUtil::toMono); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the httpHeaders it will clear the httpHeaders associated to the file. * If {@code null} is passed for the filesmbproperties it will preserve the filesmbproperties associated with the * file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @return Response containing the {@link FileInfo file info} and response status code. * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return withContext(context -> setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission, context)); } Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); return postProcessResponse(azureFileStorageClient.files() .setHTTPHeadersWithRestResponseAsync(shareName, filePath, fileAttributes, fileCreationTime, fileLastWriteTime, null, newFileSize, filePermission, filePermissionKey, httpHeaders, context)) .map(this::setPropertiesResponse); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadata * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return {@link FileMetadataInfo file meta info} * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<FileMetadataInfo> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return A response containing the {@link FileMetadataInfo file meta info} and status code * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata) { return withContext(context -> setMetadataWithResponse(metadata, context)); } Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .setMetadataWithRestResponseAsync(shareName, filePath, null, metadata, context)) .map(this::setMetadataResponse); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" to the file in Storage File Service. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @return A response that only contains headers and response status code */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length) { return uploadWithResponse(data, length).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload "default" to the file. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero.. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length) { return withContext(context -> uploadWithResponse(data, length, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, Context context) { FileRange range = new FileRange(0, length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" starting from 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return The {@link FileUploadInfo file upload info} * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length, long offset) { return uploadWithResponse(data, length, offset).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset) { return withContext(context -> uploadWithResponse(data, length, offset, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrl * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return The {@link FileUploadRangeFromUrlInfo file upload range from url info} */ public Mono<FileUploadRangeFromUrlInfo> uploadRangeFromUrl(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI) .flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return A response containing the {@link FileUploadRangeFromUrlInfo file upload range from url info} with headers * and response status code. */ public Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return withContext(context -> uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI, context)); } Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI, Context context) { FileRange destinationRange = new FileRange(destinationOffset, destinationOffset + length - 1); FileRange sourceRange = new FileRange(sourceOffset, sourceOffset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeFromURLWithRestResponseAsync(shareName, filePath, destinationRange.toString(), sourceURI.toString(), 0, null, sourceRange.toString(), null, null, context)) .map(this::uploadRangeFromUrlResponse); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clears the first 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared. * @return The {@link FileUploadInfo file upload info} */ public Mono<FileUploadInfo> clearRange(long length) { return clearRangeWithResponse(length, 0).flatMap(FluxUtil::toMono); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clear the range starting from 1024 with length of 1024. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return A response of {@link FileUploadInfo file upload info} that only contains headers and response status code */ public Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset) { return withContext(context -> clearRangeWithResponse(length, offset, context)); } Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, context)) .map(this::uploadResponse); } /** * Uploads file to storage file service. * * <p><strong>Code Samples</strong></p> * * <p> Upload the file from the source file path. </p> * * (@codesnippet com.azure.storage.file.fileAsyncClient.uploadFromFile
class FileAsyncClient { private final ClientLogger logger = new ClientLogger(FileAsyncClient.class); private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L; private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300; private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String filePath; private final String snapshot; private final String accountName; /** * Creates a FileAsyncClient that sends requests to the storage file at {@link AzureFileStorageImpl * endpoint}. Each service call goes through the {@link HttpPipeline pipeline} in the {@code client}. * * @param azureFileStorageClient Client that interacts with the service interfaces * @param shareName Name of the share * @param filePath Path to the file * @param snapshot The snapshot of the share */ FileAsyncClient(AzureFileStorageImpl azureFileStorageClient, String shareName, String filePath, String snapshot, String accountName) { Objects.requireNonNull(shareName, "'shareName' cannot be null."); Objects.requireNonNull(filePath, "'filePath' cannot be null."); this.shareName = shareName; this.filePath = filePath; this.snapshot = snapshot; this.azureFileStorageClient = azureFileStorageClient; this.accountName = accountName; } /** * Get the url of the storage file client. * * @return the URL of the storage file client */ public String getFileUrl() { StringBuilder fileUrlstring = new StringBuilder(azureFileStorageClient.getUrl()).append("/") .append(shareName).append("/").append(filePath); if (snapshot != null) { fileUrlstring.append("?snapshot=").append(snapshot); } return fileUrlstring.toString(); } /** * Creates a file in the storage account and returns a response of {@link FileInfo} to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with size 1KB.</p> * * {@codesnippet com.azure.storage.file.fileClient.create} * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @return A response containing the file info and the status of creating the file. * @throws StorageException If the file has already existed, the parent directory does not exist or fileName is an * invalid resource name. */ public Mono<FileInfo> create(long maxSize) { return createWithResponse(maxSize, null, null, null, null).flatMap(FluxUtil::toMono); } /** * Creates a file in the storage account and returns a response of FileInfo to interact with it. * * <p><strong>Code Samples</strong></p> * * <p>Create the file with length of 1024 bytes, some headers, file smb properties and metadata.</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.createWithResponse * * <p>For more information, see the * <a href="https: * * @param maxSize The maximum size in bytes for the file, up to 1 TiB. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @param metadata Optional name-value pairs associated with the file as metadata. * @return A response containing the {@link FileInfo file info} and the status of creating the file. * @throws StorageException If the directory has already existed, the parent directory does not exist or directory * is an invalid resource name. */ public Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata) { return withContext(context -> createWithResponse(maxSize, httpHeaders, smbProperties, filePermission, metadata, context)); } Mono<Response<FileInfo>> createWithResponse(long maxSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Map<String, String> metadata, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.FILE_PERMISSION_INHERIT); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.FILE_ATTRIBUTES_NONE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.FILE_TIME_NOW); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.FILE_TIME_NOW); return postProcessResponse(azureFileStorageClient.files() .createWithRestResponseAsync(shareName, filePath, maxSize, fileAttributes, fileCreationTime, fileLastWriteTime, null, metadata, filePermission, filePermissionKey, httpHeaders, context)) .map(this::createFileInfoResponse); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopy * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return The {@link FileCopyInfo file copy info}. * @see <a href="https: */ public Mono<FileCopyInfo> startCopy(String sourceUrl, Map<String, String> metadata) { return startCopyWithResponse(sourceUrl, metadata).flatMap(FluxUtil::toMono); } /** * Copies a blob or file to a destination file within the storage account. * * <p><strong>Code Samples</strong></p> * * <p>Copy file from source url to the {@code resourcePath} </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.startCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param sourceUrl Specifies the URL of the source file or blob, up to 2 KB in length. * @param metadata Optional name-value pairs associated with the file as metadata. Metadata names must adhere to the * naming rules. * @return A response containing the {@link FileCopyInfo file copy info} and the status of copying the file. * @see <a href="https: */ public Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata) { return withContext(context -> startCopyWithResponse(sourceUrl, metadata, context)); } Mono<Response<FileCopyInfo>> startCopyWithResponse(String sourceUrl, Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .startCopyWithRestResponseAsync(shareName, filePath, sourceUrl, null, metadata, context)) .map(this::startCopyResponse); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopy * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return An empty response. */ public Mono<Void> abortCopy(String copyId) { return abortCopyWithResponse(copyId).flatMap(FluxUtil::toMono); } /** * Aborts a pending Copy File operation, and leaves a destination file with zero length and full metadata. * * <p><strong>Code Samples</strong></p> * * <p>Abort copy file from copy id("someCopyId") </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.abortCopyWithResponse * * <p>For more information, see the * <a href="https: * * @param copyId Specifies the copy id which has copying pending status associate with it. * @return A response containing the status of aborting copy the file. */ public Mono<Response<Void>> abortCopyWithResponse(String copyId) { return withContext(context -> abortCopyWithResponse(copyId, context)); } Mono<Response<Void>> abortCopyWithResponse(String copyId, Context context) { return postProcessResponse(azureFileStorageClient.files() .abortCopyWithRestResponseAsync(shareName, filePath, copyId, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFile * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @return An empty response. */ public Mono<FileProperties> downloadToFile(String downloadFilePath) { return downloadToFileWithResponse(downloadFilePath, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties into a file specified by the path. * * <p>The file will be created and must not exist, if the file already exists a {@link FileAlreadyExistsException} * will be thrown.</p> * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes to current folder. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadToFileWithResponse * * <p>For more information, see the * <a href="https: * * @param downloadFilePath The path where store the downloaded file * @param range Optional byte range which returns file data only from the specified range. * @return An empty response. */ public Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range) { return withContext(context -> downloadToFileWithResponse(downloadFilePath, range, context)); } Mono<Response<FileProperties>> downloadToFileWithResponse(String downloadFilePath, FileRange range, Context context) { return Mono.using(() -> channelSetup(downloadFilePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW), channel -> getPropertiesWithResponse(context).flatMap(response -> downloadResponseInChunk(response, channel, range, context)), this::channelCleanUp); } private Mono<Response<FileProperties>> downloadResponseInChunk(Response<FileProperties> response, AsynchronousFileChannel channel, FileRange range, Context context) { return Mono.justOrEmpty(range).switchIfEmpty(Mono.just(new FileRange(0, response.getValue() .getContentLength()))) .map(currentRange -> { List<FileRange> chunks = new ArrayList<>(); for (long pos = currentRange.getStart(); pos < currentRange.getEnd(); pos += FILE_DEFAULT_BLOCK_SIZE) { long count = FILE_DEFAULT_BLOCK_SIZE; if (pos + count > currentRange.getEnd()) { count = currentRange.getEnd() - pos; } chunks.add(new FileRange(pos, pos + count - 1)); } return chunks; }).flatMapMany(Flux::fromIterable).flatMap(chunk -> downloadWithPropertiesWithResponse(chunk, false, context) .map(dar -> dar.getValue().getBody()) .subscribeOn(Schedulers.elastic()) .flatMap(fbb -> FluxUtil .writeFile(fbb, channel, chunk.getStart() - (range == null ? 0 : range.getStart())) .subscribeOn(Schedulers.elastic()) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException))) .then(Mono.just(response)); } private AsynchronousFileChannel channelSetup(String filePath, OpenOption... options) { try { return AsynchronousFileChannel.open(Paths.get(filePath), options); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } } private void channelCleanUp(AsynchronousFileChannel channel) { try { channel.close(); } catch (IOException e) { throw logger.logExceptionAsError(Exceptions.propagate(new UncheckedIOException(e))); } } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file with its metadata and properties. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithProperties} * * <p>For more information, see the * <a href="https: * * @return The {@link FileDownloadInfo file download Info} */ public Mono<FileDownloadInfo> downloadWithProperties() { return downloadWithPropertiesWithResponse(null, null).flatMap(FluxUtil::toMono); } /** * Downloads a file from the system, including its metadata and properties * * <p><strong>Code Samples</strong></p> * * <p>Download the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.downloadWithPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param range Optional byte range which returns file data only from the specified range. * @param rangeGetContentMD5 Optional boolean which the service returns the MD5 hash for the range when it sets to * true, as long as the range is less than or equal to 4 MB in size. * @return A response containing the {@link FileDownloadInfo file download Info} with headers and response status * code */ public Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5) { return withContext(context -> downloadWithPropertiesWithResponse(range, rangeGetContentMD5, context)); } Mono<Response<FileDownloadInfo>> downloadWithPropertiesWithResponse(FileRange range, Boolean rangeGetContentMD5, Context context) { String rangeString = range == null ? null : range.toString(); return postProcessResponse(azureFileStorageClient.files() .downloadWithRestResponseAsync(shareName, filePath, null, rangeString, rangeGetContentMD5, context)) .map(this::downloadWithPropertiesResponse); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.delete} * * <p>For more information, see the * <a href="https: * * @return An empty response * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Void> delete() { return deleteWithResponse(null).flatMap(FluxUtil::toMono); } /** * Deletes the file associate with the client. * * <p><strong>Code Samples</strong></p> * * <p>Delete the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.deleteWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response that only contains headers and response status code * @throws StorageException If the directory doesn't exist or the file doesn't exist. */ public Mono<Response<Void>> deleteWithResponse() { return withContext(this::deleteWithResponse); } Mono<Response<Void>> deleteWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .deleteWithRestResponseAsync(shareName, filePath, context)) .map(response -> new SimpleResponse<>(response, null)); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getProperties} * * <p>For more information, see the * <a href="https: * * @return {@link FileProperties Storage file properties} */ public Mono<FileProperties> getProperties() { return getPropertiesWithResponse().flatMap(FluxUtil::toMono); } /** * Retrieves the properties of the storage account's file. The properties includes file metadata, last modified * date, is server encrypted, and eTag. * * <p><strong>Code Samples</strong></p> * * <p>Retrieve file properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.getPropertiesWithResponse} * * <p>For more information, see the * <a href="https: * * @return A response containing the {@link FileProperties storage file properties} and response status code */ public Mono<Response<FileProperties>> getPropertiesWithResponse() { return withContext(this::getPropertiesWithResponse); } Mono<Response<FileProperties>> getPropertiesWithResponse(Context context) { return postProcessResponse(azureFileStorageClient.files() .getPropertiesWithRestResponseAsync(shareName, filePath, snapshot, null, context)) .map(this::getPropertiesResponse); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the fileProperties.httpHeaders it will clear the httpHeaders associated to the * file. * If {@code null} is passed for the fileProperties.filesmbproperties it will preserve the filesmb properties * associated with the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setProperties * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file * @return The {@link FileInfo file info} * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<FileInfo> setProperties(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission) .flatMap(FluxUtil::toMono); } /** * Sets the user-defined file properties to associate to the file. * * <p>If {@code null} is passed for the httpHeaders it will clear the httpHeaders associated to the file. * If {@code null} is passed for the filesmbproperties it will preserve the filesmbproperties associated with the * file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the httpHeaders of contentType of "text/plain"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>Clear the metadata of the file and preserve the SMB properties</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setPropertiesWithResponse * * <p>For more information, see the * <a href="https: * * @param newFileSize New file size of the file. * @param httpHeaders The user settable file http headers. * @param smbProperties The user settable file smb properties. * @param filePermission The file permission of the file. * @return Response containing the {@link FileInfo file info} and response status code. * @throws IllegalArgumentException thrown if parameters fail the validation. */ public Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission) { return withContext(context -> setPropertiesWithResponse(newFileSize, httpHeaders, smbProperties, filePermission, context)); } Mono<Response<FileInfo>> setPropertiesWithResponse(long newFileSize, FileHTTPHeaders httpHeaders, FileSmbProperties smbProperties, String filePermission, Context context) { smbProperties = smbProperties == null ? new FileSmbProperties() : smbProperties; validateFilePermissionAndKey(filePermission, smbProperties.getFilePermissionKey()); filePermission = smbProperties.setFilePermission(filePermission, FileConstants.PRESERVE); String filePermissionKey = smbProperties.getFilePermissionKey(); String fileAttributes = smbProperties.setNtfsFileAttributes(FileConstants.PRESERVE); String fileCreationTime = smbProperties.setFileCreationTime(FileConstants.PRESERVE); String fileLastWriteTime = smbProperties.setFileLastWriteTime(FileConstants.PRESERVE); return postProcessResponse(azureFileStorageClient.files() .setHTTPHeadersWithRestResponseAsync(shareName, filePath, fileAttributes, fileCreationTime, fileLastWriteTime, null, newFileSize, filePermission, filePermissionKey, httpHeaders, context)) .map(this::setPropertiesResponse); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadata * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return {@link FileMetadataInfo file meta info} * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<FileMetadataInfo> setMetadata(Map<String, String> metadata) { return setMetadataWithResponse(metadata).flatMap(FluxUtil::toMono); } /** * Sets the user-defined metadata to associate to the file. * * <p>If {@code null} is passed for the metadata it will clear the metadata associated to the file.</p> * * <p><strong>Code Samples</strong></p> * * <p>Set the metadata to "file:updatedMetadata"</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>Clear the metadata of the file</p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.setMetadataWithResponse * * <p>For more information, see the * <a href="https: * * @param metadata Options.Metadata to set on the file, if null is passed the metadata for the file is cleared * @return A response containing the {@link FileMetadataInfo file meta info} and status code * @throws StorageException If the file doesn't exist or the metadata contains invalid keys */ public Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata) { return withContext(context -> setMetadataWithResponse(metadata, context)); } Mono<Response<FileMetadataInfo>> setMetadataWithResponse(Map<String, String> metadata, Context context) { return postProcessResponse(azureFileStorageClient.files() .setMetadataWithRestResponseAsync(shareName, filePath, null, metadata, context)) .map(this::setMetadataResponse); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" to the file in Storage File Service. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @return A response that only contains headers and response status code */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length) { return uploadWithResponse(data, length).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to the beginning of a file in storage file service. Upload operations performs an * in-place write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload "default" to the file. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero.. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length) { return withContext(context -> uploadWithResponse(data, length, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, Context context) { FileRange range = new FileRange(0, length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload data "default" starting from 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.upload * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param length Specifies the number of bytes being transmitted in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return The {@link FileUploadInfo file upload info} * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<FileUploadInfo> upload(Flux<ByteBuffer> data, long length, long offset) { return uploadWithResponse(data, length, offset).flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes to specific of a file in storage file service. Upload operations performs an in-place * write on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Upload the file from 1024 to 2048 bytes with its metadata and properties and without the contentMD5. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadWithResponse * * <p>For more information, see the * <a href="https: * * @param data The data which will upload to the storage file. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @param length Specifies the number of bytes being transmitted in the request body. When the FileRangeWriteType is * set to clear, the value of this header must be set to zero. * @return A response containing the {@link FileUploadInfo file upload info} with headers and response status code * @throws StorageException If you attempt to upload a range that is larger than 4 MB, the service returns status * code 413 (Request Entity Too Large) */ public Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset) { return withContext(context -> uploadWithResponse(data, length, offset, context)); } Mono<Response<FileUploadInfo>> uploadWithResponse(Flux<ByteBuffer> data, long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)) .map(this::uploadResponse); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrl * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return The {@link FileUploadRangeFromUrlInfo file upload range from url info} */ public Mono<FileUploadRangeFromUrlInfo> uploadRangeFromUrl(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI) .flatMap(FluxUtil::toMono); } /** * Uploads a range of bytes from one file to another file. * * <p><strong>Code Samples</strong></p> * * <p>Upload a number of bytes from a file at defined source and destination offsets </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.uploadRangeFromUrlWithResponse * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being transmitted in the request body. * @param destinationOffset Starting point of the upload range on the destination. * @param sourceOffset Starting point of the upload range on the source. * @param sourceURI Specifies the URL of the source file. * @return A response containing the {@link FileUploadRangeFromUrlInfo file upload range from url info} with headers * and response status code. */ public Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI) { return withContext(context -> uploadRangeFromUrlWithResponse(length, destinationOffset, sourceOffset, sourceURI, context)); } Mono<Response<FileUploadRangeFromUrlInfo>> uploadRangeFromUrlWithResponse(long length, long destinationOffset, long sourceOffset, URI sourceURI, Context context) { FileRange destinationRange = new FileRange(destinationOffset, destinationOffset + length - 1); FileRange sourceRange = new FileRange(sourceOffset, sourceOffset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeFromURLWithRestResponseAsync(shareName, filePath, destinationRange.toString(), sourceURI.toString(), 0, null, sourceRange.toString(), null, null, context)) .map(this::uploadRangeFromUrlResponse); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clears the first 1024 bytes. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared. * @return The {@link FileUploadInfo file upload info} */ public Mono<FileUploadInfo> clearRange(long length) { return clearRangeWithResponse(length, 0).flatMap(FluxUtil::toMono); } /** * Clear a range of bytes to specific of a file in storage file service. Clear operations performs an in-place write * on the specified file. * * <p><strong>Code Samples</strong></p> * * <p>Clear the range starting from 1024 with length of 1024. </p> * * {@codesnippet com.azure.storage.file.fileAsyncClient.clearRange * * <p>For more information, see the * <a href="https: * * @param length Specifies the number of bytes being cleared in the request body. * @param offset Optional starting point of the upload range. It will start from the beginning if it is * {@code null} * @return A response of {@link FileUploadInfo file upload info} that only contains headers and response status code */ public Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset) { return withContext(context -> clearRangeWithResponse(length, offset, context)); } Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) { FileRange range = new FileRange(offset, offset + length - 1); return postProcessResponse(azureFileStorageClient.files() .uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, context)) .map(this::uploadResponse); } /** * Uploads file to storage file service. * * <p><strong>Code Samples</strong></p> * * <p> Upload the file from the source file path. </p> * * (@codesnippet com.azure.storage.file.fileAsyncClient.uploadFromFile
Pass the err as the inner parameter to IllegalArgumentException. Same with the one below so users can expand the inner throwable.
public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString); try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret is invalid and cannot instantiate the HMAC-SHA256 algorithm.")); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.")); } this.endpoint = credential.getBaseUri(); return this; }
throw logger.logExceptionAsError(new IllegalArgumentException(
public ConfigurationClientBuilder connectionString(String connectionString) { Objects.requireNonNull(connectionString); try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( "The secret is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); return this; }
class ConfigurationClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private static final String ACCEPT_HEADER = "Accept"; private static final String ACCEPT_HEADER_VALUE = "application/vnd.microsoft.azconfig.kv+json"; private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private ConfigurationClientCredentials credential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; /** * The constructor with defaults. */ public ConfigurationClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * * <p> * If {@link * {@link * settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * * <p> * If {@link * {@link * builder settings are ignored. * </p> * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; ConfigurationClientCredentials configurationCredentials = getConfigurationCredentials(buildConfiguration); String buildEndpoint = getBuildEndpoint(configurationCredentials); Objects.requireNonNull(buildEndpoint); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline); } ConfigurationClientCredentials buildCredential = (credential == null) ? configurationCredentials : credential; if (buildCredential == null) { throw logger.logExceptionAsWarning(new IllegalStateException("'credential' is required.")); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(AzureConfiguration.NAME, AzureConfiguration.VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); policies.add(new AddDatePolicy()); policies.add(new ConfigurationCredentialsPolicy(buildCredential)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline); } /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance to send {@link ConfigurationSetting} * service requests to and receive responses from. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException if {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is {@code null}. */ /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; 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 ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); policies.add(policy); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from * {@link ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * @param retryPolicy RetryPolicy applied to each request. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } private ConfigurationClientCredentials getConfigurationCredentials(Configuration configuration) { String connectionString = configuration.get("AZURE_APPCONFIG_CONNECTION_STRING"); if (ImplUtils.isNullOrEmpty(connectionString)) { return credential; } try { return new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException | NoSuchAlgorithmException ex) { return null; } } private String getBuildEndpoint(ConfigurationClientCredentials buildCredentials) { if (endpoint != null) { return endpoint; } else if (buildCredentials != null) { return buildCredentials.getBaseUri(); } else { return null; } } }
class ConfigurationClientBuilder { private static final String ECHO_REQUEST_ID_HEADER = "x-ms-return-client-request-id"; private static final String CONTENT_TYPE_HEADER = "Content-Type"; private static final String CONTENT_TYPE_HEADER_VALUE = "application/json"; private static final String ACCEPT_HEADER = "Accept"; private static final String ACCEPT_HEADER_VALUE = "application/vnd.microsoft.azconfig.kv+json"; private final ClientLogger logger = new ClientLogger(ConfigurationClientBuilder.class); private final List<HttpPipelinePolicy> policies; private final HttpHeaders headers; private ConfigurationClientCredentials credential; private String endpoint; private HttpClient httpClient; private HttpLogOptions httpLogOptions; private HttpPipeline pipeline; private RetryPolicy retryPolicy; private Configuration configuration; /** * The constructor with defaults. */ public ConfigurationClientBuilder() { policies = new ArrayList<>(); httpLogOptions = new HttpLogOptions(); headers = new HttpHeaders() .put(ECHO_REQUEST_ID_HEADER, "true") .put(CONTENT_TYPE_HEADER, CONTENT_TYPE_HEADER_VALUE) .put(ACCEPT_HEADER, ACCEPT_HEADER_VALUE); } /** * Creates a {@link ConfigurationClient} based on options set in the Builder. Every time {@code buildClient()} is * called a new instance of {@link ConfigurationClient} is created. * * <p> * If {@link * {@link * settings are ignored.</p> * * @return A ConfigurationClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationClient buildClient() { return new ConfigurationClient(buildAsyncClient()); } /** * Creates a {@link ConfigurationAsyncClient} based on options set in the Builder. Every time * {@code buildAsyncClient()} is called a new instance of {@link ConfigurationAsyncClient} is created. * * <p> * If {@link * {@link * builder settings are ignored. * </p> * * @return A ConfigurationAsyncClient with the options set from the builder. * @throws NullPointerException If {@code endpoint} has not been set. This setting is automatically set when * {@link * explicitly by calling {@link * @throws IllegalStateException If {@link */ public ConfigurationAsyncClient buildAsyncClient() { Configuration buildConfiguration = (configuration == null) ? Configuration.getGlobalConfiguration().clone() : configuration; ConfigurationClientCredentials configurationCredentials = getConfigurationCredentials(buildConfiguration); String buildEndpoint = getBuildEndpoint(configurationCredentials); Objects.requireNonNull(buildEndpoint); if (pipeline != null) { return new ConfigurationAsyncClient(buildEndpoint, pipeline); } ConfigurationClientCredentials buildCredential = (credential == null) ? configurationCredentials : credential; if (buildCredential == null) { throw logger.logExceptionAsWarning(new IllegalStateException("'credential' is required.")); } final List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy(AzureConfiguration.NAME, AzureConfiguration.VERSION, buildConfiguration)); policies.add(new RequestIdPolicy()); policies.add(new AddHeadersPolicy(headers)); policies.add(new AddDatePolicy()); policies.add(new ConfigurationCredentialsPolicy(buildCredential)); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(retryPolicy == null ? new RetryPolicy() : retryPolicy); policies.addAll(this.policies); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); HttpPipeline pipeline = new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .httpClient(httpClient) .build(); return new ConfigurationAsyncClient(buildEndpoint, pipeline); } /** * Sets the service endpoint for the Azure App Configuration instance. * * @param endpoint The URL of the Azure App Configuration instance to send {@link ConfigurationSetting} * service requests to and receive responses from. * @return The updated ConfigurationClientBuilder object. * @throws IllegalArgumentException if {@code endpoint} is null or it cannot be parsed into a valid URL. */ public ConfigurationClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; } /** * Sets the credential to use when authenticating HTTP requests. Also, sets the {@link * for this ConfigurationClientBuilder. * * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. * @throws NullPointerException If {@code credential} is {@code null}. */ /** * Sets the logging configuration for HTTP requests and responses. * * <p> If logLevel is not provided, default value of {@link HttpLogDetailLevel * * @param logOptions The logging configuration to use when sending and receiving HTTP requests/responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpLogOptions(HttpLogOptions logOptions) { httpLogOptions = logOptions; 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 ConfigurationClientBuilder object. * @throws NullPointerException If {@code policy} is {@code null}. */ public ConfigurationClientBuilder addPolicy(HttpPipelinePolicy policy) { Objects.requireNonNull(policy); policies.add(policy); return this; } /** * Sets the HTTP client to use for sending and receiving requests to and from the service. * * @param client The HTTP client to use for requests. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; } /** * Sets the HTTP pipeline to use for the service client. * * If {@code pipeline} is set, all other settings are ignored, aside from * {@link ConfigurationClientBuilder * ConfigurationClient}. * * @param pipeline The HTTP pipeline to use for sending service requests and receiving responses. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; 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 ConfigurationClientBuilder object. */ public ConfigurationClientBuilder configuration(Configuration configuration) { this.configuration = configuration; return this; } /** * Sets the {@link RetryPolicy} that is used when each request is sent. * * The default retry policy will be used if not provided {@link ConfigurationClientBuilder * to build {@link ConfigurationAsyncClient} or {@link ConfigurationClient}. * @param retryPolicy RetryPolicy applied to each request. * @return The updated ConfigurationClientBuilder object. */ public ConfigurationClientBuilder retryPolicy(RetryPolicy retryPolicy) { this.retryPolicy = retryPolicy; return this; } private ConfigurationClientCredentials getConfigurationCredentials(Configuration configuration) { String connectionString = configuration.get("AZURE_APPCONFIG_CONNECTION_STRING"); if (ImplUtils.isNullOrEmpty(connectionString)) { return credential; } try { return new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException | NoSuchAlgorithmException ex) { return null; } } private String getBuildEndpoint(ConfigurationClientCredentials buildCredentials) { if (endpoint != null) { return endpoint; } else if (buildCredentials != null) { return buildCredentials.getBaseUri(); } else { return null; } } }
Actually, it looks like we don't do any reading of the `ByteBuffer`, so can this be removed?
public Mono<HttpResponse> send(HttpRequest request, Context contextData) { if(request.body() != null){ request.body().map(ByteBuffer::reset); } return httpPipeline.send(request, contextData); }
request.body().map(ByteBuffer::reset);
public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request, request.body())); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Flux<ByteBuffer> validateLength(final HttpRequest request, final Flux<ByteBuffer> bbFlux) { if (bbFlux == null) { return Flux.empty(); } return Flux.defer(new Supplier<Publisher<ByteBuffer>>() { @Override public Publisher<ByteBuffer> get() { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); List<Integer> bufferLengthList = new ArrayList<>(); return bbFlux.doOnEach(s -> { if (s.isOnNext()) { Long currentTotalLength = Long.valueOf( bufferLengthList.stream().reduce(Integer::sum).orElse(0)) + s.get().remaining(); if (currentTotalLength > expectedLength) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } bufferLengthList.add(s.get().remaining()); } else if (s.isOnComplete()) { Long currentTotalLength = Long.valueOf( bufferLengthList.stream().reduce(Integer::sum).orElse(0)); if (expectedLength.compareTo(currentTotalLength) != 0) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } } else { logger.logExceptionAsError(new RuntimeException("Error occurs when validating " + "the request body legnth and the header content length. Error details: " + s.getThrowable().getMessage())); } }); } }); } private int len(ByteBuffer input) { int result = input.remaining(); return result; } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if(bodyContentObject instanceof ByteBuffer) { request.body(Flux.just(((ByteBuffer) bodyContentObject))); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) throws Exception { throw new Exception("The resume operation is not available in the base RestProxy class."); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(() -> { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); final long[] currentTotalLength = new long[1]; return bbFlux.doOnEach(s -> { if (s.isOnNext()) { ByteBuffer byteBuffer = s.get(); int currentLength = (byteBuffer == null) ? 0 : byteBuffer.remaining(); currentTotalLength[0] += currentLength; if (currentTotalLength[0] > expectedLength) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } else if (s.isOnComplete()) { if (expectedLength.compareTo(currentTotalLength[0]) != 0) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } }); }); } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("The resume operation is not available in the base RestProxy class."))); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
It is not needed. Good catch. Will remove,
public Mono<HttpResponse> send(HttpRequest request, Context contextData) { if(request.body() != null){ request.body().map(ByteBuffer::reset); } return httpPipeline.send(request, contextData); }
request.body().map(ByteBuffer::reset);
public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request, request.body())); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Flux<ByteBuffer> validateLength(final HttpRequest request, final Flux<ByteBuffer> bbFlux) { if (bbFlux == null) { return Flux.empty(); } return Flux.defer(new Supplier<Publisher<ByteBuffer>>() { @Override public Publisher<ByteBuffer> get() { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); List<Integer> bufferLengthList = new ArrayList<>(); return bbFlux.doOnEach(s -> { if (s.isOnNext()) { Long currentTotalLength = Long.valueOf( bufferLengthList.stream().reduce(Integer::sum).orElse(0)) + s.get().remaining(); if (currentTotalLength > expectedLength) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } bufferLengthList.add(s.get().remaining()); } else if (s.isOnComplete()) { Long currentTotalLength = Long.valueOf( bufferLengthList.stream().reduce(Integer::sum).orElse(0)); if (expectedLength.compareTo(currentTotalLength) != 0) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } } else { logger.logExceptionAsError(new RuntimeException("Error occurs when validating " + "the request body legnth and the header content length. Error details: " + s.getThrowable().getMessage())); } }); } }); } private int len(ByteBuffer input) { int result = input.remaining(); return result; } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if(bodyContentObject instanceof ByteBuffer) { request.body(Flux.just(((ByteBuffer) bodyContentObject))); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) throws Exception { throw new Exception("The resume operation is not available in the base RestProxy class."); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(() -> { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); final long[] currentTotalLength = new long[1]; return bbFlux.doOnEach(s -> { if (s.isOnNext()) { ByteBuffer byteBuffer = s.get(); int currentLength = (byteBuffer == null) ? 0 : byteBuffer.remaining(); currentTotalLength[0] += currentLength; if (currentTotalLength[0] > expectedLength) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } else if (s.isOnComplete()) { if (expectedLength.compareTo(currentTotalLength[0]) != 0) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } }); }); } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("The resume operation is not available in the base RestProxy class."))); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
Use lambda instead of an anonymous class.
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(new Supplier<Publisher<ByteBuffer>>() { @Override public Publisher<ByteBuffer> get() { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); List<Long> bufferLengthList = new ArrayList<>(); return bbFlux.doOnEach(s -> { if (s.isOnNext()) { Long currentLength = Long.valueOf(s.get().remaining()); Long currentTotalLength = bufferLengthList.stream().reduce(Long::sum).orElse(0L) + currentLength; if (currentTotalLength > expectedLength) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } bufferLengthList.add(currentLength); } else if (s.isOnComplete()) { Long currentTotalLength = bufferLengthList.stream().reduce(Long::sum).orElse(0L); if (expectedLength.compareTo(currentTotalLength) != 0) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } } }); } }); }
return Flux.defer(new Supplier<Publisher<ByteBuffer>>() {
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(() -> { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); final long[] currentTotalLength = new long[1]; return bbFlux.doOnEach(s -> { if (s.isOnNext()) { ByteBuffer byteBuffer = s.get(); int currentLength = (byteBuffer == null) ? 0 : byteBuffer.remaining(); currentTotalLength[0] += currentLength; if (currentTotalLength[0] > expectedLength) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } else if (s.isOnComplete()) { if (expectedLength.compareTo(currentTotalLength[0]) != 0) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } }); }); }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) throws Exception { throw new Exception("The resume operation is not available in the base RestProxy class."); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("The resume operation is not available in the base RestProxy class."))); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
You can just use a running sum for total length instead of storing each buffer's size in an array and sum it. This can just be `long totalLength = 0L` and on line 176, you could just do `totalLength += currentLength`.
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(new Supplier<Publisher<ByteBuffer>>() { @Override public Publisher<ByteBuffer> get() { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); List<Long> bufferLengthList = new ArrayList<>(); return bbFlux.doOnEach(s -> { if (s.isOnNext()) { Long currentLength = Long.valueOf(s.get().remaining()); Long currentTotalLength = bufferLengthList.stream().reduce(Long::sum).orElse(0L) + currentLength; if (currentTotalLength > expectedLength) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } bufferLengthList.add(currentLength); } else if (s.isOnComplete()) { Long currentTotalLength = bufferLengthList.stream().reduce(Long::sum).orElse(0L); if (expectedLength.compareTo(currentTotalLength) != 0) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } } }); } }); }
List<Long> bufferLengthList = new ArrayList<>();
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(() -> { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); final long[] currentTotalLength = new long[1]; return bbFlux.doOnEach(s -> { if (s.isOnNext()) { ByteBuffer byteBuffer = s.get(); int currentLength = (byteBuffer == null) ? 0 : byteBuffer.remaining(); currentTotalLength[0] += currentLength; if (currentTotalLength[0] > expectedLength) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } else if (s.isOnComplete()) { if (expectedLength.compareTo(currentTotalLength[0]) != 0) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } }); }); }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) throws Exception { throw new Exception("The resume operation is not available in the base RestProxy class."); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("The resume operation is not available in the base RestProxy class."))); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
I tried. Lambda does not take in non final variable. No easy way to do sum up.
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(new Supplier<Publisher<ByteBuffer>>() { @Override public Publisher<ByteBuffer> get() { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); List<Long> bufferLengthList = new ArrayList<>(); return bbFlux.doOnEach(s -> { if (s.isOnNext()) { Long currentLength = Long.valueOf(s.get().remaining()); Long currentTotalLength = bufferLengthList.stream().reduce(Long::sum).orElse(0L) + currentLength; if (currentTotalLength > expectedLength) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } bufferLengthList.add(currentLength); } else if (s.isOnComplete()) { Long currentTotalLength = bufferLengthList.stream().reduce(Long::sum).orElse(0L); if (expectedLength.compareTo(currentTotalLength) != 0) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } } }); } }); }
List<Long> bufferLengthList = new ArrayList<>();
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(() -> { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); final long[] currentTotalLength = new long[1]; return bbFlux.doOnEach(s -> { if (s.isOnNext()) { ByteBuffer byteBuffer = s.get(); int currentLength = (byteBuffer == null) ? 0 : byteBuffer.remaining(); currentTotalLength[0] += currentLength; if (currentTotalLength[0] > expectedLength) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } else if (s.isOnComplete()) { if (expectedLength.compareTo(currentTotalLength[0]) != 0) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } }); }); }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) throws Exception { throw new Exception("The resume operation is not available in the base RestProxy class."); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("The resume operation is not available in the base RestProxy class."))); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
Do this as Anu suggested: `final long[] currentTotalLengh = new long[1];`
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(new Supplier<Publisher<ByteBuffer>>() { @Override public Publisher<ByteBuffer> get() { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); List<Long> bufferLengthList = new ArrayList<>(); return bbFlux.doOnEach(s -> { if (s.isOnNext()) { Long currentLength = Long.valueOf(s.get().remaining()); Long currentTotalLength = bufferLengthList.stream().reduce(Long::sum).orElse(0L) + currentLength; if (currentTotalLength > expectedLength) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } bufferLengthList.add(currentLength); } else if (s.isOnComplete()) { Long currentTotalLength = bufferLengthList.stream().reduce(Long::sum).orElse(0L); if (expectedLength.compareTo(currentTotalLength) != 0) { throw new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength, expectedLength), currentTotalLength, expectedLength); } } }); } }); }
List<Long> bufferLengthList = new ArrayList<>();
private Flux<ByteBuffer> validateLength(final HttpRequest request) { final Flux<ByteBuffer> bbFlux = request.body(); if (bbFlux == null) { return Flux.empty(); } return Flux.defer(() -> { Long expectedLength = Long.valueOf(request.headers().value("Content-Length")); final long[] currentTotalLength = new long[1]; return bbFlux.doOnEach(s -> { if (s.isOnNext()) { ByteBuffer byteBuffer = s.get(); int currentLength = (byteBuffer == null) ? 0 : byteBuffer.remaining(); currentTotalLength[0] += currentLength; if (currentTotalLength[0] > expectedLength) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes more than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } else if (s.isOnComplete()) { if (expectedLength.compareTo(currentTotalLength[0]) != 0) { throw logger.logExceptionAsError(new UnexpectedLengthException( String.format("Request body emitted %d bytes less than the expected %d bytes.", currentTotalLength[0], expectedLength), currentTotalLength[0], expectedLength)); } } }); }); }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) throws Exception { throw new Exception("The resume operation is not available in the base RestProxy class."); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
class RestProxy implements InvocationHandler { private final ClientLogger logger = new ClientLogger(RestProxy.class); private final HttpPipeline httpPipeline; private final SerializerAdapter serializer; private final SwaggerInterfaceParser interfaceParser; private final HttpResponseDecoder decoder; /** * Create a RestProxy. * * @param httpPipeline the HttpPipelinePolicy and HttpClient httpPipeline that will be used to send HTTP * requests. * @param serializer the serializer that will be used to convert response bodies to POJOs. * @param interfaceParser the parser that contains information about the interface describing REST API methods * that this RestProxy "implements". */ public RestProxy(HttpPipeline httpPipeline, SerializerAdapter serializer, SwaggerInterfaceParser interfaceParser) { this.httpPipeline = httpPipeline; this.serializer = serializer; this.interfaceParser = interfaceParser; this.decoder = new HttpResponseDecoder(this.serializer); } /** * Get the SwaggerMethodParser for the provided method. The Method must exist on the Swagger * interface that this RestProxy was created to "implement". * * @param method the method to get a SwaggerMethodParser for * @return the SwaggerMethodParser for the provided method */ private SwaggerMethodParser methodParser(Method method) { return interfaceParser.methodParser(method); } /** * Get the SerializerAdapter used by this RestProxy. * * @return The SerializerAdapter used by this RestProxy */ public SerializerAdapter serializer() { return serializer; } /** * Send the provided request asynchronously, applying any request policies provided to the HttpClient instance. * * @param request the HTTP request to send * @param contextData the context * @return a {@link Mono} that emits HttpResponse asynchronously */ public Mono<HttpResponse> send(HttpRequest request, Context contextData) { return httpPipeline.send(request, contextData); } @Override public Object invoke(Object proxy, final Method method, Object[] args) { try { final SwaggerMethodParser methodParser; final HttpRequest request; if (method.isAnnotationPresent(ResumeOperation.class)) { OperationDescription opDesc = ImplUtils.findFirstOfType(args, OperationDescription.class); Method resumeMethod = determineResumeMethod(method, opDesc.methodName()); methodParser = methodParser(resumeMethod); request = createHttpRequest(opDesc, methodParser, args); final Type returnType = methodParser.returnType(); return handleResumeOperation(request, opDesc, methodParser, returnType, startTracingSpan(resumeMethod, Context.NONE)); } else { methodParser = methodParser(method); request = createHttpRequest(methodParser, args); Context context = methodParser.context(args).addData("caller-method", methodParser.fullyQualifiedMethodName()); context = startTracingSpan(method, context); if (request.body() != null) { request.body(validateLength(request)); } final Mono<HttpResponse> asyncResponse = send(request, context); Mono<HttpDecodedResponse> asyncDecodedResponse = this.decoder.decode(asyncResponse, methodParser); return handleHttpResponse(request, asyncDecodedResponse, methodParser, methodParser.returnType(), context); } } catch (Exception e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } } private Method determineResumeMethod(Method method, String resumeMethodName) { for (Method potentialResumeMethod : method.getDeclaringClass().getMethods()) { if (potentialResumeMethod.getName().equals(resumeMethodName)) { return potentialResumeMethod; } } return null; } /** * Starts the tracing span for the current service call, additionally set metadata attributes on the span by passing * additional context information. * @param method Service method being called. * @param context Context information about the current service call. * @return The updated context containing the span context. */ private Context startTracingSpan(Method method, Context context) { String spanName = String.format("Azure.%s/%s", interfaceParser.serviceName(), method.getName()); context = TracerProxy.setSpanName(spanName, context); return TracerProxy.start(spanName, context); } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(SwaggerMethodParser methodParser, Object[] args) throws IOException { UrlBuilder urlBuilder; final String path = methodParser.path(args); final UrlBuilder pathUrlBuilder = UrlBuilder.parse(path); if (pathUrlBuilder.scheme() != null) { urlBuilder = pathUrlBuilder; } else { urlBuilder = new UrlBuilder(); final String scheme = methodParser.scheme(args); urlBuilder.scheme(scheme); final String host = methodParser.host(args); urlBuilder.host(host); if (path != null && !path.isEmpty() && !path.equals("/")) { String hostPath = urlBuilder.path(); if (hostPath == null || hostPath.isEmpty() || hostPath.equals("/")) { urlBuilder.path(path); } else { urlBuilder.path(hostPath + "/" + path); } } } for (final EncodedParameter queryParameter : methodParser.encodedQueryParameters(args)) { urlBuilder.setQueryParameter(queryParameter.name(), queryParameter.encodedValue()); } final URL url = urlBuilder.toURL(); final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), url), methodParser, args); for (final HttpHeader header : methodParser.headers(args)) { request.header(header.name(), header.value()); } return request; } /** * Create a HttpRequest for the provided Swagger method using the provided arguments. * * @param methodParser the Swagger method parser to use * @param args the arguments to use to populate the method's annotation values * @return a HttpRequest * @throws IOException thrown if the body contents cannot be serialized */ private HttpRequest createHttpRequest(OperationDescription operationDescription, SwaggerMethodParser methodParser, Object[] args) throws IOException { final HttpRequest request = configRequest(new HttpRequest(methodParser.httpMethod(), operationDescription.url()), methodParser, args); for (final String headerName : operationDescription.headers().keySet()) { request.header(headerName, operationDescription.headers().get(headerName)); } return request; } @SuppressWarnings("unchecked") private HttpRequest configRequest(HttpRequest request, SwaggerMethodParser methodParser, Object[] args) throws IOException { final Object bodyContentObject = methodParser.body(args); if (bodyContentObject == null) { request.headers().put("Content-Length", "0"); } else { String contentType = methodParser.bodyContentType(); if (contentType == null || contentType.isEmpty()) { if (bodyContentObject instanceof byte[] || bodyContentObject instanceof String) { contentType = ContentType.APPLICATION_OCTET_STREAM; } else { contentType = ContentType.APPLICATION_JSON; } } request.headers().put("Content-Type", contentType); boolean isJson = false; final String[] contentTypeParts = contentType.split(";"); for (String contentTypePart : contentTypeParts) { if (contentTypePart.trim().equalsIgnoreCase(ContentType.APPLICATION_JSON)) { isJson = true; break; } } if (isJson) { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.JSON); request.body(bodyContentString); } else if (FluxUtil.isFluxByteBuffer(methodParser.bodyJavaType())) { request.body((Flux<ByteBuffer>) bodyContentObject); } else if (bodyContentObject instanceof byte[]) { request.body((byte[]) bodyContentObject); } else if (bodyContentObject instanceof String) { final String bodyContentString = (String) bodyContentObject; if (!bodyContentString.isEmpty()) { request.body(bodyContentString); } } else if (bodyContentObject instanceof ByteBuffer) { request.body(Flux.just((ByteBuffer) bodyContentObject)); } else { final String bodyContentString = serializer.serialize(bodyContentObject, SerializerEncoding.fromHeaders(request.headers())); request.body(bodyContentString); } } return request; } private Mono<HttpDecodedResponse> ensureExpectedStatus(Mono<HttpDecodedResponse> asyncDecodedResponse, final SwaggerMethodParser methodParser) { return asyncDecodedResponse .flatMap(decodedHttpResponse -> ensureExpectedStatus(decodedHttpResponse, methodParser, null)); } private static Exception instantiateUnexpectedException(UnexpectedExceptionInformation exception, HttpResponse httpResponse, String responseContent, Object responseDecodedContent) { final int responseStatusCode = httpResponse.statusCode(); String contentType = httpResponse.headerValue("Content-Type"); String bodyRepresentation; if ("application/octet-stream".equalsIgnoreCase(contentType)) { bodyRepresentation = "(" + httpResponse.headerValue("Content-Length") + "-byte body)"; } else { bodyRepresentation = responseContent.isEmpty() ? "(empty body)" : "\"" + responseContent + "\""; } Exception result; try { final Constructor<? extends HttpResponseException> exceptionConstructor = exception.exceptionType().getConstructor(String.class, HttpResponse.class, exception.exceptionBodyType()); result = exceptionConstructor.newInstance("Status code " + responseStatusCode + ", " + bodyRepresentation, httpResponse, responseDecodedContent); } catch (ReflectiveOperationException e) { String message = "Status code " + responseStatusCode + ", but an instance of " + exception.exceptionType().getCanonicalName() + " cannot be created." + " Response body: " + bodyRepresentation; result = new IOException(message, e); } return result; } /** * Create a publisher that (1) emits error if the provided response {@code decodedResponse} has * 'disallowed status code' OR (2) emits provided response if it's status code ia allowed. * * 'disallowed status code' is one of the status code defined in the provided SwaggerMethodParser * or is in the int[] of additional allowed status codes. * * @param decodedResponse The HttpResponse to check. * @param methodParser The method parser that contains information about the service interface * method that initiated the HTTP request. * @param additionalAllowedStatusCodes Additional allowed status codes that are permitted based * on the context of the HTTP request. * @return An async-version of the provided decodedResponse. */ public Mono<HttpDecodedResponse> ensureExpectedStatus(final HttpDecodedResponse decodedResponse, final SwaggerMethodParser methodParser, int[] additionalAllowedStatusCodes) { final int responseStatusCode = decodedResponse.sourceResponse().statusCode(); final Mono<HttpDecodedResponse> asyncResult; if (!methodParser.isExpectedResponseStatusCode(responseStatusCode, additionalAllowedStatusCodes)) { Mono<String> bodyAsString = decodedResponse.sourceResponse().bodyAsString(); asyncResult = bodyAsString.flatMap((Function<String, Mono<HttpDecodedResponse>>) responseContent -> { Mono<Object> decodedErrorBody = decodedResponse.decodedBody(); return decodedErrorBody.flatMap((Function<Object, Mono<HttpDecodedResponse>>) responseDecodedErrorObject -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, responseDecodedErrorObject); return Mono.error(exception); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), responseContent, null); return Mono.error(exception); })); }).switchIfEmpty(Mono.defer((Supplier<Mono<HttpDecodedResponse>>) () -> { Throwable exception = instantiateUnexpectedException(methodParser.getUnexpectedException(responseStatusCode), decodedResponse.sourceResponse(), "", null); return Mono.error(exception); })); } else { asyncResult = Mono.just(decodedResponse); } return asyncResult; } private Mono<?> handleRestResponseReturnType(HttpDecodedResponse response, SwaggerMethodParser methodParser, Type entityType) { Mono<?> asyncResult; if (TypeUtil.isTypeOrSubTypeOf(entityType, Response.class)) { Type bodyType = TypeUtil.getRestResponseBodyType(entityType); if (TypeUtil.isTypeOrSubTypeOf(bodyType, Void.class)) { asyncResult = response.sourceResponse().body().ignoreElements() .then(Mono.just(createResponse(response, entityType, null))); } else { asyncResult = handleBodyReturnType(response, methodParser, bodyType) .map((Function<Object, Response<?>>) bodyAsObject -> createResponse(response, entityType, bodyAsObject)) .switchIfEmpty(Mono.defer((Supplier<Mono<Response<?>>>) () -> Mono.just(createResponse(response, entityType, null)))); } } else { asyncResult = handleBodyReturnType(response, methodParser, entityType); } return asyncResult; } @SuppressWarnings("unchecked") private Response<?> createResponse(HttpDecodedResponse response, Type entityType, Object bodyAsObject) { final HttpResponse httpResponse = response.sourceResponse(); final HttpRequest httpRequest = httpResponse.request(); final int responseStatusCode = httpResponse.statusCode(); final HttpHeaders responseHeaders = httpResponse.headers(); Class<? extends Response<?>> cls = (Class<? extends Response<?>>) TypeUtil.getRawClass(entityType); if (cls.equals(Response.class)) { cls = (Class<? extends Response<?>>) (Object) ResponseBase.class; } else if (cls.equals(PagedResponse.class)) { cls = (Class<? extends Response<?>>) (Object) PagedResponseBase.class; if (bodyAsObject != null && !TypeUtil.isTypeOrSubTypeOf(bodyAsObject.getClass(), Page.class)) { throw logger.logExceptionAsError(new RuntimeException("Unable to create PagedResponse<T>. Body must be of a type that implements: " + Page.class)); } } List<Constructor<?>> constructors = Arrays.stream(cls.getDeclaredConstructors()) .filter(constructor -> { int paramCount = constructor.getParameterCount(); return paramCount >= 3 && paramCount <= 5; }) .sorted(Comparator.comparingInt(Constructor::getParameterCount)) .collect(Collectors.toList()); if (constructors.isEmpty()) { throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } for (Constructor<?> constructor : constructors) { final Constructor<? extends Response<?>> ctor = (Constructor<? extends Response<?>>) constructor; try { final int paramCount = constructor.getParameterCount(); switch (paramCount) { case 3: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders); case 4: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject); case 5: return ctor.newInstance(httpRequest, responseStatusCode, responseHeaders, bodyAsObject, response.decodedHeaders().block()); default: throw logger.logExceptionAsError(new IllegalStateException("Response constructor with expected parameters not found.")); } } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw logger.logExceptionAsError(reactor.core.Exceptions.propagate(e)); } } throw logger.logExceptionAsError(new RuntimeException("Cannot find suitable constructor for class " + cls)); } protected final Mono<?> handleBodyReturnType(final HttpDecodedResponse response, final SwaggerMethodParser methodParser, final Type entityType) { final int responseStatusCode = response.sourceResponse().statusCode(); final HttpMethod httpMethod = methodParser.httpMethod(); final Type returnValueWireType = methodParser.returnValueWireType(); final Mono<?> asyncResult; if (httpMethod == HttpMethod.HEAD && (TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.TYPE) || TypeUtil.isTypeOrSubTypeOf(entityType, Boolean.class))) { boolean isSuccess = (responseStatusCode / 100) == 2; asyncResult = Mono.just(isSuccess); } else if (TypeUtil.isTypeOrSubTypeOf(entityType, byte[].class)) { Mono<byte[]> responseBodyBytesAsync = response.sourceResponse().bodyAsByteArray(); if (returnValueWireType == Base64Url.class) { responseBodyBytesAsync = responseBodyBytesAsync.map(base64UrlBytes -> new Base64Url(base64UrlBytes).decodedBytes()); } asyncResult = responseBodyBytesAsync; } else if (FluxUtil.isFluxByteBuffer(entityType)) { asyncResult = Mono.just(response.sourceResponse().body()); } else { asyncResult = response.decodedBody(); } return asyncResult; } protected Object handleHttpResponse(final HttpRequest httpRequest, Mono<HttpDecodedResponse> asyncDecodedHttpResponse, SwaggerMethodParser methodParser, Type returnType, Context context) { return handleRestReturnType(asyncDecodedHttpResponse, methodParser, returnType, context); } protected Object handleResumeOperation(HttpRequest httpRequest, OperationDescription operationDescription, SwaggerMethodParser methodParser, Type returnType, Context context) { throw logger.logExceptionAsError(Exceptions.propagate(new Exception("The resume operation is not available in the base RestProxy class."))); } /** * Handle the provided asynchronous HTTP response and return the deserialized value. * * @param asyncHttpDecodedResponse the asynchronous HTTP response to the original HTTP request * @param methodParser the SwaggerMethodParser that the request originates from * @param returnType the type of value that will be returned * @param context Additional context that is passed through the Http pipeline during the service call. * @return the deserialized result */ public final Object handleRestReturnType(Mono<HttpDecodedResponse> asyncHttpDecodedResponse, final SwaggerMethodParser methodParser, final Type returnType, Context context) { final Mono<HttpDecodedResponse> asyncExpectedResponse = ensureExpectedStatus(asyncHttpDecodedResponse, methodParser) .doOnEach(RestProxy::endTracingSpan) .subscriberContext(reactor.util.context.Context.of("TRACING_CONTEXT", context)); final Object result; if (TypeUtil.isTypeOrSubTypeOf(returnType, Mono.class)) { final Type monoTypeParam = TypeUtil.getTypeArgument(returnType); if (TypeUtil.isTypeOrSubTypeOf(monoTypeParam, Void.class)) { result = asyncExpectedResponse.then(); } else { result = asyncExpectedResponse.flatMap(response -> handleRestResponseReturnType(response, methodParser, monoTypeParam)); } } else if (FluxUtil.isFluxByteBuffer(returnType)) { result = asyncExpectedResponse.flatMapMany(ar -> ar.sourceResponse().body()); } else if (TypeUtil.isTypeOrSubTypeOf(returnType, void.class) || TypeUtil.isTypeOrSubTypeOf(returnType, Void.class)) { asyncExpectedResponse.block(); result = null; } else { result = asyncExpectedResponse .flatMap(httpResponse -> handleRestResponseReturnType(httpResponse, methodParser, returnType)) .block(); } return result; } private static void endTracingSpan(Signal<HttpDecodedResponse> signal) { if (signal.isOnComplete() || signal.isOnSubscribe()) { return; } reactor.util.context.Context context = signal.getContext(); Optional<Context> tracingContext = context.getOrEmpty("TRACING_CONTEXT"); if (!tracingContext.isPresent()) { return; } int statusCode = 0; HttpDecodedResponse httpDecodedResponse; Throwable throwable = null; if (signal.hasValue()) { httpDecodedResponse = signal.get(); statusCode = httpDecodedResponse.sourceResponse().statusCode(); } else if (signal.hasError()) { throwable = signal.getThrowable(); if (throwable instanceof HttpResponseException) { HttpResponseException exception = (HttpResponseException) throwable; statusCode = exception.response().statusCode(); } } TracerProxy.end(statusCode, throwable, tracingContext.get()); } /** * Create an instance of the default serializer. * * @return the default serializer */ private static SerializerAdapter createDefaultSerializer() { return JacksonAdapter.createDefaultSerializerAdapter(); } /** * Create the default HttpPipeline. * * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline() { return createDefaultPipeline((HttpPipelinePolicy) null); } /** * Create the default HttpPipeline. * * @param credentials the credentials to use to apply authentication to the pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(TokenCredential credentials) { return createDefaultPipeline(new BearerTokenAuthenticationPolicy(credentials)); } /** * Create the default HttpPipeline. * @param credentialsPolicy the credentials policy factory to use to apply authentication to the * pipeline * @return the default HttpPipeline */ public static HttpPipeline createDefaultPipeline(HttpPipelinePolicy credentialsPolicy) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new UserAgentPolicy()); policies.add(new RetryPolicy()); policies.add(new CookiePolicy()); if (credentialsPolicy != null) { policies.add(credentialsPolicy); } return new HttpPipelineBuilder() .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface) { return create(swaggerInterface, createDefaultPipeline(), createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipeline that will be used to send Http requests * @param <A> the type of the Swagger interface * @return a proxy implementation of the provided Swagger interface */ public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline) { return create(swaggerInterface, httpPipeline, createDefaultSerializer()); } /** * Create a proxy implementation of the provided Swagger interface. * * @param swaggerInterface the Swagger interface to provide a proxy implementation for * @param httpPipeline the HttpPipelinePolicy and HttpClient pipline that will be used to send Http * requests * @param serializer the serializer that will be used to convert POJOs to and from request and * response bodies * @param <A> the type of the Swagger interface. * @return a proxy implementation of the provided Swagger interface */ @SuppressWarnings("unchecked") public static <A> A create(Class<A> swaggerInterface, HttpPipeline httpPipeline, SerializerAdapter serializer) { final SwaggerInterfaceParser interfaceParser = new SwaggerInterfaceParser(swaggerInterface, serializer); final RestProxy restProxy = new RestProxy(httpPipeline, serializer, interfaceParser); return (A) Proxy.newProxyInstance(swaggerInterface.getClassLoader(), new Class<?>[]{swaggerInterface}, restProxy); } }
How were we setting a default version before this?
public AzureQueueStorageImpl build() { if (pipeline == null) { this.pipeline = RestProxy.createDefaultPipeline(); } AzureQueueStorageImpl client = new AzureQueueStorageImpl(pipeline); if (this.url != null) { client.setUrl(this.url); } if (this.version != null) { client.setVersion(this.version); } else { client.setVersion("2018-03-28"); } return client; }
client.setVersion("2018-03-28");
public AzureQueueStorageImpl build() { if (pipeline == null) { this.pipeline = RestProxy.createDefaultPipeline(); } AzureQueueStorageImpl client = new AzureQueueStorageImpl(pipeline); if (this.url != null) { client.setUrl(this.url); } if (this.version != null) { client.setVersion(this.version); } else { client.setVersion("2018-03-28"); } return client; }
class AzureQueueStorageBuilder { /* * The URL of the service account, queue or message that is the targe of the desired operation. */ private String url; /** * Sets The URL of the service account, queue or message that is the targe of the desired operation. * * @param url the url value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder url(String url) { this.url = url; return this; } /* * Specifies the version of the operation to use for this request. */ private String version; /** * Sets Specifies the version of the operation to use for this request. * * @param version the version value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder version(String version) { this.version = version; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of AzureQueueStorageImpl with the provided parameters. * * @return an instance of AzureQueueStorageImpl. */ }
class AzureQueueStorageBuilder { /* * The URL of the service account, queue or message that is the targe of the desired operation. */ private String url; /** * Sets The URL of the service account, queue or message that is the targe of the desired operation. * * @param url the url value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder url(String url) { this.url = url; return this; } /* * Specifies the version of the operation to use for this request. */ private String version; /** * Sets Specifies the version of the operation to use for this request. * * @param version the version value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder version(String version) { this.version = version; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of AzureQueueStorageImpl with the provided parameters. * * @return an instance of AzureQueueStorageImpl. */ }
`build` used to begin with this code: ``` Java if (version == null) { this.version = "2018-03-28"; } ```
public AzureQueueStorageImpl build() { if (pipeline == null) { this.pipeline = RestProxy.createDefaultPipeline(); } AzureQueueStorageImpl client = new AzureQueueStorageImpl(pipeline); if (this.url != null) { client.setUrl(this.url); } if (this.version != null) { client.setVersion(this.version); } else { client.setVersion("2018-03-28"); } return client; }
client.setVersion("2018-03-28");
public AzureQueueStorageImpl build() { if (pipeline == null) { this.pipeline = RestProxy.createDefaultPipeline(); } AzureQueueStorageImpl client = new AzureQueueStorageImpl(pipeline); if (this.url != null) { client.setUrl(this.url); } if (this.version != null) { client.setVersion(this.version); } else { client.setVersion("2018-03-28"); } return client; }
class AzureQueueStorageBuilder { /* * The URL of the service account, queue or message that is the targe of the desired operation. */ private String url; /** * Sets The URL of the service account, queue or message that is the targe of the desired operation. * * @param url the url value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder url(String url) { this.url = url; return this; } /* * Specifies the version of the operation to use for this request. */ private String version; /** * Sets Specifies the version of the operation to use for this request. * * @param version the version value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder version(String version) { this.version = version; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of AzureQueueStorageImpl with the provided parameters. * * @return an instance of AzureQueueStorageImpl. */ }
class AzureQueueStorageBuilder { /* * The URL of the service account, queue or message that is the targe of the desired operation. */ private String url; /** * Sets The URL of the service account, queue or message that is the targe of the desired operation. * * @param url the url value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder url(String url) { this.url = url; return this; } /* * Specifies the version of the operation to use for this request. */ private String version; /** * Sets Specifies the version of the operation to use for this request. * * @param version the version value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder version(String version) { this.version = version; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of AzureQueueStorageImpl with the provided parameters. * * @return an instance of AzureQueueStorageImpl. */ }
Oh we just made it an else to this instead I misread how that moved.
public AzureQueueStorageImpl build() { if (pipeline == null) { this.pipeline = RestProxy.createDefaultPipeline(); } AzureQueueStorageImpl client = new AzureQueueStorageImpl(pipeline); if (this.url != null) { client.setUrl(this.url); } if (this.version != null) { client.setVersion(this.version); } else { client.setVersion("2018-03-28"); } return client; }
client.setVersion("2018-03-28");
public AzureQueueStorageImpl build() { if (pipeline == null) { this.pipeline = RestProxy.createDefaultPipeline(); } AzureQueueStorageImpl client = new AzureQueueStorageImpl(pipeline); if (this.url != null) { client.setUrl(this.url); } if (this.version != null) { client.setVersion(this.version); } else { client.setVersion("2018-03-28"); } return client; }
class AzureQueueStorageBuilder { /* * The URL of the service account, queue or message that is the targe of the desired operation. */ private String url; /** * Sets The URL of the service account, queue or message that is the targe of the desired operation. * * @param url the url value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder url(String url) { this.url = url; return this; } /* * Specifies the version of the operation to use for this request. */ private String version; /** * Sets Specifies the version of the operation to use for this request. * * @param version the version value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder version(String version) { this.version = version; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of AzureQueueStorageImpl with the provided parameters. * * @return an instance of AzureQueueStorageImpl. */ }
class AzureQueueStorageBuilder { /* * The URL of the service account, queue or message that is the targe of the desired operation. */ private String url; /** * Sets The URL of the service account, queue or message that is the targe of the desired operation. * * @param url the url value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder url(String url) { this.url = url; return this; } /* * Specifies the version of the operation to use for this request. */ private String version; /** * Sets Specifies the version of the operation to use for this request. * * @param version the version value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder version(String version) { this.version = version; return this; } /* * The HTTP pipeline to send requests through */ private HttpPipeline pipeline; /** * Sets The HTTP pipeline to send requests through. * * @param pipeline the pipeline value. * @return the AzureQueueStorageBuilder. */ public AzureQueueStorageBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; } /** * Builds an instance of AzureQueueStorageImpl with the provided parameters. * * @return an instance of AzureQueueStorageImpl. */ }
This kind of wrapping makes me a little sad. It makes the code harder to read, in my humble opinion, for no real gain. Can we make the rules different: set a higher max length for code (e.g. 160, 180, even 200 chars), and keep the JavaDoc length at 120? Paging @conniey for her thoughts.
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
in my experience, using 120 length is my favorite. I have also used 80 in the past (that's Oracle's policy for Java code https://www.oracle.com/technetwork/java/codeconventions-136091.html ) but that's too crazy The problem for more than 120 that I have lived are: - Works great while working with a big screen in the office/home. But becomes less confortable when working directly on laptop screen - Github uses a code preview frame of 120 length. So, it's easier to watch and read PRs without scrolling right-left in the code preview - For weird people like me that sometimes uses the screen at portrait, it's useful to see code going down instead of going wide - Guess nobody do this anymore but, some years ago, it was useful to print out important implementations to have them handy, 120 char also was better here for this anyway, I'am open to work with any
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
also @JonathanGiles , note that an exception was added to JavaDoc annotation `@codesnipped` to allow any length for it. Since we have a custom rule that enforces to keep those in one line
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
Woo! Finally! I thought about adding linelength, but was thinking about all the code I'd have to fix. I prefer 120. iirc, our .editorconfig is also 120? I don't think that code is hard to read.. but maybe that's just me, being used to having hard wrapped lines. 😄
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
I think readability can be increased if you use something like... 🤔 ```java bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); ```
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
This current way is hard to read. I think this is more readable. ```java isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier.equals(AccessModifier.PROTECTED); ```
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.IMPORT: final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF: final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken( token.findFirstToken(TokenTypes.MODIFIERS)); isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier .equals(AccessModifier.PROTECTED); break; case TokenTypes.METHOD_DEF: if (!isPublicClass) { return; } checkNoExternalDependencyExposed(token); break; default: break; } }
isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.IMPORT: final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF: final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken( token.findFirstToken(TokenTypes.MODIFIERS)); isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier.equals(AccessModifier.PROTECTED); break; case TokenTypes.METHOD_DEF: if (!isPublicClass) { return; } checkNoExternalDependencyExposed(token); break; default: break; } }
class from external dependency." + " You should not use it as a %s type."; private static final Set<String> VALID_DEPENDENCY_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "java", "com.azure", "reactor", "io.netty.buffer.ByteBuf" ))); private final Map<String, String> simpleClassNameToQualifiedNameMap = new HashMap<>(); private boolean isPublicClass; @Override public void beginTree(DetailAST rootAST) { simpleClassNameToQualifiedNameMap.clear(); }
class from external dependency. You should not use it as a %s type."; private static final Set<String> VALID_DEPENDENCY_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "java", "com.azure", "reactor" ))); private final Map<String, String> simpleClassNameToQualifiedNameMap = new HashMap<>(); private boolean isPublicClass; @Override public void beginTree(DetailAST rootAST) { simpleClassNameToQualifiedNameMap.clear(); }
yeah! that would be as javascript style ! :) love it. But, most of the fixes were done automatically by IDEAj, so, it's a neverending task if doing all manual :P
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
We do it in C# as well when method parameters get too unwieldy. But generally, we dump it on the same line.
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
> But, most of the fixes were done automatically by IDEAj, so, it's a neverending task if doing all manual :P Ahh. gotcha. no wonder some of the splits are really weird
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
Yeah, generally I would like to see some of the weirder splits fixed up to be more sane.
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded(logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
logger.info("--> END {}", request.httpMethod());
private Mono<Void> logRequest(final ClientLogger logger, final HttpRequest request) { if (detailLevel.shouldLogURL()) { logger.info("--> {} {}", request.httpMethod(), request.url()); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : request.headers()) { logger.info(header.toString()); } } Mono<Void> reqBodyLoggingMono = Mono.empty(); if (detailLevel.shouldLogBody()) { if (request.body() == null) { logger.info("(empty body)"); logger.info("--> END {}", request.httpMethod()); } else { boolean isHumanReadableContentType = !"application/octet-stream".equalsIgnoreCase(request.headers().value("Content-Type")); final long contentLength = getContentLength(request.headers()); if (contentLength < MAX_BODY_LOG_SIZE && isHumanReadableContentType) { try { Mono<byte[]> collectedBytes = FluxUtil.collectBytesInByteBufferStream(request.body()); reqBodyLoggingMono = collectedBytes.flatMap(bytes -> { String bodyString = new String(bytes, StandardCharsets.UTF_8); bodyString = prettyPrintIfNeeded( logger, request.headers().value("Content-Type"), bodyString); logger.info("{}-byte body:%n{}", contentLength, bodyString); logger.info("--> END {}", request.httpMethod()); return Mono.empty(); }); } catch (Exception e) { reqBodyLoggingMono = Mono.error(e); } } else { logger.info("{}-byte body: (content not logged)", contentLength); logger.info("--> END {}", request.httpMethod()); } } } return reqBodyLoggingMono; }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. If the detailLevel does not * include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
class HttpLoggingPolicy implements HttpPipelinePolicy { private static final ObjectMapper PRETTY_PRINTER = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT); private final HttpLogDetailLevel detailLevel; private final boolean prettyPrintJSON; private static final int MAX_BODY_LOG_SIZE = 1024 * 16; /** * Creates an HttpLoggingPolicy with the given log level. * * @param detailLevel The HTTP logging detail level. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel) { this(detailLevel, false); } /** * Creates an HttpLoggingPolicy with the given log level and pretty printing setting. * * @param detailLevel The HTTP logging detail level. * @param prettyPrintJSON If true, pretty prints JSON message bodies when logging. * If the detailLevel does not include body logging, this flag does nothing. */ public HttpLoggingPolicy(HttpLogDetailLevel detailLevel, boolean prettyPrintJSON) { this.detailLevel = detailLevel; this.prettyPrintJSON = prettyPrintJSON; } @Override public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { Optional<Object> data = context.getData("caller-method"); String callerMethod = (String) data.orElse(""); final ClientLogger logger = new ClientLogger(callerMethod); final long startNs = System.nanoTime(); Mono<Void> logRequest = logRequest(logger, context.httpRequest()); Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate = logResponseDelegate(logger, context.httpRequest().url(), startNs); return logRequest.then(next.process()).flatMap(logResponseDelegate) .doOnError(throwable -> logger.warning("<-- HTTP FAILED: ", throwable)); } private Function<HttpResponse, Mono<HttpResponse>> logResponseDelegate(final ClientLogger logger, final URL url, final long startNs) { return (HttpResponse response) -> { long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs); String contentLengthString = response.headerValue("Content-Length"); String bodySize; if (contentLengthString == null || contentLengthString.isEmpty()) { bodySize = "unknown-length"; } else { bodySize = contentLengthString + "-byte"; } if (detailLevel.shouldLogURL()) { logger.info("<-- {} {} ({} ms, {} body)", response.statusCode(), url, tookMs, bodySize); } if (detailLevel.shouldLogHeaders()) { for (HttpHeader header : response.headers()) { logger.info(header.toString()); } } if (detailLevel.shouldLogBody()) { long contentLength = getContentLength(response.headers()); final String contentTypeHeader = response.headerValue("Content-Type"); if (!"application/octet-stream".equalsIgnoreCase(contentTypeHeader) && contentLength != 0 && contentLength < MAX_BODY_LOG_SIZE) { final HttpResponse bufferedResponse = response.buffer(); return bufferedResponse.bodyAsString().map(bodyStr -> { bodyStr = prettyPrintIfNeeded(logger, contentTypeHeader, bodyStr); logger.info("Response body:\n{}", bodyStr); logger.info("<-- END HTTP"); return bufferedResponse; }).switchIfEmpty(Mono.defer(() -> Mono.just(bufferedResponse))); } else { logger.info("(body content not logged)"); logger.info("<-- END HTTP"); } } else { logger.info("<-- END HTTP"); } return Mono.just(response); }; } private String prettyPrintIfNeeded(ClientLogger logger, String contentType, String body) { String result = body; if (prettyPrintJSON && contentType != null && (contentType.startsWith("application/json") || contentType.startsWith("text/json"))) { try { final Object deserialized = PRETTY_PRINTER.readTree(body); result = PRETTY_PRINTER.writeValueAsString(deserialized); } catch (Exception e) { logger.warning("Failed to pretty print JSON: {}", e.getMessage()); } } return result; } private long getContentLength(HttpHeaders headers) { long contentLength = 0; try { contentLength = Long.parseLong(headers.value("content-length")); } catch (NumberFormatException | NullPointerException ignored) { } return contentLength; } }
Does the entire line fit if you do: ```java final DetailNode tagNameNode = JavadocUtil.findFirstToken(htmlElementStartNode, JavadocTokenTypes.HTML_TAG_NAME); ```
private void checkHtmlElementStart(DetailNode htmlElementStartNode) { final DetailNode tagNameNode = JavadocUtil .findFirstToken(htmlElementStartNode, JavadocTokenTypes.HTML_TAG_NAME); final String tagName = tagNameNode.getText().toLowerCase(); if (!CHECK_TAGS.contains(tagName)) { return; } final String tagNameBracket = "<" + tagName + ">"; final DetailNode htmlTagNode = htmlElementStartNode.getParent(); if (!isInlineCode(htmlTagNode)) { log(htmlTagNode.getLineNumber(), htmlTagNode.getColumnNumber(), String.format(MULTIPLE_LINE_SPAN_ERROR, tagNameBracket, tagNameBracket)); } }
final DetailNode tagNameNode = JavadocUtil
private void checkHtmlElementStart(DetailNode htmlElementStartNode) { final DetailNode tagNameNode = JavadocUtil.findFirstToken(htmlElementStartNode, JavadocTokenTypes.HTML_TAG_NAME); final String tagName = tagNameNode.getText().toLowerCase(); if (!CHECK_TAGS.contains(tagName)) { return; } final String tagNameBracket = "<" + tagName + ">"; final DetailNode htmlTagNode = htmlElementStartNode.getParent(); if (!isInlineCode(htmlTagNode)) { log(htmlTagNode.getLineNumber(), htmlTagNode.getColumnNumber(), String.format(MULTIPLE_LINE_SPAN_ERROR, tagNameBracket, tagNameBracket)); } }
class JavadocInlineTagCheck extends AbstractJavadocCheck { private static final String MULTIPLE_LINE_SPAN_ERROR = "Tag '%s' spans multiple lines. Use @codesnippet annotation" + " instead of '%s' to ensure that the code block always compiles."; private static final Set<String> CHECK_TAGS = Collections.unmodifiableSet(new HashSet<>( Arrays.asList("pre", "code"))); @Override public int[] getDefaultJavadocTokens() { return getRequiredJavadocTokens(); } @Override public int[] getRequiredJavadocTokens() { return new int[] { JavadocTokenTypes.HTML_ELEMENT_START, JavadocTokenTypes.JAVADOC_INLINE_TAG }; } @Override public void visitJavadocToken(DetailNode token) { DetailAST blockCommentToken = getBlockCommentAst(); if (!BlockCommentPosition.isOnMethod(blockCommentToken) && !BlockCommentPosition.isOnConstructor(blockCommentToken)) { return; } switch (token.getType()) { case JavadocTokenTypes.HTML_ELEMENT_START: checkHtmlElementStart(token); break; case JavadocTokenTypes.JAVADOC_INLINE_TAG: checkJavadocInlineTag(token); break; default: break; } } /** * Use {@literal {@codesnippet ...}} instead of '<code>', '<pre>', or {@literal {@code ...}) if these tags span * multiple lines. Inline code sample are fine as-is. * * @param htmlElementStartNode HTML_ELEMENT_START node */ /** * Check to see if the JAVADOC_INLINE_TAG node is {@literal @code} tag. If it is, check if the tag contains a new * line or a leading asterisk, which implies the tag has spanned in multiple lines. * * @param inlineTagNode JAVADOC_INLINE_TAG javadoc node */ private void checkJavadocInlineTag(DetailNode inlineTagNode) { final DetailNode codeLiteralNode = JavadocUtil.findFirstToken(inlineTagNode, JavadocTokenTypes.CODE_LITERAL); if (codeLiteralNode == null) { return; } final String codeLiteral = codeLiteralNode.getText(); if (!isInlineCode(inlineTagNode)) { log(codeLiteralNode.getLineNumber(), codeLiteralNode.getColumnNumber(), String.format(MULTIPLE_LINE_SPAN_ERROR, codeLiteral, codeLiteral)); } } /** * Find if the given tag node is in-line code sample. * @param node A given node that could be HTML_TAG or JAVADOC_INLINE_TAG * @return false if it is a code block, otherwise, return true if it is a in-line code. */ private boolean isInlineCode(DetailNode node) { for (final DetailNode child : node.getChildren()) { final int childType = child.getType(); if (childType == JavadocTokenTypes.NEWLINE || childType == JavadocTokenTypes.LEADING_ASTERISK) { return false; } } return true; } }
class JavadocInlineTagCheck extends AbstractJavadocCheck { private static final String MULTIPLE_LINE_SPAN_ERROR = "Tag '%s' spans multiple lines. Use @codesnippet annotation" + " instead of '%s' to ensure that the code block always compiles."; private static final Set<String> CHECK_TAGS = Collections.unmodifiableSet(new HashSet<>( Arrays.asList("pre", "code"))); @Override public int[] getDefaultJavadocTokens() { return getRequiredJavadocTokens(); } @Override public int[] getRequiredJavadocTokens() { return new int[] { JavadocTokenTypes.HTML_ELEMENT_START, JavadocTokenTypes.JAVADOC_INLINE_TAG }; } @Override public void visitJavadocToken(DetailNode token) { DetailAST blockCommentToken = getBlockCommentAst(); if (!BlockCommentPosition.isOnMethod(blockCommentToken) && !BlockCommentPosition.isOnConstructor(blockCommentToken)) { return; } switch (token.getType()) { case JavadocTokenTypes.HTML_ELEMENT_START: checkHtmlElementStart(token); break; case JavadocTokenTypes.JAVADOC_INLINE_TAG: checkJavadocInlineTag(token); break; default: break; } } /** * Use {@literal {@codesnippet ...}} instead of {@literal <code>}, {@literal <pre>}, or {@literal {@code ...}} * if these tags span multiple lines. Inline code sample are fine as-is. * * @param htmlElementStartNode HTML_ELEMENT_START node */ /** * Check to see if the JAVADOC_INLINE_TAG node is {@literal @code} tag. If it is, check if the tag contains a new * line or a leading asterisk, which implies the tag has spanned in multiple lines. * * @param inlineTagNode JAVADOC_INLINE_TAG javadoc node */ private void checkJavadocInlineTag(DetailNode inlineTagNode) { final DetailNode codeLiteralNode = JavadocUtil.findFirstToken(inlineTagNode, JavadocTokenTypes.CODE_LITERAL); if (codeLiteralNode == null) { return; } final String codeLiteral = codeLiteralNode.getText(); if (!isInlineCode(inlineTagNode)) { log(codeLiteralNode.getLineNumber(), codeLiteralNode.getColumnNumber(), String.format(MULTIPLE_LINE_SPAN_ERROR, codeLiteral, codeLiteral)); } } /** * Find if the given tag node is in-line code sample. * @param node A given node that could be HTML_TAG or JAVADOC_INLINE_TAG * @return false if it is a code block, otherwise, return true if it is a in-line code. */ private boolean isInlineCode(DetailNode node) { for (final DetailNode child : node.getChildren()) { final int childType = child.getType(); if (childType == JavadocTokenTypes.NEWLINE || childType == JavadocTokenTypes.LEADING_ASTERISK) { return false; } } return true; } }
Can this instead be `return Mono.just(content)`? Any reason to return `Mono.empty()` instead of an empty string?
public Mono<String> bodyAsString() { if (this.responseBody() == null) { return Mono.empty(); } else { return Mono.using(() -> this.responseBody(), rb -> { try { String content = rb.string(); return content.length() == 0 ? Mono.empty() : Mono.just(content); } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }, rb -> rb.close()); } }
return content.length() == 0 ? Mono.empty() : Mono.just(content);
public Mono<String> bodyAsString() { if (this.responseBody() == null) { return Mono.empty(); } else { return Mono.using(() -> this.responseBody(), rb -> { try { String content = rb.string(); return content.length() == 0 ? Mono.empty() : Mono.just(content); } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }, rb -> rb.close()); } }
class OkHttpResponse extends HttpResponse { private final okhttp3.Response inner; private final HttpHeaders headers; private final static int BYTE_BUFFER_CHUNK_SIZE = 1024; public OkHttpResponse(okhttp3.Response inner, HttpRequest request) { this.inner = inner; this.headers = fromOkHttpHeaders(this.inner.headers()); super.request(request); } @Override public int statusCode() { return this.inner.code(); } @Override public String headerValue(String name) { return this.headers.value(name); } @Override public HttpHeaders headers() { return this.headers; } @Override public Flux<ByteBuffer> body() { return this.responseBody() != null ? toFluxByteBuffer(this.responseBody().byteStream()) : Flux.empty(); } @Override public Mono<byte[]> bodyAsByteArray() { if (this.responseBody() == null) { return Mono.empty(); } else { return Mono.using(() -> this.responseBody(), rb -> { try { byte[] content = rb.bytes(); return content.length == 0 ? Mono.empty() : Mono.just(content); } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }, rb -> rb.close()); } } @Override @Override public Mono<String> bodyAsString(Charset charset) { return bodyAsByteArray() .map(bytes -> new String(bytes, charset)); } @Override public void close() { if (this.inner.body() != null) { this.inner.body().close(); } } private okhttp3.ResponseBody responseBody() { return this.inner.body(); } /** * Creates azure-core HttpHeaders from okhttp headers. * * @param headers okhttp headers * @return azure-core HttpHeaders */ private static HttpHeaders fromOkHttpHeaders(okhttp3.Headers headers) { HttpHeaders httpHeaders = new HttpHeaders(); for (String headerName : headers.names()) { httpHeaders.put(headerName, headers.get(headerName)); } return httpHeaders; } /** * Creates a Flux of ByteBuffer, with each ByteBuffer wrapping bytes read from the given * InputStream. * * @param inputStream InputStream to back the Flux * @return Flux of ByteBuffer backed by the InputStream */ private static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { Pair pair = new Pair(); return Flux.using(() -> inputStream, is -> Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[BYTE_BUFFER_CHUNK_SIZE]; try { int numBytes = is.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(p -> p.buffer()), is -> { try { is.close(); } catch (IOException ioe) { throw Exceptions.propagate(ioe); } } ); } private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
class OkHttpResponse extends HttpResponse { private final okhttp3.Response inner; private final HttpHeaders headers; private final static int BYTE_BUFFER_CHUNK_SIZE = 1024; public OkHttpResponse(okhttp3.Response inner, HttpRequest request) { this.inner = inner; this.headers = fromOkHttpHeaders(this.inner.headers()); super.request(request); } @Override public int statusCode() { return this.inner.code(); } @Override public String headerValue(String name) { return this.headers.value(name); } @Override public HttpHeaders headers() { return this.headers; } @Override public Flux<ByteBuffer> body() { return this.responseBody() != null ? toFluxByteBuffer(this.responseBody().byteStream()) : Flux.empty(); } @Override public Mono<byte[]> bodyAsByteArray() { if (this.responseBody() == null) { return Mono.empty(); } else { return Mono.using(() -> this.responseBody(), rb -> { try { byte[] content = rb.bytes(); return content.length == 0 ? Mono.empty() : Mono.just(content); } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }, rb -> rb.close()); } } @Override @Override public Mono<String> bodyAsString(Charset charset) { return bodyAsByteArray() .map(bytes -> new String(bytes, charset)); } @Override public void close() { if (this.inner.body() != null) { this.inner.body().close(); } } private okhttp3.ResponseBody responseBody() { return this.inner.body(); } /** * Creates azure-core HttpHeaders from okhttp headers. * * @param headers okhttp headers * @return azure-core HttpHeaders */ private static HttpHeaders fromOkHttpHeaders(okhttp3.Headers headers) { HttpHeaders httpHeaders = new HttpHeaders(); for (String headerName : headers.names()) { httpHeaders.put(headerName, headers.get(headerName)); } return httpHeaders; } /** * Creates a Flux of ByteBuffer, with each ByteBuffer wrapping bytes read from the given * InputStream. * * @param inputStream InputStream to back the Flux * @return Flux of ByteBuffer backed by the InputStream */ private static Flux<ByteBuffer> toFluxByteBuffer(InputStream inputStream) { Pair pair = new Pair(); return Flux.using(() -> inputStream, is -> Flux.just(true) .repeat() .map(ignore -> { byte[] buffer = new byte[BYTE_BUFFER_CHUNK_SIZE]; try { int numBytes = is.read(buffer); if (numBytes > 0) { return pair.buffer(ByteBuffer.wrap(buffer, 0, numBytes)).readBytes(numBytes); } else { return pair.buffer(null).readBytes(numBytes); } } catch (IOException ioe) { throw Exceptions.propagate(ioe); } }) .takeUntil(p -> p.readBytes() == -1) .filter(p -> p.readBytes() > 0) .map(p -> p.buffer()), is -> { try { is.close(); } catch (IOException ioe) { throw Exceptions.propagate(ioe); } } ); } private static class Pair { private ByteBuffer byteBuffer; private int readBytes; ByteBuffer buffer() { return this.byteBuffer; } int readBytes() { return this.readBytes; } Pair buffer(ByteBuffer byteBuffer) { this.byteBuffer = byteBuffer; return this; } Pair readBytes(int cnt) { this.readBytes = cnt; return this; } } }
Updated. What do you guys think about letting team know about some files might contain weird line breaks and to ask team to gradually enhance those cases as we keep coding in those files? That way we don't need to go line by line inspecting all code. I can create a new issue to set the right rules for new line breaks. that would produce a big list of things to gradually fix. (I would suggest to get some of the conventions from https://www.oracle.com/technetwork/java/codeconventions-150003.pdf)
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.IMPORT: final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF: final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken( token.findFirstToken(TokenTypes.MODIFIERS)); isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier .equals(AccessModifier.PROTECTED); break; case TokenTypes.METHOD_DEF: if (!isPublicClass) { return; } checkNoExternalDependencyExposed(token); break; default: break; } }
isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.IMPORT: final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF: final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken( token.findFirstToken(TokenTypes.MODIFIERS)); isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier.equals(AccessModifier.PROTECTED); break; case TokenTypes.METHOD_DEF: if (!isPublicClass) { return; } checkNoExternalDependencyExposed(token); break; default: break; } }
class from external dependency." + " You should not use it as a %s type."; private static final Set<String> VALID_DEPENDENCY_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "java", "com.azure", "reactor", "io.netty.buffer.ByteBuf" ))); private final Map<String, String> simpleClassNameToQualifiedNameMap = new HashMap<>(); private boolean isPublicClass; @Override public void beginTree(DetailAST rootAST) { simpleClassNameToQualifiedNameMap.clear(); }
class from external dependency. You should not use it as a %s type."; private static final Set<String> VALID_DEPENDENCY_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "java", "com.azure", "reactor" ))); private final Map<String, String> simpleClassNameToQualifiedNameMap = new HashMap<>(); private boolean isPublicClass; @Override public void beginTree(DetailAST rootAST) { simpleClassNameToQualifiedNameMap.clear(); }
> What do you guys think about letting team know about some files might contain weird line breaks and to ask team to gradually enhance those cases as we keep coding in those files? I'd prefer against it. 1. You're forcing developers who probably wrote OK looking code to look for weird code and fixing it. Also, assuming that they'll be looking over those files again sometime in the near future. I am sure I haven't looked back at many of my implementation classes. 1. git works by applying diffs between commits. I think the less noise between applying one change, just to revert it makes our git footprint smaller. (This is also why I have that comment about the Javadoc changes that aren't relevant to this PR.)
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.IMPORT: final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF: final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken( token.findFirstToken(TokenTypes.MODIFIERS)); isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier .equals(AccessModifier.PROTECTED); break; case TokenTypes.METHOD_DEF: if (!isPublicClass) { return; } checkNoExternalDependencyExposed(token); break; default: break; } }
isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.IMPORT: final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF: final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken( token.findFirstToken(TokenTypes.MODIFIERS)); isPublicClass = accessModifier.equals(AccessModifier.PUBLIC) || accessModifier.equals(AccessModifier.PROTECTED); break; case TokenTypes.METHOD_DEF: if (!isPublicClass) { return; } checkNoExternalDependencyExposed(token); break; default: break; } }
class from external dependency." + " You should not use it as a %s type."; private static final Set<String> VALID_DEPENDENCY_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "java", "com.azure", "reactor", "io.netty.buffer.ByteBuf" ))); private final Map<String, String> simpleClassNameToQualifiedNameMap = new HashMap<>(); private boolean isPublicClass; @Override public void beginTree(DetailAST rootAST) { simpleClassNameToQualifiedNameMap.clear(); }
class from external dependency. You should not use it as a %s type."; private static final Set<String> VALID_DEPENDENCY_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "java", "com.azure", "reactor" ))); private final Map<String, String> simpleClassNameToQualifiedNameMap = new HashMap<>(); private boolean isPublicClass; @Override public void beginTree(DetailAST rootAST) { simpleClassNameToQualifiedNameMap.clear(); }