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
Move the `() ->` down to the next line too, so it is `() -> listKeysFirstPage(),`
public PagedFlux<KeyBase> listKeys() { return new PagedFlux<>(() -> listKeysFirstPage(), continuationToken -> listKeysNextPage(continuationToken)); }
continuationToken -> listKeysNextPage(continuationToken));
public PagedFlux<KeyBase> listKeys() { return new PagedFlux<>(() -> listKeysFirstPage(), continuationToken -> listKeysNextPage(continuationToken)); }
class KeyAsyncClient { 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 Ke...
class KeyAsyncClient { 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 Ke...
The logging messages with listSecretsNextPage will not be consistent with listSecretVersionsFirstPage
public PagedFlux<SecretBase> listSecretVersions(String name) { return new PagedFlux<>(() -> listSecretVersionsFirstPage(name), continuationToken -> listSecretsNextPage(continuationToken)); }
continuationToken -> listSecretsNextPage(continuationToken));
public PagedFlux<SecretBase> listSecretVersions(String name) { return new PagedFlux<>(() -> listSecretVersionsFirstPage(name), continuationToken -> listSecretVersionsNextPage(continuationToken)); }
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...
Better, but use logger.logAndThrow(new ...)
public ConfigurationClientBuilder endpoint(String endpoint) { try { this.endpoint = new URL(endpoint); } catch (MalformedURLException ex) { throw new IllegalArgumentException("'endpoint' must be a valid URL"); } return this; }
throw new IllegalArgumentException("'endpoint' must be a valid URL");
public ConfigurationClientBuilder endpoint(String endpoint) { try { this.endpoint = new URL(endpoint); } catch (MalformedURLException ex) { logger.logAndThrow(new IllegalArgumentException("'endpoint' must be a valid URL")); } 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...
Just call `getSubDirectoryClient()`. It's these exact lines. Similar comment for `createFile()`.
public Mono<Response<DirectoryAsyncClient>> createSubDirectory(String subDirectoryName, Map<String, String> metadata) { String directoryPath = directoryName + "/" + subDirectoryName; DirectoryAsyncClient createSubClient = new DirectoryAsyncClient(azureFileStorageClient, shareName, directoryPath, snapshot); return creat...
DirectoryAsyncClient createSubClient = new DirectoryAsyncClient(azureFileStorageClient, shareName, directoryPath, snapshot);
new DirectoryAsyncClient(azureFileStorageClient, shareName, directoryPath, snapshot); } /** * Creates this directory in the file share and returns a response of {@link DirectoryInfo}
class DirectoryAsyncClient { private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String directoryName; private final String snapshot; /** * Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link AzureFileStorageImpl * Each service call ...
class DirectoryAsyncClient { private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String directoryPath; private final String snapshot; /** * Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link AzureFileStorageImpl * Each service call ...
Same as before. We have methods for this logic. Just use them here and for deleting directories.
public Mono<VoidResponse> deleteFile(String fileName) { String filePath = directoryName + "/" + fileName; FileAsyncClient fileAsyncClient = new FileAsyncClient(azureFileStorageClient, shareName, filePath, snapshot); return fileAsyncClient.delete().map(VoidResponse::new); }
FileAsyncClient fileAsyncClient = new FileAsyncClient(azureFileStorageClient, shareName, filePath, snapshot);
public Mono<VoidResponse> deleteFile(String fileName) { FileAsyncClient fileAsyncClient = getFileClient(fileName); return fileAsyncClient.delete().map(VoidResponse::new); }
class DirectoryAsyncClient { private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String directoryName; private final String snapshot; /** * Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link AzureFileStorageImpl * Each service call ...
class DirectoryAsyncClient { private final AzureFileStorageImpl azureFileStorageClient; private final String shareName; private final String directoryPath; private final String snapshot; /** * Creates a DirectoryAsyncClient that sends requests to the storage directory at {@link AzureFileStorageImpl * Each service call ...
For the non-WithResponse examples do we need to have this variable?
public void addSettingsCodeSnippet() { ConfigurationAsyncClient client = getAsyncClient(); client.addSetting("prodDBConnection", "db_connection") .subscriberContext(Context.of(key1, value1, key2, value2)) .subscribe(response -> { ConfigurationSetting result = response; System.out.printf("Key: %s, Value: %s", result.key...
ConfigurationSetting result = response;
public void addSettingsCodeSnippet() { ConfigurationAsyncClient client = getAsyncClient(); client.addSetting("prodDBConnection", "db_connection") .subscriberContext(Context.of(key1, value1, key2, value2)) .subscribe(response -> { System.out.printf("Key: %s, Value: %s", response.key(), response.value()); }); /** * Code ...
class ConfigurationAsyncClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Code snippets for {@link ConfigurationAsyncClient */ /** * Code snippets for {@link ConfigurationAsyncClient */ public void setSettingsCod...
class ConfigurationAsyncClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Code snippets for {@link ConfigurationAsyncClient */ /** * Code snippets for {@link ConfigurationAsyncClient */ public void setSettingsCod...
So I think this branch condition is a little off (once this method also uses the path of the URL). Take this set of steps: 1. `myClient1 = builder.endpoint("http://myaccount.blob.core.windows.net/mycontainer/myblob?snapshot=mysnapshotid").buildBlobClient();` 2. `myClient2 = builder.endpoint("http://myaccount.blob.core...
public BlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobURLParts parts = URLParser.parse(url); this.endpoint = parts.scheme() + ": if (parts.containerName() != null) { this.containerName = parts.containerName(); } if (parts.blobName() != null) { this.blobName = parts.blobName(); } if...
}
public BlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobURLParts parts = URLParser.parse(url); this.endpoint = parts.scheme() + ": this.containerName = parts.containerName(); this.blobName = parts.blobName(); this.snapshot = parts.snapshot(); this.sasTokenCredential = SASTokenCredent...
class BlobClientBuilder { private static final String ACCOUNT_NAME = "accountname"; private static final String ACCOUNT_KEY = "accountkey"; private static final String ENDPOINT_PROTOCOL = "defaultendpointsprotocol"; private static final String ENDPOINT_SUFFIX = "endpointsuffix"; private final List<HttpPipelinePolicy> p...
class BlobClientBuilder { private static final String ACCOUNT_NAME = "accountname"; private static final String ACCOUNT_KEY = "accountkey"; private static final String ENDPOINT_PROTOCOL = "defaultendpointsprotocol"; private static final String ENDPOINT_SUFFIX = "endpointsuffix"; private final List<HttpPipelinePolicy> p...
I agree with those proposals, they are not only easier to explain but also removes assumptions we are trying to make on the behalf of the consumer.
public BlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobURLParts parts = URLParser.parse(url); this.endpoint = parts.scheme() + ": if (parts.containerName() != null) { this.containerName = parts.containerName(); } if (parts.blobName() != null) { this.blobName = parts.blobName(); } if...
}
public BlobClientBuilder endpoint(String endpoint) { try { URL url = new URL(endpoint); BlobURLParts parts = URLParser.parse(url); this.endpoint = parts.scheme() + ": this.containerName = parts.containerName(); this.blobName = parts.blobName(); this.snapshot = parts.snapshot(); this.sasTokenCredential = SASTokenCredent...
class BlobClientBuilder { private static final String ACCOUNT_NAME = "accountname"; private static final String ACCOUNT_KEY = "accountkey"; private static final String ENDPOINT_PROTOCOL = "defaultendpointsprotocol"; private static final String ENDPOINT_SUFFIX = "endpointsuffix"; private final List<HttpPipelinePolicy> p...
class BlobClientBuilder { private static final String ACCOUNT_NAME = "accountname"; private static final String ACCOUNT_KEY = "accountkey"; private static final String ENDPOINT_PROTOCOL = "defaultendpointsprotocol"; private static final String ENDPOINT_SUFFIX = "endpointsuffix"; private final List<HttpPipelinePolicy> p...
This whole method should just call `getSecretWithResponse(secretBase).flatMap(FluxUtil::toMono)`. Try to leave the duplication to a minimum.
public Mono<Secret> getSecret(SecretBase secretBase) { Objects.requireNonNull(secretBase, "The Secret Base parameter cannot be null."); if (secretBase.version() == null) { return getSecret(secretBase.name()); } return getSecretWithResponse(secretBase.name(), secretBase.version()) .flatMap(FluxUtil::toMono); }
.flatMap(FluxUtil::toMono);
public Mono<Secret> getSecret(SecretBase secretBase) { return getSecretWithResponse(secretBase).flatMap(FluxUtil::toMono); }
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...
Not very important but a thought, can we have getSnapshotId API?
public Mono<Response<BlobAsyncClient>> createSnapshot(Metadata metadata, BlobAccessConditions accessConditions) { metadata = metadata == null ? new Metadata() : metadata; accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs()...
.map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.deserializedHeaders().snapshot())));
new Metadata() : metadata; sourceModifiedAccessConditions = sourceModifiedAccessConditions == null ? new ModifiedAccessConditions() : sourceModifiedAccessConditions; destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions; SourceModifiedAccessConditions sourceConditions =...
class BlobAsyncClient { private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB; private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB; final AzureBlobStorageImpl azureBlobStorage; protected final String snapshot; /** * Package-private constructor for use by {@link BlobClientBu...
class BlobAsyncClient { private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB; private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB; final AzureBlobStorageImpl azureBlobStorage; protected final String snapshot; /** * Package-private constructor for use by {@link BlobClientBu...
There is a getSnapshotId method in the client
public Mono<Response<BlobAsyncClient>> createSnapshot(Metadata metadata, BlobAccessConditions accessConditions) { metadata = metadata == null ? new Metadata() : metadata; accessConditions = accessConditions == null ? new BlobAccessConditions() : accessConditions; return postProcessResponse(this.azureBlobStorage.blobs()...
.map(rb -> new SimpleResponse<>(rb, this.getSnapshotClient(rb.deserializedHeaders().snapshot())));
new Metadata() : metadata; sourceModifiedAccessConditions = sourceModifiedAccessConditions == null ? new ModifiedAccessConditions() : sourceModifiedAccessConditions; destAccessConditions = destAccessConditions == null ? new BlobAccessConditions() : destAccessConditions; SourceModifiedAccessConditions sourceConditions =...
class BlobAsyncClient { private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB; private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB; final AzureBlobStorageImpl azureBlobStorage; protected final String snapshot; /** * Package-private constructor for use by {@link BlobClientBu...
class BlobAsyncClient { private static final int BLOB_DEFAULT_DOWNLOAD_BLOCK_SIZE = 4 * Constants.MB; private static final int BLOB_MAX_DOWNLOAD_BLOCK_SIZE = 100 * Constants.MB; final AzureBlobStorageImpl azureBlobStorage; protected final String snapshot; /** * Package-private constructor for use by {@link BlobClientBu...
Document what happens if stream() is called multiple times. Does it work? Same with iterator(). Ensure unit tests are written that test if you get a stream, collect it into a list, and then do the same again, are they equivalent? Etc.
public Stream<T> stream() { return flux.toStream(); }
}
public Stream<T> stream() { return flux.toStream(); }
class IterableResponse<T> implements Iterable<T> { private final Flux<T> flux; /** * Creates instance given {@link Flux}. * @param flux to iterate over */ public IterableResponse(Flux<T> flux) { this.flux = flux; } /** * Retrieve the {@link Stream} from response. * @return stream of T */ /** * Provides iterator API. *...
class IterableResponse<T> implements Iterable<T> { private final Flux<T> flux; /** * Creates instance given {@link Flux}. * @param flux to iterate over */ public IterableResponse(Flux<T> flux) { this.flux = flux; } /** * Utility function to provide {@link Stream} of value T. * It will provide same stream of T values if...
Do you need these logs?
public void listWithMultipleLabels() { String key = getKey(); String label = getLabel(); String label2 = getLabel(); listWithMultipleLabelsRunner(key, label, label2, (setting, setting2) -> { logger.info("$$$$ listWithMultipleLabels adding setting"); assertConfigurationEquals(setting, client.addSetting(setting)); assert...
logger.info("$$$$ listWithMultipleLabels adding setting");
public void listWithMultipleLabels() { String key = getKey(); String label = getLabel(); String label2 = getLabel(); listWithMultipleLabelsRunner(key, label, label2, (setting, setting2) -> { assertConfigurationEquals(setting, client.addSetting(setting)); assertConfigurationEquals(setting2, client.addSetting(setting2));...
class ConfigurationClientTest extends ConfigurationClientTestBase { private final ClientLogger logger = new ClientLogger(ConfigurationClientTest.class); private ConfigurationClient client; @Override protected void beforeTest() { beforeTestSetup(); if (interceptorManager.isPlaybackMode()) { client = clientSetup(credenti...
class ConfigurationClientTest extends ConfigurationClientTestBase { private final ClientLogger logger = new ClientLogger(ConfigurationClientTest.class); private ConfigurationClient client; @Override protected void beforeTest() { beforeTestSetup(); if (interceptorManager.isPlaybackMode()) { client = clientSetup(credenti...
Don't bother creating the intermediate csStream variable, just do `configurationClient.listSettings(settingSelector).forEach`
public void listSettings() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); PagedIterable<ConfigurationSetting> csStream = configurationClient.listSettings(settingSelector); csStream.forEach(setting -> { Syste...
csStream.forEach(setting -> {
public void listSettings() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); configurationClient.listSettings(settingSelector).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.key(), setting....
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 IllegalStateExc...
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 IllegalStateExc...
Do this in all cases in the snippets below too.
public void listSettings() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); PagedIterable<ConfigurationSetting> csStream = configurationClient.listSettings(settingSelector); csStream.forEach(setting -> { Syste...
csStream.forEach(setting -> {
public void listSettings() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); configurationClient.listSettings(settingSelector).forEach(setting -> { System.out.printf("Key: %s, Value: %s", setting.key(), setting....
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 IllegalStateExc...
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 IllegalStateExc...
This isn't a good example. Try grabbing the page as a variable and doing something more relevant with it.
public void listSettingRevisions() { ConfigurationClient configurationClient = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); PagedIterable<ConfigurationSetting> csStream = configurationClient.listSettingRevisions(settingSelector); csStream.streamByPa...
System.out.printf("Key: %s, Value: %s", setting.value().get(0).key(), setting.value().get(0).value());
public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and statu...
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 IllegalStateExc...
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 IllegalStateExc...
Do you mean to print the number of partitions owned, or the array? Right now I think it will do the array and not the length.
private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) { return Mono.fromRunnable(() -> { logger.info("Starting load balancer"); Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1(); List<String> partitionIds = tuple.getT2(); if (ImplUtils.isNullOrEmpty(partit...
ownerPartitionMap.get(ownerId));
private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) { return Mono.fromRunnable(() -> { logger.info("Starting load balancer"); Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1(); List<String> partitionIds = tuple.getT2(); if (ImplUtils.isNullOrEmpty(partit...
class PartitionBasedLoadBalancer { private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class); private final String eventHubName; private final String consumerGroupName; private final PartitionManager partitionManager; private final EventHub...
class PartitionBasedLoadBalancer { private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class); private final String eventHubName; private final String consumerGroupName; private final PartitionManager partitionManager; private final EventHub...
Need higher code quality - odd indentation, new lines, etc should be rectified.
private IterableResponse<Integer> getIntegerIterableResponse(int startNumber, int noOfValues){ Flux<Integer> integerFlux = Flux.range(startNumber, noOfValues); return new IterableResponse<>(integerFlux); }
return new IterableResponse<>(integerFlux);
private IterableResponse<Integer> getIntegerIterableResponse(int startNumber, int noOfValues) { Flux<Integer> integerFlux = Flux.range(startNumber, noOfValues); return new IterableResponse<>(integerFlux); }
class IterableResponseTest { @Rule public TestName testName = new TestName(); @Before public void setup() { System.out.println("-------------- Running " + testName.getMethodName() + " -----------------------------"); } /*Ensure that if we call stream multiple times, it always returns same values and they are same as or...
class IterableResponseTest { @Rule public TestName testName = new TestName(); @Before public void setup() { System.out.println("-------------- Running " + testName.getMethodName() + " -----------------------------"); } /*Ensure that if we call stream multiple times, it always returns same values and they are same as or...
IIRC, %n is preferred to \n when using string.format() because it produces a platform specific line ending. Spotbugs entry: ``` FS: Format string should use %n rather than \n (VA_FORMAT_STRING_USES_NEWLINE) This format string include a newline character (\n). In format strings, it is generally preferable better to use...
public void iterateByPageSnippet() { PagedFlux<Integer> pagedFlux = createAnInstance(); PagedIterable<Integer> pagedIterableResponse = new PagedIterable<>(pagedFlux); pagedIterableResponse.iterableByPage().forEach(resp -> { if (resp.statusCode() == HttpURLConnection.HTTP_OK) { System.out.printf("Response headers are %...
System.out.printf("Response headers are %s. Url %s \n", resp.headers(), resp.request().url());
public void iterateByPageSnippet() { PagedFlux<Integer> pagedFlux = createAnInstance(); PagedIterable<Integer> pagedIterableResponse = new PagedIterable<>(pagedFlux); pagedIterableResponse.iterableByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.headers(), res...
class PagedIterableJavaDocCodeSnippets { /**Provides an example for iterate over each response using streamByPage function.**/ public void streamByPageSnippet() { PagedFlux<Integer> pagedFlux = createAnInstance(); PagedIterable<Integer> pagedIterableResponse = new PagedIterable<>(pagedFlux); pagedIterableResponse.stre...
class PagedIterableJavaDocCodeSnippets { /**Provides an example for iterate over each response using streamByPage function.**/ public void streamByPageSnippet() { PagedFlux<Integer> pagedFlux = createAnInstance(); PagedIterable<Integer> pagedIterableResponse = new PagedIterable<>(pagedFlux); pagedIterableResponse.stre...
nit: 2 spaces rather than 1. And same with lines 38, 44, and 45.
private IterableResponse<Integer> getIntegerIterableResponse(int startNumber, int noOfValues) { Flux<Integer> integerFlux = Flux.range(startNumber, noOfValues); return new IterableResponse<>(integerFlux); }
Flux<Integer> integerFlux = Flux.range(startNumber, noOfValues);
private IterableResponse<Integer> getIntegerIterableResponse(int startNumber, int noOfValues) { Flux<Integer> integerFlux = Flux.range(startNumber, noOfValues); return new IterableResponse<>(integerFlux); }
class IterableResponseTest { @Rule public TestName testName = new TestName(); @Before public void setup() { System.out.println("-------------- Running " + testName.getMethodName() + " -----------------------------"); } /*Ensure that if we call stream multiple times, it always returns same values and they are same as or...
class IterableResponseTest { @Rule public TestName testName = new TestName(); @Before public void setup() { System.out.println("-------------- Running " + testName.getMethodName() + " -----------------------------"); } /*Ensure that if we call stream multiple times, it always returns same values and they are same as or...
nit: blank line will come through into generated JavaDoc
public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().forEach(response -> { if (response.statusCode() == HttpURLConnection.HTTP_OK) ...
public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and statu...
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 IllegalStateExc...
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 IllegalStateExc...
What actually happens when the underlying `PagedFlux` has an error response? I would think that an exception is thrown instead of having a return like this.
public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().forEach(response -> { if (response.statusCode() == HttpURLConnection.HTTP_OK) {...
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and statu...
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 IllegalStateExc...
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 IllegalStateExc...
We need to figure out our code style formatting as I've seen this being changed back and forth in PRs
protected void beforeTest() { beforeTestSetup(); if (interceptorManager.isPlaybackMode()) { client = clientSetup(credentials -> new ConfigurationClientBuilder() .credential(credentials) .httpClient(interceptorManager.getPlaybackClient()) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .buildAsyncClient()); } e...
.credential(credentials)
protected void beforeTest() { beforeTestSetup(); if (interceptorManager.isPlaybackMode()) { client = clientSetup(credentials -> new ConfigurationClientBuilder() .credential(credentials) .httpClient(interceptorManager.getPlaybackClient()) .httpLogDetailLevel(HttpLogDetailLevel.BODY_AND_HEADERS) .buildAsyncClient()); } e...
class ConfigurationAsyncClientTest extends ConfigurationClientTestBase { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class); private ConfigurationAsyncClient client; @Override @Override protected void afterTest() { logger.info("Cleaning up created key values."); client.listSettings...
class ConfigurationAsyncClientTest extends ConfigurationClientTestBase { private final ClientLogger logger = new ClientLogger(ConfigurationAsyncClientTest.class); private ConfigurationAsyncClient client; @Override @Override protected void afterTest() { logger.info("Cleaning up created key values."); client.listSettings...
I would agree that the exception will be thrown and do not need to handle here.
public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().forEach(response -> { if (response.statusCode() == HttpURLConnection.HTTP_OK) {...
if (response.statusCode() == HttpURLConnection.HTTP_OK) {
public void listSettingRevisions() { ConfigurationClient client = createSyncConfigurationClient(); SettingSelector settingSelector = new SettingSelector().keys("prodDBConnection"); client.listSettingRevisions(settingSelector).streamByPage().forEach(resp -> { System.out.printf("Response headers are %s. Url %s and statu...
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 IllegalStateExc...
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 IllegalStateExc...
These code snippets would need a valid `jsonWebKeyToImport` to work. @g2vinay do we have a good working example for this or should we just keep these in the code files for now?
public void createKey() { KeyClient keyClient = createClient(); Key key = keyClient.createKey("keyName", KeyType.EC); System.out.printf("Key is created with name %s and id %s %n", key.name(), key.id()); KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA) .notBefore(OffsetDateTime.now().plus...
public void createKey() { KeyClient keyClient = createClient(); Key key = keyClient.createKey("keyName", KeyType.EC); System.out.printf("Key is created with name %s and id %s %n", key.name(), key.id()); KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA) .notBefore(OffsetDateTime.now().plus...
class KeyClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Generates code sample for creating a {@link KeyAsyncClient} * @return An instance of {@link KeyAsyncClient} */ public KeyAsyncClient createAsyncClientWit...
class KeyClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Generates code sample for creating a {@link KeyClient} * @return An instance of {@link KeyClient} */ public KeyClient createClient() { KeyClient keyClien...
We will have a good working example with Crypto API implementation. Where we can import local crypto keys into the service. I'll let you know, once I add that. For now, let's keep it in the code files. Add a TODO there.
public void createKey() { KeyClient keyClient = createClient(); Key key = keyClient.createKey("keyName", KeyType.EC); System.out.printf("Key is created with name %s and id %s %n", key.name(), key.id()); KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA) .notBefore(OffsetDateTime.now().plus...
public void createKey() { KeyClient keyClient = createClient(); Key key = keyClient.createKey("keyName", KeyType.EC); System.out.printf("Key is created with name %s and id %s %n", key.name(), key.id()); KeyCreateOptions keyCreateOptions = new KeyCreateOptions("keyName", KeyType.RSA) .notBefore(OffsetDateTime.now().plus...
class KeyClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Generates code sample for creating a {@link KeyAsyncClient} * @return An instance of {@link KeyAsyncClient} */ public KeyAsyncClient createAsyncClientWit...
class KeyClientJavaDocCodeSnippets { private String key1 = "key1"; private String key2 = "key2"; private String value1 = "val1"; private String value2 = "val2"; /** * Generates code sample for creating a {@link KeyClient} * @return An instance of {@link KeyClient} */ public KeyClient createClient() { KeyClient keyClien...
Shouldn't this be: ```java return setSecretWithResponse(secret).flatMap(FluxUtil::toMono); ```
public Mono<Secret> setSecret(Secret secret) { return withContext(context -> setSecretWithResponse(secret)) .flatMap(FluxUtil::toMono); }
.flatMap(FluxUtil::toMono);
public Mono<Secret> setSecret(Secret secret) { return setSecretWithResponse(secret).flatMap(FluxUtil::toMono); }
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...
You're discarding the Context here, which shouldn't be done.
Mono<Response<Secret>> getSecret(String name, String version, Context context) { if (version == null) { return getSecretWithResponse(name, ""); } return service.getSecret(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignoredValue -> logger.info("Retrieving secre...
return getSecretWithResponse(name, "");
return getSecretWithResponse(name, "").flatMap(FluxUtil::toMono); } /** * Updates the attributes associated with the specified secret, but not the value of the specified secret in the key vault. The update * operation changes specified attributes of an existing stored secret and attributes that are not specified in the...
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...
updated to include the context.
Mono<Response<Secret>> getSecret(String name, String version, Context context) { if (version == null) { return getSecretWithResponse(name, ""); } return service.getSecret(endpoint, name, version, API_VERSION, ACCEPT_LANGUAGE, CONTENT_TYPE_HEADER_VALUE, context) .doOnRequest(ignoredValue -> logger.info("Retrieving secre...
return getSecretWithResponse(name, "");
return getSecretWithResponse(name, "").flatMap(FluxUtil::toMono); } /** * Updates the attributes associated with the specified secret, but not the value of the specified secret in the key vault. The update * operation changes specified attributes of an existing stored secret and attributes that are not specified in the...
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...
Try to be consistent in two ways: 1. Sometimes you use `this.` and sometimes not. When it comes to method calls like this, don't use `this`. 2. Sometimes you wrap to a new line, and sometimes not. Unless you need to wrap or there are multiple chained calls, don't bother - it's nicer on one line.
public Mono<Secret> getSecret(String name) { return getSecretWithResponse(name, "") .flatMap(FluxUtil::toMono); }
.flatMap(FluxUtil::toMono);
public Mono<Secret> getSecret(String name) { return getSecretWithResponse(name, "").flatMap(FluxUtil::toMono); }
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...
Wrap `ConcurrentModificationException` with `IndexOutOfBoundsException` as the cause.
public void remove() { if (this.lastRetIndex < 0) { logger.logAndThrow(new IllegalStateException()); return; } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { logger.logAndThrow(new ConcurrentModificationException()); ret...
logger.logAndThrow(new ConcurrentModificationException());
public void remove() { if (this.lastRetIndex < 0) { throw logger.logExceptionAsError(new IllegalStateException()); } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw logger.logExceptionAsError(new ConcurrentModificat...
class ListItr implements ListIterator<E> { private final ClientLogger logger = new ClientLogger(ListItr.class); /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIte...
class ListItr implements ListIterator<E> { private final ClientLogger logger = new ClientLogger(ListItr.class); /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIte...
Same here and at other places too
public E previous() { int i = this.nextIndex - 1; if (i < 0) { logger.logAndThrow(new NoSuchElementException()); return null; } else if (i >= items.size()) { logger.logAndThrow(new ConcurrentModificationException()); return null; } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetInd...
logger.logAndThrow(new ConcurrentModificationException());
public E previous() { int i = this.nextIndex - 1; if (i < 0) { throw logger.logExceptionAsError(new NoSuchElementException()); } else if (i >= items.size()) { throw logger.logExceptionAsError(new ConcurrentModificationException()); } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetI...
class ListItr implements ListIterator<E> { private final ClientLogger logger = new ClientLogger(ListItr.class); /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIte...
class ListItr implements ListIterator<E> { private final ClientLogger logger = new ClientLogger(ListItr.class); /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIte...
There are many other places in the same place is without error cause. Should I also need to include the error cause in these places?
public E previous() { int i = this.nextIndex - 1; if (i < 0) { logger.logAndThrow(new NoSuchElementException()); return null; } else if (i >= items.size()) { logger.logAndThrow(new ConcurrentModificationException()); return null; } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetInd...
logger.logAndThrow(new ConcurrentModificationException());
public E previous() { int i = this.nextIndex - 1; if (i < 0) { throw logger.logExceptionAsError(new NoSuchElementException()); } else if (i >= items.size()) { throw logger.logExceptionAsError(new ConcurrentModificationException()); } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetI...
class ListItr implements ListIterator<E> { private final ClientLogger logger = new ClientLogger(ListItr.class); /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIte...
class ListItr implements ListIterator<E> { private final ClientLogger logger = new ClientLogger(ListItr.class); /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIte...
It feels like you are subverting the visitor pattern in isValidScope by doing the tree traversal yourself. You can save states in your logger. 1. When at a class def, is this class publicly visible? 2. When at a method def, is this method publicly visible? 3. I encountered a "throw", is it inside that method and class...
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.LITERAL_THROW: if (!isValidScope(token)) { return; } log(token, String.format("Directly throwing an exception is disallowed. Replace the throw statement with" + " a call to ''%s''.", LOGGER_LOG_AND_THROW)); break; case TokenTypes.METHO...
if (!isValidScope(token)) {
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.CLASS_DEF: DetailAST modifiersToken = token.findFirstToken(TokenTypes.MODIFIERS); classStaticDeque.addLast(modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)); break; case TokenTypes.CTOR_DEF: isInConstructor = true; break; case ...
class ThrowFromClientLoggerCheck extends AbstractCheck { private static final String LOGGER_LOG_AND_THROW = "logger.logAndThrow"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredToken...
class is static private final Deque<Boolean> classStaticDeque = new ArrayDeque<>(); private final Deque<Boolean> methodStaticDeque = new ArrayDeque<>(); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
What's the reason for this logic? Might need some clarifying docs. (ie. Why don't we have `exprToken.getNextSibling().getNextSibling().getNextSibling()` if we have `exprToken.getNextSibling().getNextSibling()`?) Would: TokenUtils.findFirstTokenByPredicate(DetailAST root, Predicate<DetailAST> predicate) help?
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.LITERAL_THROW: if (!isValidScope(token)) { return; } log(token, String.format("Directly throwing an exception is disallowed. Replace the throw statement with" + " a call to ''%s''.", LOGGER_LOG_AND_THROW)); break; case TokenTypes.METHO...
if (exprToken.getNextSibling() == null || exprToken.getNextSibling().getNextSibling() == null
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.CLASS_DEF: DetailAST modifiersToken = token.findFirstToken(TokenTypes.MODIFIERS); classStaticDeque.addLast(modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)); break; case TokenTypes.CTOR_DEF: isInConstructor = true; break; case ...
class ThrowFromClientLoggerCheck extends AbstractCheck { private static final String LOGGER_LOG_AND_THROW = "logger.logAndThrow"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredToken...
class is static private final Deque<Boolean> classStaticDeque = new ArrayDeque<>(); private final Deque<Boolean> methodStaticDeque = new ArrayDeque<>(); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
Yep. You are right. Will change to using the state of token.
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.LITERAL_THROW: if (!isValidScope(token)) { return; } log(token, String.format("Directly throwing an exception is disallowed. Replace the throw statement with" + " a call to ''%s''.", LOGGER_LOG_AND_THROW)); break; case TokenTypes.METHO...
if (!isValidScope(token)) {
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.CLASS_DEF: DetailAST modifiersToken = token.findFirstToken(TokenTypes.MODIFIERS); classStaticDeque.addLast(modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)); break; case TokenTypes.CTOR_DEF: isInConstructor = true; break; case ...
class ThrowFromClientLoggerCheck extends AbstractCheck { private static final String LOGGER_LOG_AND_THROW = "logger.logAndThrow"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredToken...
class is static private final Deque<Boolean> classStaticDeque = new ArrayDeque<>(); private final Deque<Boolean> methodStaticDeque = new ArrayDeque<>(); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
The logic here is checking immediately return after throw statements. Any of getNextSibling return null implies no return statement immediately after throw
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.LITERAL_THROW: if (!isValidScope(token)) { return; } log(token, String.format("Directly throwing an exception is disallowed. Replace the throw statement with" + " a call to ''%s''.", LOGGER_LOG_AND_THROW)); break; case TokenTypes.METHO...
if (exprToken.getNextSibling() == null || exprToken.getNextSibling().getNextSibling() == null
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.CLASS_DEF: DetailAST modifiersToken = token.findFirstToken(TokenTypes.MODIFIERS); classStaticDeque.addLast(modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)); break; case TokenTypes.CTOR_DEF: isInConstructor = true; break; case ...
class ThrowFromClientLoggerCheck extends AbstractCheck { private static final String LOGGER_LOG_AND_THROW = "logger.logAndThrow"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredToken...
class is static private final Deque<Boolean> classStaticDeque = new ArrayDeque<>(); private final Deque<Boolean> methodStaticDeque = new ArrayDeque<>(); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
BTW, the logic will only check if the class is a static class because ClientLogger will not be a static variable, it will not able to use a non-static variable in a static class. The rule checks all main code package no matter if a class is public or private.
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.LITERAL_THROW: if (!isValidScope(token)) { return; } log(token, String.format("Directly throwing an exception is disallowed. Replace the throw statement with" + " a call to ''%s''.", LOGGER_LOG_AND_THROW)); break; case TokenTypes.METHO...
if (!isValidScope(token)) {
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.CLASS_DEF: DetailAST modifiersToken = token.findFirstToken(TokenTypes.MODIFIERS); classStaticDeque.addLast(modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)); break; case TokenTypes.CTOR_DEF: isInConstructor = true; break; case ...
class ThrowFromClientLoggerCheck extends AbstractCheck { private static final String LOGGER_LOG_AND_THROW = "logger.logAndThrow"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredToken...
class is static private final Deque<Boolean> classStaticDeque = new ArrayDeque<>(); private final Deque<Boolean> methodStaticDeque = new ArrayDeque<>(); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
What about `exprToken.getNextSibling().getNextSibling() == null`?
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.LITERAL_THROW: if (!isValidScope(token)) { return; } log(token, String.format("Directly throwing an exception is disallowed. Replace the throw statement with" + " a call to ''%s''.", LOGGER_LOG_AND_THROW)); break; case TokenTypes.METHO...
if (exprToken.getNextSibling() == null || exprToken.getNextSibling().getNextSibling() == null
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.CLASS_DEF: DetailAST modifiersToken = token.findFirstToken(TokenTypes.MODIFIERS); classStaticDeque.addLast(modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)); break; case TokenTypes.CTOR_DEF: isInConstructor = true; break; case ...
class ThrowFromClientLoggerCheck extends AbstractCheck { private static final String LOGGER_LOG_AND_THROW = "logger.logAndThrow"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredToken...
class is static private final Deque<Boolean> classStaticDeque = new ArrayDeque<>(); private final Deque<Boolean> methodStaticDeque = new ArrayDeque<>(); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
Document this in the code.
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.LITERAL_THROW: if (!isValidScope(token)) { return; } log(token, String.format("Directly throwing an exception is disallowed. Replace the throw statement with" + " a call to ''%s''.", LOGGER_LOG_AND_THROW)); break; case TokenTypes.METHO...
if (exprToken.getNextSibling() == null || exprToken.getNextSibling().getNextSibling() == null
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.CLASS_DEF: DetailAST modifiersToken = token.findFirstToken(TokenTypes.MODIFIERS); classStaticDeque.addLast(modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)); break; case TokenTypes.CTOR_DEF: isInConstructor = true; break; case ...
class ThrowFromClientLoggerCheck extends AbstractCheck { private static final String LOGGER_LOG_AND_THROW = "logger.logAndThrow"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredToken...
class is static private final Deque<Boolean> classStaticDeque = new ArrayDeque<>(); private final Deque<Boolean> methodStaticDeque = new ArrayDeque<>(); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
exprToken.getNextSibling() could be SEME, ';'. exprToken.getNextSibling().getNextSibling() could be null if there is no other statement following ; https://github.com/Azure/azure-sdk-for-java/blob/0c12ca0d946f943531503451549610bad658ca82/sdk/eventhubs/azure-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventDat...
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.LITERAL_THROW: if (!isValidScope(token)) { return; } log(token, String.format("Directly throwing an exception is disallowed. Replace the throw statement with" + " a call to ''%s''.", LOGGER_LOG_AND_THROW)); break; case TokenTypes.METHO...
if (exprToken.getNextSibling() == null || exprToken.getNextSibling().getNextSibling() == null
public void visitToken(DetailAST token) { switch (token.getType()) { case TokenTypes.CLASS_DEF: DetailAST modifiersToken = token.findFirstToken(TokenTypes.MODIFIERS); classStaticDeque.addLast(modifiersToken.branchContains(TokenTypes.LITERAL_STATIC)); break; case TokenTypes.CTOR_DEF: isInConstructor = true; break; case ...
class ThrowFromClientLoggerCheck extends AbstractCheck { private static final String LOGGER_LOG_AND_THROW = "logger.logAndThrow"; @Override public int[] getDefaultTokens() { return getRequiredTokens(); } @Override public int[] getAcceptableTokens() { return getRequiredTokens(); } @Override public int[] getRequiredToken...
class is static private final Deque<Boolean> classStaticDeque = new ArrayDeque<>(); private final Deque<Boolean> methodStaticDeque = new ArrayDeque<>(); private boolean isInConstructor = false; @Override public int[] getDefaultTokens() { return getRequiredTokens(); }
How does the service loader determine iteration order? Alphabetically, random? Maybe build in a preference order here or a configuration setting?
public static HttpClient createInstance() { if (defaultProvider == null) { defaultProvider = serviceLoader.iterator().next(); } if (defaultProvider == null) { } return defaultProvider.createNewInstance(); }
public static HttpClient createInstance() { if (defaultProvider == null) { throw new IllegalStateException( "Cannot find any HttpClient provider on the classpath - unable to create a default HttpClient instance"); } return defaultProvider.createInstance(); }
class HttpClientProviders { private static ServiceLoader<HttpClientProvider> serviceLoader; static { serviceLoader = ServiceLoader.load(HttpClientProvider.class); } private static HttpClientProvider defaultProvider; private HttpClientProviders() { } }
class HttpClientProviders { private static HttpClientProvider defaultProvider; static { ServiceLoader<HttpClientProvider> serviceLoader = ServiceLoader.load(HttpClientProvider.class); Iterator<HttpClientProvider> it = serviceLoader.iterator(); if (it.hasNext()) { defaultProvider = it.next(); } } private HttpClientProvi...
It's in the order as found on the classpath. For now this will be sufficient I think. In the fullness of time we would only fall through to this when the user has not specified one in their builder via a `httpClient(..)` builder method.
public static HttpClient createInstance() { if (defaultProvider == null) { defaultProvider = serviceLoader.iterator().next(); } if (defaultProvider == null) { } return defaultProvider.createNewInstance(); }
public static HttpClient createInstance() { if (defaultProvider == null) { throw new IllegalStateException( "Cannot find any HttpClient provider on the classpath - unable to create a default HttpClient instance"); } return defaultProvider.createInstance(); }
class HttpClientProviders { private static ServiceLoader<HttpClientProvider> serviceLoader; static { serviceLoader = ServiceLoader.load(HttpClientProvider.class); } private static HttpClientProvider defaultProvider; private HttpClientProviders() { } }
class HttpClientProviders { private static HttpClientProvider defaultProvider; static { ServiceLoader<HttpClientProvider> serviceLoader = ServiceLoader.load(HttpClientProvider.class); Iterator<HttpClientProvider> it = serviceLoader.iterator(); if (it.hasNext()) { defaultProvider = it.next(); } } private HttpClientProvi...
Good catch. I was being quite hacky. I'll fix this now so if you want to continue this PR tomorrow it is already resolved.
private boolean shouldRetry(HttpResponse response, int tryCount) { int code = response.statusCode(); return tryCount < maxRetries && (code == 408 || (code >= 500) && code != 501 && code != 505); }
|| (code >= 500)
private boolean shouldRetry(HttpResponse response, int tryCount) { int code = response.statusCode(); return tryCount < maxRetries && (code == HttpURLConnection.HTTP_CLIENT_TIMEOUT || (code >= HttpURLConnection.HTTP_INTERNAL_ERROR && code != HttpURLConnection.HTTP_NOT_IMPLEMENTED && code != HttpURLConnection.HTTP_VERSIO...
class RetryPolicy implements HttpPipelinePolicy { private static final int DEFAULT_MAX_RETRIES = 3; private static final int DEFAULT_DELAY = 0; private static final ChronoUnit DEFAULT_TIME_UNIT = ChronoUnit.MILLIS; private static final String RETRY_AFTER_MS_HEADER = "retry-after-ms"; private final int maxRetries; priva...
class RetryPolicy implements HttpPipelinePolicy { private static final int DEFAULT_MAX_RETRIES = 3; private static final int DEFAULT_DELAY = 0; private static final ChronoUnit DEFAULT_TIME_UNIT = ChronoUnit.MILLIS; private static final String RETRY_AFTER_MS_HEADER = "retry-after-ms"; private final int maxRetries; priva...
Why flatmap rather than .map()? `.flatMap` transforms items asynchronously. If `flatMap` is what you want then `this.eTag` is not being used in a thread-safe manner. How about `.map().then()`? .then() replays the complete signal and any errors.
public Mono<Void> updateCheckpoint(long sequenceNumber, String offset){ Checkpoint checkpoint = new Checkpoint() .consumerGroupName(partitionContext.consumerGroupName()) .eventHubName(partitionContext.eventHubName()) .instanceId(partitionContext.instanceId()) .partitionId(partitionContext.partitionId()) .sequenceNumber...
return this.partitionManager.updateCheckpoint(checkpoint).flatMap(eTag -> {
public Mono<Void> updateCheckpoint(long sequenceNumber, String offset) { String previousETag = this.eTag.get(); Checkpoint checkpoint = new Checkpoint() .consumerGroupName(partitionContext.consumerGroupName()) .eventHubName(partitionContext.eventHubName()) .ownerId(ownerId) .partitionId(partitionContext.partitionId()) ...
class will forward the request to private PartitionManager partitionManager; private String eTag; CheckpointManager(PartitionContext partitionContext, PartitionManager partitionManager, String eTag) { this.partitionContext = partitionContext; this.partitionManager = partitionManager; this.eTag = eTag; }
class CheckpointManager { private final PartitionContext partitionContext; private final PartitionManager partitionManager; private final AtomicReference<String> eTag; private final String ownerId; /** * Creates a new checkpoint manager which {@link PartitionProcessor} can use to update checkpoints. * * @param ownerId ...
Since this is a demo, I won't comment too much... but: 1. remove `.blockLast()` 1. `doOnNext` I see for side effects like logging, but since following code depends on it, have you considered using .map and .flatMap?
void run() { /* This should run periodically get new ownership details and close/open new consumers when ownership of this instance has changed */ List<String> eventHubPartitionIds = new ArrayList<>(); this.eventHubAsyncClient.getPartitionIds().doOnNext(eventHubPartitionIds::add).blockLast(); logger.info("Found {} part...
this.eventHubAsyncClient.getPartitionIds().doOnNext(eventHubPartitionIds::add).blockLast();
void run() { /* This will run periodically to get new ownership details and close/open new consumers when ownership of this instance has changed */ final Flux<PartitionOwnership> ownershipFlux = partitionManager.listOwnership(eventHubName, consumerGroupName) .cache(); eventHubAsyncClient.getPartitionIds() .flatMap(id -...
class and add more details to this */
class EventProcessorAsyncClient { private static final long INTERVAL_IN_SECONDS = 10; private static final long INITIAL_DELAY = 0; private static final long OWNERSHIP_EXPIRATION_TIME_IN_MILLIS = TimeUnit.SECONDS.toMillis(30); private final ClientLogger logger = new ClientLogger(EventProcessorAsyncClient.class); private...
It is likely my shallow knowledge of Java, but does this comment imply that we're not explicitly requiring someone to pass an instance and, instead, are going spelunking through the path and find one at random? If so, that scares me and I think it probably needs discussion. Or, this is a case of "you have no idea wh...
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
class implementing {@link PartitionManager}
class EventHubClientBuilder { private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private TokenCredential credentials; private Configuration configuration; private Duration timeout; private ProxyConfiguration proxyConfiguration; private Retry retry; private Scheduler s...
No, your understanding is correct. Jonathan suggested that we add this functionality as we are/will be doing this for other stuff too. This may not be required for preview 2 and we can discuss this further if this is necessary.
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
class implementing {@link PartitionManager}
class EventHubClientBuilder { private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private TokenCredential credentials; private Configuration configuration; private Duration timeout; private ProxyConfiguration proxyConfiguration; private Retry retry; private Scheduler s...
I am fine with this being discussed. My basic proposition was based on an assumption that in most cases the user will likely have on their classpath (i.e. with their application) a single partition manager. This would be on the classpath because the user opted into a specific one as part of their Maven configuration. H...
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
class implementing {@link PartitionManager}
class EventHubClientBuilder { private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private TokenCredential credentials; private Configuration configuration; private Duration timeout; private ProxyConfiguration proxyConfiguration; private Retry retry; private Scheduler s...
I feel like we're in some very Java-specific areas here, and I don't want to push against common practice, known patterns, and language idioms, so I'm going to nod and smile at most of that since I just don't have the context or experience to really discuss intelligently. For my own edification, what happens if I have...
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
class implementing {@link PartitionManager}
class EventHubClientBuilder { private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private TokenCredential credentials; private Configuration configuration; private Duration timeout; private ProxyConfiguration proxyConfiguration; private Retry retry; private Scheduler s...
I cannot have Response <T> return types except for getKey operation. Should I avoid having Context overloads ?
public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> client.encrypt(algorithm, plaintext, context, iv, authenticationData)).block(); }
return withContext(context -> client.encrypt(algorithm, plaintext, context, iv, authenticationData)).block();
public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return encrypt(algorithm, plaintext, iv, authenticationData, 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...
I'm not fond of the .blockLast() in this synchronous method because it'll throw an exception if we use a parallel or single scheduler... Since this runs periodically, I have to think more about a better way to do this. Here's a way to reduce the number of .blocks you are using. ```java final Flux<PartitionOwnership>...
void run() { /* This should run periodically get new ownership details and close/open new consumers when ownership of this instance has changed */ List<String> eventHubPartitionIds = new ArrayList<>(); this.eventHubAsyncClient.getPartitionIds() .map(eventHubPartitionIds::add).blockLast(Duration.ofSeconds(1)); logger.in...
List<String> eventHubPartitionIds = new ArrayList<>();
void run() { /* This will run periodically to get new ownership details and close/open new consumers when ownership of this instance has changed */ final Flux<PartitionOwnership> ownershipFlux = partitionManager.listOwnership(eventHubName, consumerGroupName) .cache(); eventHubAsyncClient.getPartitionIds() .flatMap(id -...
class and add more details to this */
class EventProcessorAsyncClient { private static final long INTERVAL_IN_SECONDS = 10; private static final long INITIAL_DELAY = 0; private static final long OWNERSHIP_EXPIRATION_TIME_IN_MILLIS = TimeUnit.SECONDS.toMillis(30); private final ClientLogger logger = new ClientLogger(EventProcessorAsyncClient.class); private...
This is where we can define the rules that we want. A set of rules we might define are: 1. If there is no partition manager (PM) on the classpath, and if the user does not explicitly provide one (somehow?!), then we throw an exception. 2. If there is no PM on the classpath, and the user does specify one, we use it. 3....
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
class implementing {@link PartitionManager}
class EventHubClientBuilder { private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private TokenCredential credentials; private Configuration configuration; private Duration timeout; private ProxyConfiguration proxyConfiguration; private Retry retry; private Scheduler s...
Thanks for the insight. For what its worth, that all sounds lucid and well-reasoned to me, from an outsider's perspective.
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
public EventHubClientBuilder partitionManager(PartitionManager partitionManager) { this.partitionManager = partitionManager; return this; }
class implementing {@link PartitionManager}
class EventHubClientBuilder { private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING"; private TokenCredential credentials; private Configuration configuration; private Duration timeout; private ProxyConfiguration proxyConfiguration; private Retry retry; private Scheduler s...
Why do this check every time you call getToken. Couldn't this be done up front when the credential is constructed?
public Mono<AccessToken> getToken(String... scopes) { if (clientId() == null) { throw new IllegalArgumentException("Must provide non-null value for client id in " + this.getClass().getSimpleName()); } return identityClient.authenticateWithCurrentlyLoggedInAccount(scopes).onErrorResume(t -> Mono.empty()) .switchIfEmpty(...
throw new IllegalArgumentException("Must provide non-null value for client id in " + this.getClass().getSimpleName());
public Mono<AccessToken> getToken(String... scopes) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithUserRefreshToken(scopes, cachedToken.get()).onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty(Mono.defer(() -> identityClient.authentica...
class InteractiveBrowserCredential extends AadCredential<InteractiveBrowserCredential> { private int port; private final IdentityClient identityClient; /** * Creates a InteractiveBrowserCredential with a listening port, for which {@code http: * registered as a valid reply URL on the application. * * @param port the por...
class InteractiveBrowserCredential implements TokenCredential { private final int port; private final IdentityClient identityClient; private final AtomicReference<MsalToken> cachedToken; /** * Creates a InteractiveBrowserCredential with the given identity client options and a listening port, for which * {@code http: * ...
Let me talk to Jonathan about this one - currently the client id parameter is mutable.
public Mono<AccessToken> getToken(String... scopes) { if (clientId() == null) { throw new IllegalArgumentException("Must provide non-null value for client id in " + this.getClass().getSimpleName()); } return identityClient.authenticateWithCurrentlyLoggedInAccount(scopes).onErrorResume(t -> Mono.empty()) .switchIfEmpty(...
throw new IllegalArgumentException("Must provide non-null value for client id in " + this.getClass().getSimpleName());
public Mono<AccessToken> getToken(String... scopes) { return Mono.defer(() -> { if (cachedToken.get() != null) { return identityClient.authenticateWithUserRefreshToken(scopes, cachedToken.get()).onErrorResume(t -> Mono.empty()); } else { return Mono.empty(); } }).switchIfEmpty(Mono.defer(() -> identityClient.authentica...
class InteractiveBrowserCredential extends AadCredential<InteractiveBrowserCredential> { private int port; private final IdentityClient identityClient; /** * Creates a InteractiveBrowserCredential with a listening port, for which {@code http: * registered as a valid reply URL on the application. * * @param port the por...
class InteractiveBrowserCredential implements TokenCredential { private final int port; private final IdentityClient identityClient; private final AtomicReference<MsalToken> cachedToken; /** * Creates a InteractiveBrowserCredential with the given identity client options and a listening port, for which * {@code http: * ...
You should consider making a copy of credentials here, otherwise it may get modified afterwards if the user continues to user the builder and modify the credentials.
public ChainedTokenCredential build() { return new ChainedTokenCredential(credentials); }
return new ChainedTokenCredential(credentials);
public ChainedTokenCredential build() { return new ChainedTokenCredential(new ArrayDeque<>(credentials)); }
class ChainedTokenCredentialBuilder { private final Deque<TokenCredential> credentials; /** * Creates an instance of the builder to config the credential. */ public ChainedTokenCredentialBuilder() { this.credentials = new ArrayDeque<>(); } /** * Adds a credential to try to authenticate at the front of the chain. * @par...
class ChainedTokenCredentialBuilder { private final Deque<TokenCredential> credentials; /** * Creates an instance of the builder to config the credential. */ public ChainedTokenCredentialBuilder() { this.credentials = new ArrayDeque<>(); } /** * Adds a credential to try to authenticate at the front of the chain. * @par...
The code here could be made into a general-purpose util for validation of parameters. Might be an interesting challenge at some point.
public ClientCertificateCredential build() { List<String> missing = new ArrayList<>(); if (clientId == null) { missing.add("clientId"); } if (tenantId == null) { missing.add("tenantId"); } if (clientCertificate == null) { missing.add("clientCertificate"); } if (missing.size() > 0) { throw new IllegalArgumentException("...
}
public ClientCertificateCredential build() { ValidationUtil.validate(getClass().getSimpleName(), new HashMap<String, Object>() {{ put("clientId", clientId); put("tenantId", tenantId); put("clientCertificate", clientCertificate); }}); return new ClientCertificateCredential(tenantId, clientId, clientCertificate, clientCe...
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String clientCertificate; private String clientCertificatePassword; /** * Sets the client certificate for authenticating to AAD. * * @param certificatePath the PEM file containing the certificate * @r...
class ClientCertificateCredentialBuilder extends AadCredentialBuilderBase<ClientCertificateCredentialBuilder> { private String tenantId; private String clientCertificate; private String clientCertificatePassword; /** * Sets the tenant ID of the application. * @param tenantId the tenant ID of the application. * @return ...
I guess the reason for using self here is because compiler won't allow using non-final variable inside .then() In that case, we should just make self explicitly final so its more clear to the reader of the code.
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { AutoCheckpointer self = this; return self.observer.processChanges(context, docs) .then(self.afterProcessChanges(context)); }
AutoCheckpointer self = this;
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .then(this.afterProcessChanges(context)); }
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; private ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) ...
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private volatile int processedDocCount; private volatile ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedO...
Same here. We should make self final explicitly.
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { AutoCheckpointer self = this; self.processedDocCount ++; if (self.isCheckpointNeeded()) { return context.checkpoint() .doOnSuccess((Void) -> { self.processedDocCount = 0; self.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }); } retu...
AutoCheckpointer self = this;
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { this.processedDocCount ++; if (this.isCheckpointNeeded()) { return context.checkpoint() .doOnSuccess((Void) -> { this.processedDocCount = 0; this.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }); } return Mono.empty(); }
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; private ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) ...
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private volatile int processedDocCount; private volatile ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedO...
we don't have any inner class etc, here. You can use `this` directly why are are using `self=this`
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { AutoCheckpointer self = this; return self.observer.processChanges(context, docs) .then(self.afterProcessChanges(context)); }
AutoCheckpointer self = this;
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .then(this.afterProcessChanges(context)); }
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; private ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) ...
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private volatile int processedDocCount; private volatile ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedO...
Last comment on `final` keyword. Here and other places if any.
public Mono<Void> initialize() { BootstrapperImpl self = this; self.isInitialized = false; return Mono.just(self) .flatMap( value -> self.leaseStore.isInitialized()) .flatMap(initialized -> { self.isInitialized = initialized; if (initialized) { return Mono.empty(); } else { return self.leaseStore.acquireInitializationL...
self.isInitialized = false;
public Mono<Void> initialize() { this.isInitialized = false; return Mono.just(this) .flatMap( value -> this.leaseStore.isInitialized()) .flatMap(initialized -> { this.isInitialized = initialized; if (initialized) { return Mono.empty(); } else { return this.leaseStore.acquireInitializationLock(this.lockTime) .flatMap(lo...
class BootstrapperImpl implements Bootstrapper { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final PartitionSynchronizer synchronizer; private final LeaseStore leaseStore; private final Duration lockTime; private final Duration sleepTime; private boolean isInitialized; private...
class BootstrapperImpl implements Bootstrapper { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final PartitionSynchronizer synchronizer; private final LeaseStore leaseStore; private final Duration lockTime; private final Duration sleepTime; private volatile boolean isInitialized...
slf4j logger has support for place holder `{}`, you don't need String.format here. remove `String.format` https://www.slf4j.org/manual.html
public Mono<Void> run(CancellationToken cancellationToken) { LeaseRenewerImpl self = this; logger.info(String.format("Partition %s: renewer task started.", self.lease.getLeaseToken())); long remainingWork = this.leaseRenewInterval.toMillis(); try { while (!cancellationToken.isCancellationRequested() && remainingWork > ...
logger.error(String.format("Partition %s: renew lease loop failed.", self.lease.getLeaseToken()), throwable);
public Mono<Void> run(CancellationToken cancellationToken) { logger.info("Partition {}: renewer task started.", this.lease.getLeaseToken()); return Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseR...
class LeaseRenewerImpl implements LeaseRenewer { private final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, LeaseMan...
class LeaseRenewerImpl implements LeaseRenewer { private static final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, L...
slf4j logger has support for place holder {}, you don't need String.format here. remove String.format https://www.slf4j.org/manual.html
private Mono<Lease> renew(CancellationToken cancellationToken) { LeaseRenewerImpl self = this; if (cancellationToken.isCancellationRequested()) return Mono.empty(); return self.leaseManager.renew(self.lease) .map(renewedLease -> { if (renewedLease != null) { self.lease = renewedLease; } logger.info(String.format("Parti...
logger.error(String.format("Partition %s: lost lease on renew.", self.lease.getLeaseToken()), lle);
private Mono<Lease> renew(CancellationToken cancellationToken) { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } return this.leaseManager.renew(this.lease) .map(renewedLease -> { if (renewedLease != null) { this.lease = renewedLease; } logger.info("Partition {}: renewed lease with result {}", ...
class LeaseRenewerImpl implements LeaseRenewer { private final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, LeaseMan...
class LeaseRenewerImpl implements LeaseRenewer { private static final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, L...
last comment on the String.format inside slf4j logger. slf4j logger has support for place holder {}, you don't need String.format here. remove String.format https://www.slf4j.org/manual.html please fix this here and elsewhere throughout the code.
private Mono<Lease> renew(CancellationToken cancellationToken) { LeaseRenewerImpl self = this; if (cancellationToken.isCancellationRequested()) return Mono.empty(); return self.leaseManager.renew(self.lease) .map(renewedLease -> { if (renewedLease != null) { self.lease = renewedLease; } logger.info(String.format("Parti...
logger.error(String.format("Partition %s: failed to renew lease.", self.lease.getLeaseToken()), throwable);
private Mono<Lease> renew(CancellationToken cancellationToken) { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } return this.leaseManager.renew(this.lease) .map(renewedLease -> { if (renewedLease != null) { this.lease = renewedLease; } logger.info("Partition {}: renewed lease with result {}", ...
class LeaseRenewerImpl implements LeaseRenewer { private final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, LeaseMan...
class LeaseRenewerImpl implements LeaseRenewer { private static final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, L...
String.format creates unnecessary objects internally. We should avoid it as much as we can. And in this case, I suppose this call can be replaced by something like this: `logger.info("Partition {} renewer task started", self.lease.getLeaseToken())`
public Mono<Void> run(CancellationToken cancellationToken) { LeaseRenewerImpl self = this; logger.info(String.format("Partition %s: renewer task started.", self.lease.getLeaseToken())); long remainingWork = this.leaseRenewInterval.toMillis(); try { while (!cancellationToken.isCancellationRequested() && remainingWork > ...
logger.info(String.format("Partition %s: renewer task started.", self.lease.getLeaseToken()));
public Mono<Void> run(CancellationToken cancellationToken) { logger.info("Partition {}: renewer task started.", this.lease.getLeaseToken()); return Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseR...
class LeaseRenewerImpl implements LeaseRenewer { private final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, LeaseMan...
class LeaseRenewerImpl implements LeaseRenewer { private static final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, L...
Same here and below at line 65.
public Mono<Void> run(CancellationToken cancellationToken) { LeaseRenewerImpl self = this; logger.info(String.format("Partition %s: renewer task started.", self.lease.getLeaseToken())); long remainingWork = this.leaseRenewInterval.toMillis(); try { while (!cancellationToken.isCancellationRequested() && remainingWork > ...
logger.info(String.format("Partition %s: renewer task stopped.", self.lease.getLeaseToken()));
public Mono<Void> run(CancellationToken cancellationToken) { logger.info("Partition {}: renewer task started.", this.lease.getLeaseToken()); return Mono.just(this) .flatMap(value -> { if (cancellationToken.isCancellationRequested()) { return Mono.empty(); } ZonedDateTime stopTimer = ZonedDateTime.now().plus(this.leaseR...
class LeaseRenewerImpl implements LeaseRenewer { private final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, LeaseMan...
class LeaseRenewerImpl implements LeaseRenewer { private static final Logger logger = LoggerFactory.getLogger(LeaseRenewerImpl.class); private final LeaseManager leaseManager; private final Duration leaseRenewInterval; private Lease lease; private RuntimeException resultException; public LeaseRenewerImpl(Lease lease, L...
you don't need `Exception.propagate(.)` here. `Exception.propagate(.)` will wrap the exception in runtime exception if it is not already a runtime exception. In this case `IllegalArgumentException` is already a runtime exception.
public Mono<Lease> createLeaseIfNotExist(String leaseToken, String continuationToken) { if (leaseToken == null) throw Exceptions.propagate(new IllegalArgumentException("leaseToken")); String leaseDocId = this.getDocumentId(leaseToken); ServiceItemLease documentServiceLease = new ServiceItemLease() .withId(leaseDocId) ....
if (leaseToken == null) throw Exceptions.propagate(new IllegalArgumentException("leaseToken"));
public Mono<Lease> createLeaseIfNotExist(String leaseToken, String continuationToken) { if (leaseToken == null) { throw new IllegalArgumentException("leaseToken"); } String leaseDocId = this.getDocumentId(leaseToken); ServiceItemLease documentServiceLease = new ServiceItemLease() .withId(leaseDocId) .withLeaseToken(lea...
class LeaseStoreManagerImpl implements LeaseStoreManager, LeaseStoreManager.LeaseStoreManagerBuilderDefinition { private final Logger logger = LoggerFactory.getLogger(LeaseStoreManagerImpl.class); private LeaseStoreManagerSettings settings; private ChangeFeedContextClient leaseDocumentClient; private RequestOptionsFact...
class LeaseStoreManagerImpl implements LeaseStoreManager, LeaseStoreManager.LeaseStoreManagerBuilderDefinition { private final Logger logger = LoggerFactory.getLogger(LeaseStoreManagerImpl.class); private LeaseStoreManagerSettings settings; private ChangeFeedContextClient leaseDocumentClient; private RequestOptionsFact...
This doesn't log what you intend. `%s` is for String.format not for slfj4 logger. slf4j logger doesn't understand `%s` placeholder please fix. https://www.slf4j.org/manual.html
private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lease lease) { PartitionControllerImpl self = this; CancellationToken cancellationToken = this.shutdownCts.getToken(); WorkerTask partitionSupervisorTask = new WorkerTask(lease, () -> { partitionSupervisor.run(cancellationToken) .onErrorResume...
logger.debug("Partition %s: processing canceled.", lease.getLeaseToken());
private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lease lease) { CancellationToken cancellationToken = this.shutdownCts.getToken(); WorkerTask partitionSupervisorTask = new WorkerTask(lease, () -> { partitionSupervisor.run(cancellationToken) .onErrorResume(throwable -> { if (throwable instanc...
class PartitionControllerImpl implements PartitionController { private final Logger logger = LoggerFactory.getLogger(PartitionControllerImpl.class); private final Map<String, WorkerTask> currentlyOwnedPartitions = new ConcurrentHashMap<>(); private final LeaseContainer leaseContainer; private final LeaseManager leaseMa...
class PartitionControllerImpl implements PartitionController { private static final Logger logger = LoggerFactory.getLogger(PartitionControllerImpl.class); private final Map<String, WorkerTask> currentlyOwnedPartitions = new ConcurrentHashMap<>(); private final LeaseContainer leaseContainer; private final LeaseManager ...
This doesn't log what you intend. `%s` is for String.format not for slfj4 logger. slf4j logger doesn't understand `%s` placeholder please fix. https://www.slf4j.org/manual.html
private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lease lease) { PartitionControllerImpl self = this; CancellationToken cancellationToken = this.shutdownCts.getToken(); WorkerTask partitionSupervisorTask = new WorkerTask(lease, () -> { partitionSupervisor.run(cancellationToken) .onErrorResume...
logger.warn("Partition %s: processing failed.", lease.getLeaseToken(), throwable);
private WorkerTask processPartition(PartitionSupervisor partitionSupervisor, Lease lease) { CancellationToken cancellationToken = this.shutdownCts.getToken(); WorkerTask partitionSupervisorTask = new WorkerTask(lease, () -> { partitionSupervisor.run(cancellationToken) .onErrorResume(throwable -> { if (throwable instanc...
class PartitionControllerImpl implements PartitionController { private final Logger logger = LoggerFactory.getLogger(PartitionControllerImpl.class); private final Map<String, WorkerTask> currentlyOwnedPartitions = new ConcurrentHashMap<>(); private final LeaseContainer leaseContainer; private final LeaseManager leaseMa...
class PartitionControllerImpl implements PartitionController { private static final Logger logger = LoggerFactory.getLogger(PartitionControllerImpl.class); private final Map<String, WorkerTask> currentlyOwnedPartitions = new ConcurrentHashMap<>(); private final LeaseContainer leaseContainer; private final LeaseManager ...
why are we creating threads here?! we should rely on what the reactor stream platform provide rather than creating our own threads.
public Mono<Void> start() { PartitionLoadBalancerImpl self = this; synchronized (lock) { if (this.started) { throw new IllegalStateException("Partition load balancer already started"); } this.started = true; this.cancellationTokenSource = new CancellationTokenSource(); } return Mono.fromRunnable( () -> { Thread thread ...
Thread thread = new Thread(() -> self.run(self.cancellationTokenSource.getToken()).subscribe());
public Mono<Void> start() { synchronized (lock) { if (this.started) { throw new IllegalStateException("Partition load balancer already started"); } this.started = true; this.cancellationTokenSource = new CancellationTokenSource(); } return Mono.fromRunnable( () -> { scheduler.schedule(() -> this.run(this.cancellationTo...
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalanci...
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalanci...
I don't think `self` is needed here at all. The only place `this` is ambigous is when you have an inner class. which is not the case here. Please remove `self`.
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { AutoCheckpointer self = this; return self.observer.processChanges(context, docs) .then(self.afterProcessChanges(context)); }
AutoCheckpointer self = this;
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .then(this.afterProcessChanges(context)); }
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; private ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) ...
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private volatile int processedDocCount; private volatile ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedO...
I don't think `self` is needed here at all. The only place `this` is ambigous is when you have an inner class. which is not the case here. Please remove `self`.
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { AutoCheckpointer self = this; self.processedDocCount ++; if (self.isCheckpointNeeded()) { return context.checkpoint() .doOnSuccess((Void) -> { self.processedDocCount = 0; self.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }); } retu...
AutoCheckpointer self = this;
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { this.processedDocCount ++; if (this.isCheckpointNeeded()) { return context.checkpoint() .doOnSuccess((Void) -> { this.processedDocCount = 0; this.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }); } return Mono.empty(); }
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; private ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) ...
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private volatile int processedDocCount; private volatile ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedO...
I don't think `self` is needed here at all. The only place `this` is ambiguous is when you have an inner class. which is not the case here. Please remove `self`.
public Mono<Void> initialize() { BootstrapperImpl self = this; self.isInitialized = false; return Mono.just(self) .flatMap( value -> self.leaseStore.isInitialized()) .flatMap(initialized -> { self.isInitialized = initialized; if (initialized) { return Mono.empty(); } else { return self.leaseStore.acquireInitializationL...
self.isInitialized = false;
public Mono<Void> initialize() { this.isInitialized = false; return Mono.just(this) .flatMap( value -> this.leaseStore.isInitialized()) .flatMap(initialized -> { this.isInitialized = initialized; if (initialized) { return Mono.empty(); } else { return this.leaseStore.acquireInitializationLock(this.lockTime) .flatMap(lo...
class BootstrapperImpl implements Bootstrapper { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final PartitionSynchronizer synchronizer; private final LeaseStore leaseStore; private final Duration lockTime; private final Duration sleepTime; private boolean isInitialized; private...
class BootstrapperImpl implements Bootstrapper { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final PartitionSynchronizer synchronizer; private final LeaseStore leaseStore; private final Duration lockTime; private final Duration sleepTime; private volatile boolean isInitialized...
We create the corresponding workers for each partition range dynamically and they can go away based on changes to load balancing or splitting. Using reactor streams is an alternative that I'm still exploring outside of this PR.
public Mono<Void> start() { PartitionLoadBalancerImpl self = this; synchronized (lock) { if (this.started) { throw new IllegalStateException("Partition load balancer already started"); } this.started = true; this.cancellationTokenSource = new CancellationTokenSource(); } return Mono.fromRunnable( () -> { Thread thread ...
Thread thread = new Thread(() -> self.run(self.cancellationTokenSource.getToken()).subscribe());
public Mono<Void> start() { synchronized (lock) { if (this.started) { throw new IllegalStateException("Partition load balancer already started"); } this.started = true; this.cancellationTokenSource = new CancellationTokenSource(); } return Mono.fromRunnable( () -> { scheduler.schedule(() -> this.run(this.cancellationTo...
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalanci...
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalanci...
We need to loop/wait before making another check to retrieve the state. Can you please recommend another way to do this in a non-blocking fashion?
private Mono<Void> run(CancellationToken cancellationToken) { PartitionLoadBalancerImpl self = this; return Flux.just(self) .flatMap(value -> self.leaseContainer.getAllLeases()) .collectList() .flatMap(allLeases -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); List<Lease> leasesToTake = self.p...
Thread.sleep(100);
private Mono<Void> run(CancellationToken cancellationToken) { return Flux.just(this) .flatMap(value -> this.leaseContainer.getAllLeases()) .collectList() .flatMap(allLeases -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); List<Lease> leasesToTake = this.partitionLoadBalancingStrategy.selectLea...
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalanci...
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalanci...
In the more general context, "this" in the presence of lambdas is tricky and could lead to bugs. I've probably had such case here as well before settling to the final code.
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { AutoCheckpointer self = this; return self.observer.processChanges(context, docs) .then(self.afterProcessChanges(context)); }
AutoCheckpointer self = this;
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .then(this.afterProcessChanges(context)); }
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; private ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) ...
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private volatile int processedDocCount; private volatile ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedO...
In this particular case we want to "block" the current thread since the lock was acquired by another instance of the CFP and we have to wait until it finishes initializing the lease container. I'll call "delayElement()" on the return as an alternative to Thread.sleep().
public Mono<Void> initialize() { BootstrapperImpl self = this; self.isInitialized = false; return Mono.just(self) .flatMap( value -> self.leaseStore.isInitialized()) .flatMap(initialized -> { self.isInitialized = initialized; if (initialized) { return Mono.empty(); } else { return self.leaseStore.acquireInitializationL...
Thread.sleep(self.sleepTime.toMillis());
public Mono<Void> initialize() { this.isInitialized = false; return Mono.just(this) .flatMap( value -> this.leaseStore.isInitialized()) .flatMap(initialized -> { this.isInitialized = initialized; if (initialized) { return Mono.empty(); } else { return this.leaseStore.acquireInitializationLock(this.lockTime) .flatMap(lo...
class BootstrapperImpl implements Bootstrapper { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final PartitionSynchronizer synchronizer; private final LeaseStore leaseStore; private final Duration lockTime; private final Duration sleepTime; private boolean isInitialized; private...
class BootstrapperImpl implements Bootstrapper { private final Logger logger = LoggerFactory.getLogger(BootstrapperImpl.class); private final PartitionSynchronizer synchronizer; private final LeaseStore leaseStore; private final Duration lockTime; private final Duration sleepTime; private volatile boolean isInitialized...
As discussed with @JonathanGiles it isn't likely the right choice to throw an exception here as having a null HttpClient is valid for the builder.
public ConfigurationClientBuilder httpClient(HttpClient client) { this.httpClient = client; return this; }
this.httpClient = client;
public ConfigurationClientBuilder httpClient(HttpClient client) { if (this.httpClient != null && client == null) { logger.info("HttpClient is being set to 'null' when it was previously configured."); } this.httpClient = client; return this; }
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...
Take a look at `Flux.repeat()` and `Flux.takeUntil()` you can build a non-blocking while loop using them.
private Mono<Void> run(CancellationToken cancellationToken) { PartitionLoadBalancerImpl self = this; return Flux.just(self) .flatMap(value -> self.leaseContainer.getAllLeases()) .collectList() .flatMap(allLeases -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); List<Lease> leasesToTake = self.p...
Thread.sleep(100);
private Mono<Void> run(CancellationToken cancellationToken) { return Flux.just(this) .flatMap(value -> this.leaseContainer.getAllLeases()) .collectList() .flatMap(allLeases -> { if (cancellationToken.isCancellationRequested()) return Mono.empty(); List<Lease> leasesToTake = this.partitionLoadBalancingStrategy.selectLea...
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalanci...
class PartitionLoadBalancerImpl implements PartitionLoadBalancer { private final Logger logger = LoggerFactory.getLogger(PartitionLoadBalancerImpl.class); private final PartitionController partitionController; private final LeaseContainer leaseContainer; private final PartitionLoadBalancingStrategy partitionLoadBalanci...
`self=this` pattern is more for javascript. We are using lambdas throughout the sdk with `this` with no issues. `this` will be ambiguous in the presence of inner classes/outer class, but you are not using any inner class here. Please remove `self=this` here and elsewhere, and use `this`
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { AutoCheckpointer self = this; return self.observer.processChanges(context, docs) .then(self.afterProcessChanges(context)); }
AutoCheckpointer self = this;
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .then(this.afterProcessChanges(context)); }
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; private ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) ...
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private volatile int processedDocCount; private volatile ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedO...
`self=this` pattern is more for javascript. We are using lambdas throughout the sdk with `this` with no issues. `this` will be ambiguous in the presence of inner classes/outer class, but you are not using any inner class here. Please remove `self=this` here and elsewhere, and use `this`
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { final AutoCheckpointer self = this; self.processedDocCount ++; if (self.isCheckpointNeeded()) { return context.checkpoint() .doOnSuccess((Void) -> { self.processedDocCount = 0; self.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }); ...
final AutoCheckpointer self = this;
private Mono<Void> afterProcessChanges(ChangeFeedObserverContext context) { this.processedDocCount ++; if (this.isCheckpointNeeded()) { return context.checkpoint() .doOnSuccess((Void) -> { this.processedDocCount = 0; this.lastCheckpointTime = ZonedDateTime.now(ZoneId.of("UTC")); }); } return Mono.empty(); }
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private int processedDocCount; private ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedObserver observer) ...
class AutoCheckpointer implements ChangeFeedObserver { private final CheckpointFrequency checkpointFrequency; private final ChangeFeedObserver observer; private volatile int processedDocCount; private volatile ZonedDateTime lastCheckpointTime; public AutoCheckpointer(CheckpointFrequency checkpointFrequency, ChangeFeedO...
this doesn't give you what you intend. you should use slf4j place holder not `%s` please fix everywhere. slf4j will print out `%s` as is no substitution. https://www.slf4j.org/manual.html
public Mono<Void> inspect(HealthMonitoringRecord record) { return Mono.fromRunnable(() -> { if (record.getSeverity() == HealthMonitoringRecord.HealthSeverity.ERROR) { logger.error("Unhealthiness detected in the operation %s for %s.", record.operation.name(), record.lease.getId(), record.throwable); } }); }
logger.error("Unhealthiness detected in the operation %s for %s.", record.operation.name(), record.lease.getId(), record.throwable);
public Mono<Void> inspect(HealthMonitoringRecord record) { return Mono.fromRunnable(() -> { if (record.getSeverity() == HealthMonitoringRecord.HealthSeverity.ERROR) { logger.error("Unhealthiness detected in the operation {} for {}.", record.operation.name(), record.lease.getId(), record.throwable); } }); }
class TraceHealthMonitor implements HealthMonitor { private final Logger logger = LoggerFactory.getLogger(TraceHealthMonitor.class); @Override }
class TraceHealthMonitor implements HealthMonitor { private final Logger logger = LoggerFactory.getLogger(TraceHealthMonitor.class); @Override }
If someone creates a key locally and passes it as JsonWebKey, i.e key doesn't exist in KV, for example an Oct Key. We wouldn't have any key Id associated with it. will not have info about the vault url to create service client / send requests to. Should we enforce user to always specify vault endpoint in the Cryptogr...
private boolean serviceCryptoAvailable(){ return serviceClient != null ; }
}
private boolean serviceCryptoAvailable() { return serviceClient != null; }
class RsaKeyCryptographyClient { private CryptographyServiceClient serviceClient; private KeyPair keyPair; /* * Creates a RsaKeyCryptographyClient that uses {@code serviceClient) to service requests * * @param keyPair the key pair to use for cryptography operations. */ RsaKeyCryptographyClient(CryptographyServiceClient...
class RsaKeyCryptographyClient extends LocalKeyCryptographyClient { private KeyPair keyPair; /* * Creates a RsaKeyCryptographyClient that uses {@code serviceClient) to service requests * * @param keyPair the key pair to use for cryptography operations. */ RsaKeyCryptographyClient(CryptographyServiceClient serviceClient...
you missed this. "%s" won't work for slf4j.
public Mono<Void> inspect(HealthMonitoringRecord record) { return Mono.fromRunnable(() -> { if (record.getSeverity() == HealthMonitoringRecord.HealthSeverity.ERROR) { logger.error("Unhealthiness detected in the operation %s for %s.", record.operation.name(), record.lease.getId(), record.throwable); } }); }
logger.error("Unhealthiness detected in the operation %s for %s.", record.operation.name(), record.lease.getId(), record.throwable);
public Mono<Void> inspect(HealthMonitoringRecord record) { return Mono.fromRunnable(() -> { if (record.getSeverity() == HealthMonitoringRecord.HealthSeverity.ERROR) { logger.error("Unhealthiness detected in the operation {} for {}.", record.operation.name(), record.lease.getId(), record.throwable); } }); }
class TraceHealthMonitor implements HealthMonitor { private final Logger logger = LoggerFactory.getLogger(TraceHealthMonitor.class); @Override }
class TraceHealthMonitor implements HealthMonitor { private final Logger logger = LoggerFactory.getLogger(TraceHealthMonitor.class); @Override }
please add a message to the RuntimeException.
public Mono<Lease> updateLease(Lease cachedLease, CosmosItem itemLink, CosmosItemRequestOptions requestOptions, Function<Lease, Lease> updateLease) { Lease arrayLease[] = {cachedLease}; arrayLease[0] = updateLease.apply(cachedLease); if (arrayLease[0] == null) { return Mono.empty(); } arrayLease[0].setTimestamp(ZonedDa...
throw new RuntimeException("");
public Mono<Lease> updateLease(Lease cachedLease, CosmosItem itemLink, CosmosItemRequestOptions requestOptions, Function<Lease, Lease> updateLease) { Lease arrayLease[] = {cachedLease}; arrayLease[0] = updateLease.apply(cachedLease); if (arrayLease[0] == null) { return Mono.empty(); } arrayLease[0].setTimestamp(ZonedDa...
class DocumentServiceLeaseUpdaterImpl implements ServiceItemLeaseUpdater { private final Logger logger = LoggerFactory.getLogger(DocumentServiceLeaseUpdaterImpl.class); private final int RETRY_COUNT_ON_CONFLICT = 5; private final ChangeFeedContextClient client; public DocumentServiceLeaseUpdaterImpl(ChangeFeedContextCl...
class DocumentServiceLeaseUpdaterImpl implements ServiceItemLeaseUpdater { private final Logger logger = LoggerFactory.getLogger(DocumentServiceLeaseUpdaterImpl.class); private final int RETRY_COUNT_ON_CONFLICT = 5; private final ChangeFeedContextClient client; public DocumentServiceLeaseUpdaterImpl(ChangeFeedContextCl...
No, the builder should just take a JWK or a Key ID like you have now. It's possible that you could enforce that the JWK has valid kid field but I think what you have here is good for now.
private boolean serviceCryptoAvailable(){ return serviceClient != null ; }
}
private boolean serviceCryptoAvailable() { return serviceClient != null; }
class RsaKeyCryptographyClient { private CryptographyServiceClient serviceClient; private KeyPair keyPair; /* * Creates a RsaKeyCryptographyClient that uses {@code serviceClient) to service requests * * @param keyPair the key pair to use for cryptography operations. */ RsaKeyCryptographyClient(CryptographyServiceClient...
class RsaKeyCryptographyClient extends LocalKeyCryptographyClient { private KeyPair keyPair; /* * Creates a RsaKeyCryptographyClient that uses {@code serviceClient) to service requests * * @param keyPair the key pair to use for cryptography operations. */ RsaKeyCryptographyClient(CryptographyServiceClient serviceClient...
I think if you create the scheduler/executorservice you will be responsible for disposing it as well. Please make sure we are doing the proper cleanup scheduler/executorservice on stop/shutdown
public PartitionSupervisorImpl(Lease lease, ChangeFeedObserver observer, PartitionProcessor processor, LeaseRenewer renewer, Scheduler scheduler) { this.lease = lease; this.observer = observer; this.processor = processor; this.renewer = renewer; this.scheduler = scheduler; if (scheduler == null) { this.scheduler = Sche...
this.scheduler = Schedulers.elastic();
public PartitionSupervisorImpl(Lease lease, ChangeFeedObserver observer, PartitionProcessor processor, LeaseRenewer renewer, Scheduler scheduler) { this.lease = lease; this.observer = observer; this.processor = processor; this.renewer = renewer; this.scheduler = scheduler; if (scheduler == null) { this.scheduler = Sche...
class PartitionSupervisorImpl implements PartitionSupervisor, Closeable { private final Lease lease; private final ChangeFeedObserver observer; private final PartitionProcessor processor; private final LeaseRenewer renewer; private CancellationTokenSource renewerCancellation; private CancellationTokenSource processorCa...
class PartitionSupervisorImpl implements PartitionSupervisor, Closeable { private final Lease lease; private final ChangeFeedObserver observer; private final PartitionProcessor processor; private final LeaseRenewer renewer; private CancellationTokenSource renewerCancellation; private CancellationTokenSource processorCa...
here and elsewhere. You have two concurrent threads. thread1: does the checking here if there is any failure thread2: sets the exception. I think we have a bug here around thread2 seeing thread1 most recent changes. as the resultException is not set atomically by thread2. please fix in all places.
public Mono<Void> run(CancellationToken shutdownToken) { this.resultException = null; ChangeFeedObserverContext context = new ChangeFeedObserverContextImpl(this.lease.getLeaseToken()); this.observer.open(context); this.processorCancellation = new CancellationTokenSource(); this.scheduler.schedule(() -> this.processor.r...
.repeat( () -> !shutdownToken.isCancellationRequested() && this.processor.getResultException() == null && this.renewer.getResultException() == null)
public Mono<Void> run(CancellationToken shutdownToken) { this.resultException = null; ChangeFeedObserverContext context = new ChangeFeedObserverContextImpl(this.lease.getLeaseToken()); this.observer.open(context); this.processorCancellation = new CancellationTokenSource(); this.scheduler.schedule(() -> this.processor.r...
class PartitionSupervisorImpl implements PartitionSupervisor, Closeable { private final Lease lease; private final ChangeFeedObserver observer; private final PartitionProcessor processor; private final LeaseRenewer renewer; private CancellationTokenSource renewerCancellation; private CancellationTokenSource processorCa...
class PartitionSupervisorImpl implements PartitionSupervisor, Closeable { private final Lease lease; private final ChangeFeedObserver observer; private final PartitionProcessor processor; private final LeaseRenewer renewer; private CancellationTokenSource renewerCancellation; private CancellationTokenSource processorCa...
IMO, it is better to keep the `private static string label` for the error message, having strings like this is not good for maintenance. What about having 3 static strings ``` private static String EXTERNAL_DEPEPENDENCY_ERROR_TITLE = "Class ''%s'', is a class from external dependency. . You should not use it as a"; pri...
private void checkNoExternalDependencyExposed(DetailAST methodDefToken) { final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (!accessModifier.equals(AccessModifier.PUBLIC) && !acces...
(token, parameterTypeName) -> log(token, String.format("Class ''%s'', is a class from external dependency. You should not use it as a method argument type.", parameterTypeName)));
private void checkNoExternalDependencyExposed(DetailAST methodDefToken) { final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (!accessModifier.equals(AccessModifier.PUBLIC) && !acces...
class and value is the full package path of class. final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF...
class and value is the full package path of class. final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF...
Agree on putting common string out as private static final String. For the "return type" and "argument type", because they are only used once. It should not necessary to add those two fields.
private void checkNoExternalDependencyExposed(DetailAST methodDefToken) { final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (!accessModifier.equals(AccessModifier.PUBLIC) && !acces...
(token, parameterTypeName) -> log(token, String.format("Class ''%s'', is a class from external dependency. You should not use it as a method argument type.", parameterTypeName)));
private void checkNoExternalDependencyExposed(DetailAST methodDefToken) { final DetailAST modifiersToken = methodDefToken.findFirstToken(TokenTypes.MODIFIERS); final AccessModifier accessModifier = CheckUtil.getAccessModifierFromModifiersToken(modifiersToken); if (!accessModifier.equals(AccessModifier.PUBLIC) && !acces...
class and value is the full package path of class. final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF...
class and value is the full package path of class. final String importClassPath = FullIdent.createFullIdentBelow(token).getText(); final String className = importClassPath.substring(importClassPath.lastIndexOf(".") + 1); simpleClassNameToQualifiedNameMap.put(className, importClassPath); break; case TokenTypes.CLASS_DEF...
getKey might fail if the calling principal doesn't have the key_get permission. This should be handled and default to calling the service for all crypto calls when no key is avialable.
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); if(key == null){ this.key = getKey().block().value().keyMaterial(); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.e...
}
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...
You might consider creating a common abstract base class for all the cryptography client implementations. Then you could just have field, something like implCryptoClient, and avoid having this switch statement in every method.
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); if(key == null){ this.key = getKey().block().value().keyMaterial(); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.e...
}
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...
Yeah, I started doing this refactor in the morning. will push soon.
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); if(key == null){ this.key = getKey().block().value().keyMaterial(); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.e...
}
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...
What is the scenario where serviceClient is null? Shouldn't service crypto always be available, since these instances are created by the CryptographyClient?
private boolean serviceCryptoAvailable(){ return serviceClient != null ; }
}
private boolean serviceCryptoAvailable() { return serviceClient != null; }
class RsaKeyCryptographyClient { private CryptographyServiceClient serviceClient; private KeyPair keyPair; /* * Creates a RsaKeyCryptographyClient that uses {@code serviceClient) to service requests * * @param keyPair the key pair to use for cryptography operations. */ RsaKeyCryptographyClient(CryptographyServiceClient...
class RsaKeyCryptographyClient extends LocalKeyCryptographyClient { private KeyPair keyPair; /* * Creates a RsaKeyCryptographyClient that uses {@code serviceClient) to service requests * * @param keyPair the key pair to use for cryptography operations. */ RsaKeyCryptographyClient(CryptographyServiceClient serviceClient...
Just curious, why are we using `parallelStream()` instead of regular `stream()`? are we making any network calls?
private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) { return Mono.fromRunnable(() -> { logger.info("Starting load balancer"); Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1(); List<String> partitionIds = tuple.getT2(); if (ImplUtils.isNullOrEmpty(partit...
String partitionToClaim = partitionIds.parallelStream()
private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) { return Mono.fromRunnable(() -> { logger.info("Starting load balancer"); Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1(); List<String> partitionIds = tuple.getT2(); if (ImplUtils.isNullOrEmpty(partit...
class PartitionBasedLoadBalancer { private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class); private final String eventHubName; private final String consumerGroupName; private final PartitionManager partitionManager; private final EventHub...
class PartitionBasedLoadBalancer { private static final Random RANDOM = new Random(); private final ClientLogger logger = new ClientLogger(PartitionBasedLoadBalancer.class); private final String eventHubName; private final String consumerGroupName; private final PartitionManager partitionManager; private final EventHub...
added the logic to handle this issue and default to service api if key not available locally.
Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) { Objects.requireNonNull(algorithm); if(key == null){ this.key = getKey().block().value().keyMaterial(); } if (!checkKeyPermissions(this.key.keyOps(), KeyOperation.ENCRYPT)){ return Mono.e...
}
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...
`logger.logAndThrow()` instead of throwing. Update all other places in this java file.
public byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException { hmac.update(input); byte[] hash = hmac.doFinal(aadLength); byte[] tag = new byte[hmacKey.length]; System.arraycopy(hash, 0, tag, 0, hmacKey.length); if (!ByteExtensions.sequenceEqua...
throw new IllegalArgumentException("Data is not authentic");
public byte[] doFinal(byte[] input) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException { hmac.update(input); byte[] hash = hmac.doFinal(aadLength); byte[] tag = new byte[hmacKey.length]; System.arraycopy(hash, 0, tag, 0, hmacKey.length); if (!ByteExtensions.sequenceEqua...
class AesCbcHmacSha2Decryptor implements IAuthenticatedCryptoTransform { final byte[] aadLength; final Mac hmac; final byte[] hmacKey; final ICryptoTransform inner; byte[] tag; AesCbcHmacSha2Decryptor(String name, byte[] key, byte[] iv, byte[] authenticationData, byte[] authenticationTa...
class AesCbcHmacSha2Decryptor implements IAuthenticatedCryptoTransform { final byte[] aadLength; final Mac hmac; final byte[] hmacKey; final ICryptoTransform inner; final ClientLogger logger = new ClientLogger(AesCbcHmacSha2Decryptor.class); byte[] tag; AesCbcHmacSha2Decryptor(String name, byte[] key, byte[] iv, byte[]...
Don't use `printStackTrace()`. Wrap it in `IllegalArgumentException` and throw or if you don't want to throw, just log warning.
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...
e.printStackTrace();
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...
Sync clients cannot use `withContext`. You need to explicitly add a `Context` to the API args. Note that `Context` is supported only for APIs that return `Response<T>`.
public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return withContext(context -> client.encrypt(algorithm, plaintext, context, iv, authenticationData)).block(); }
return withContext(context -> client.encrypt(algorithm, plaintext, context, iv, authenticationData)).block();
public EncryptResult encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, byte[] iv, byte[] authenticationData) { return encrypt(algorithm, plaintext, iv, authenticationData, 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...