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, cont... | 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 keyAvailableLo... | class CryptographyAsyncClient {
private JsonWebKey key;
private CryptographyService service;
private String version;
private EcKeyCryptographyClient ecKeyCryptographyClient;
private RsaKeyCryptographyClient rsaKeyCryptographyClient;
private CryptographyServiceClient cryptographyServiceClient;
private SymmetricKeyCrypto... | 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 Clien... |
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... | 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);... | class CryptographyAsyncClient {
private JsonWebKey key;
private CryptographyService service;
private String version;
private EcKeyCryptographyClient ecKeyCryptographyClient;
private RsaKeyCryptographyClient rsaKeyCryptographyClient;
private CryptographyServiceClient cryptographyServiceClient;
private SymmetricKeyCrypto... | 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 Clien... |
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 SymmetricKeyCrypto... | 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 Clien... |
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;
}
/*... | 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... |
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 = BlobContainerA... | 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 = BlobContainerA... | 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 AsyncKeyE... | 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 AsyncKeyE... |
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-... | private EncryptionData getAndValidateEncryptionData(String encryptedDataString) {
if (encryptedDataString == null) {
throw logger.logExceptionAsError(new IllegalStateException(CryptographyConstants.DECRYPT_UNENCRYPTED_BLOB));
}
ObjectMapper objectMapper = new ObjectMapper();
try {
EncryptionData encryptionData = object... | 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) {
retur... | 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 pr... | 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 pr... |
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.get... | 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", t... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... |
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.get... | 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", t... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... |
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.getLastMo... | 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.getLastMo... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... |
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 < ... | 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 < ... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... |
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 < ... | 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 < ... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... |
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 < ... | 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 < ... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... |
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 < ... | 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 < ... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... | class ConfigurationClientTestBase extends TestBase {
private static final String AZURE_APPCONFIG_CONNECTION_STRING = "AZURE_APPCONFIG_CONNECTION_STRING";
private static final String KEY_PREFIX = "key";
private static final String LABEL_PREFIX = "label";
private static final int PREFIX_LENGTH = 8;
private static final i... |
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 = cli... | 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 = cli... |
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 = cli... | 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 = cli... |
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 Confi... | 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 Confi... |
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 usi... | .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 usi... | 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 IllegalStateE... | 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 IllegalStateE... |
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 u... | .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 u... | 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 IllegalStateE... | 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 IllegalStateE... |
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(configurationS... | 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... | class ConfigurationAsyncClientTest extends ConfigurationClientTestBase {
private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class);
private ConfigurationAsyncClient client;
@Override
protected void beforeTest() {
beforeTestSetup();
if (interceptorManager.isPlaybackMode()) {
client = clien... | 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 (intercep... |
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 Confi... | 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 Confi... |
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 Confi... | 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 Confi... |
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 + bloc... | 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 + bloc... | 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'H... | 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'H... |
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 ... | 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 + bloc... | 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 + bloc... | 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'H... | 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'H... |
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().getCl... | 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());
Con... | 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.e... | 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.e... |
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().getCl... | 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());
Con... | 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.e... | 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.e... |
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().getCl... | 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());
Con... | 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.e... | 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.e... |
{} 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().getCl... | 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());
Con... | 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.e... | 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.e... |
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().getCl... | 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());
Con... | 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.e... | 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.e... |
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;
pr... | 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;
pr... |
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))
.bui... | 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))
.bui... | 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 Inval... | 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 Inval... |
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";
pri... | 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";
pri... |
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";
pri... | 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";
pri... |
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 ... | 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 t... |
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.getAllowedHeaderNam... | 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.getAllowedQueryPar... | 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 st... | 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 st... |
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 {@co... | 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 {@co... |
"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(),
c... | 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 t... | 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... | 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... |
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.
*/
Offs... | 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;
/**
* Expi... |
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 {@co... | 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 {@co... |
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.
*/
Offs... | 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;
/**
* Expi... |
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 = 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())... | 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... | 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... | 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 ... | 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 ... |
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())... | 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())... | 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 = 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())... | 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())... | 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())... | 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())... | 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())... | 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 parame... | 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 parame... | 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 EventGridS... | 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 EventGridS... |
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... | 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.
*/
priv... | 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.
*/
priv... |
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... | 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.
*/
priv... | 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.
*/
priv... |
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)... | 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)... | 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)... | 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)... | 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 Http... | 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
*/
p... |
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... | 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 u... | 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 ... |
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 u... | 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 ... |
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) R... | 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 + bloc... | 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)... | 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'H... | 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'H... |
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> convertSt... | 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)... | 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)... | 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'H... | 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'H... |
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)... | 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)... | 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'H... | 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'H... |
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 ne... | 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 ne... |
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 librarie... | 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, "'eventDataTy... | 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 parame... | 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 EventGridS... | 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 EventGridS... |
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 {
... | 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);
S... | 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";
pri... | 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";
pri... |
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 ge... | 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 ge... | 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... | 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... |
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 (!disposab... | } | 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 th... | 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 fina... | 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 Strin... |
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 (!disposab... | } | 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 th... | 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 fina... | 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 Strin... |
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() ... | } | 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.get... | 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 Strin... |
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() ... | } | 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.get... | 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 Strin... |
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 (!disposab... | } | 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 th... | 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 fina... | 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 Strin... |
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.f... | 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 th... | 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 th... | 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 Strin... | 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 Strin... |
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 th... | 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 th... | 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 Strin... | 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 Strin... |
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 =
(RecordEventsSpanI... | 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 =
(RecordEventsSpanI... | 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 OpenCens... | 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 OpenCens... |
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 != nu... | 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 != nu... | 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 shareN... | 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 shareN... |
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... | 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;
openCensu... | 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 Lin... | 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 OpenCens... | 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 OpenCens... |
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 =
(RecordEventsSpanI... | 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 =
(RecordEventsSpanI... | 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 OpenCens... | 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 OpenCens... |
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.getHostnam... | 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... | 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... | 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(EventH... | 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(EventH... |
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... | 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... | 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(EventH... | 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(EventH... |
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... | 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... | 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(EventH... | 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(EventH... |
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 != nu... | 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 != nu... | 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 shareN... | 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 shareN... |
@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 != nu... | 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 != nu... | 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 shareN... | 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 shareN... |
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 ... | 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 ... | 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";
pri... | 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";
pri... |
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 RestP... | 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 RestP... |
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 RestP... | 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 RestP... |
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().... | 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... | 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 RestP... | 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 RestP... |
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().... | 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... | 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 RestP... | 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 RestP... |
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().... | 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... | 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 RestP... | 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 RestP... |
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().... | 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... | 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 RestP... | 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 RestP... |
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.setVersi... | 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.setVersi... | 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 AzureQueueStorageB... | 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 AzureQueueStorageB... |
`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.setVersi... | 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.setVersi... | 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 AzureQueueStorageB... | 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 AzureQueueStorageB... |
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.setVersi... | 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.setVersi... | 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 AzureQueueStorageB... | 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 AzureQueueStorageB... |
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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
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 of... | 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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
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, importCl... | 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, importCl... | 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 =... | 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 boolea... |
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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
> 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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
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> reqB... | 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> reqB... | 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;
/**
* Cre... | 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;
/**
* Cre... |
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 ... | 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 =... | 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(ne... | 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(ne... |
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);
}
... | 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);
}
... | 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());
su... | 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());
su... |
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.... | 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, importCl... | 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, importCl... | 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 =... | 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 boolea... |
> 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, assumi... | 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, importCl... | 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, importCl... | 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 =... | 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 boolea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.