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 |
|---|---|---|---|---|---|
fixed. | Mono<DecryptResult> decryptAsync(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context, JsonWebKey key) {
throw new UnsupportedOperationException("Decrypt operaiton is not supported for EC key");
} | throw new UnsupportedOperationException("Decrypt operaiton is not supported for EC key"); | Mono<DecryptResult> decryptAsync(EncryptionAlgorithm algorithm, byte[] cipherText, byte[] iv, byte[] authenticationData, byte[] authenticationTag, Context context, JsonWebKey key) {
throw new UnsupportedOperationException("Decrypt operation is not supported for EC key");
} | class EcKeyCryptographyClient {
private KeyPair keyPair;
private CryptographyServiceClient serviceClient;
private Provider provider;
/**
* Creates a EcKeyCryptographyClient that uses {@code service} to service requests
*
* @param serviceClient the client to use for service side cryptography operations.
*/
EcKeyCryptogr... | class EcKeyCryptographyClient extends LocalKeyCryptographyClient {
private KeyPair keyPair;
private CryptographyServiceClient serviceClient;
private Provider provider;
/**
* Creates a EcKeyCryptographyClient that uses {@code service} to service requests
*
* @param serviceClient the client to use for service side crypto... |
updated. | public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
return client.wrapKey(algorithm, key, Context.NONE).block();
} | return client.wrapKey(algorithm, key, Context.NONE).block(); | public KeyWrapResult wrapKey(KeyWrapAlgorithm algorithm, byte[] key) {
return wrapKey(algorithm, key, Context.NONE);
} | class CryptographyClient {
private CryptographyAsyncClient client;
/**
* Creates a KeyClient that uses {@code pipeline} to service requests
*
* @param client The {@link CryptographyAsyncClient} that the client routes its request through.
*/
CryptographyClient(CryptographyAsyncClient client) {
this.client = client;
}
/*... | class CryptographyClient {
private final CryptographyAsyncClient client;
/**
* Creates a KeyClient that uses {@code pipeline} to service requests
*
* @param client The {@link CryptographyAsyncClient} that the client routes its request through.
*/
CryptographyClient(CryptographyAsyncClient client) {
this.client = client... |
That works too. | private void unpackAndValidateId(String keyId) {
if (keyId != null && keyId.length() > 0) {
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);
version = (tokens.length >= 4 ? tokens[3] : null);
if... | if (keyId != null && keyId.length() > 0) { | private void unpackAndValidateId(String keyId) {
if (ImplUtils.isNullOrEmpty(keyId)) {
throw new IllegalArgumentException("Key Id is invalid");
}
try {
URL url = new URL(keyId);
String[] tokens = url.getPath().split("/");
String endpoint = url.getProtocol() + ":
String keyName = (tokens.length >= 3 ? tokens[2] : null);... | class CryptographyAsyncClient {
private JsonWebKey key;
private CryptographyService service;
private String version;
private EcKeyCryptographyClient ecKeyCryptographyClient;
private RsaKeyCryptographyClient rsaKeyCryptographyClient;
private CryptographyServiceClient cryptographyServiceClient;
private SymmetricKeyCrypto... | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
private JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new Clien... |
because the return type is void. | Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) {
Objects.requireNonNull(algorithm);
boolean keyAvailableLocally = ensureValidKeyAvailable();
if(!keyAvailableLocally) {
return cryptographyServiceClient.encrypt(algorithm, plaintext, cont... | throw new UnsupportedOperationException(String.format("Encrypt Async is not allowed for Key Type: %s", key.kty().toString())); | Mono<EncryptResult> encrypt(EncryptionAlgorithm algorithm, byte[] plaintext, Context context, byte[] iv, byte[] authenticationData) {
Objects.requireNonNull(algorithm, "Encryption algorithm cannot be null.");
Objects.requireNonNull(plaintext, "Plain text content to be encrypted cannot be null.");
boolean keyAvailableLo... | class CryptographyAsyncClient {
private JsonWebKey key;
private CryptographyService service;
private String version;
private EcKeyCryptographyClient ecKeyCryptographyClient;
private RsaKeyCryptographyClient rsaKeyCryptographyClient;
private CryptographyServiceClient cryptographyServiceClient;
private SymmetricKeyCrypto... | class CryptographyAsyncClient {
static final String KEY_VAULT_SCOPE = "https:
private JsonWebKey key;
private final CryptographyService service;
private final CryptographyServiceClient cryptographyServiceClient;
private LocalKeyCryptographyClient localKeyCryptographyClient;
private final ClientLogger logger = new Clien... |
If ANNOTATION is a child of MODIFIER use getFirstToken, it does what this for loop is doing. | private boolean hasServiceClientAnnotation(DetailAST classDefToken) {
final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS);
for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
if (ast.getType() != TokenTypes.ANNOTATION) {
continue;
}
final Detai... | for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { | private boolean hasServiceClientAnnotation(DetailAST classDefToken) {
final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS);
for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
if (ast.getType() != TokenTypes.ANNOTATION) {
continue;
}
final Detai... | class is annotated with @ServiceClient, false otherwise.
*/ | class is annotated with @ServiceClient, false otherwise.
*/ |
This check may not trigger when it should since async class can false-positive into the check above. I think we should change this a bit by having: ``` Java if (async name) { async checks; } else if (sync name) { sync checks; } else { naming error } | private void checkServiceClientNaming(DetailAST classDefToken) {
final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText();
if (isAsync && !className.endsWith(ASYNC_CLIENT)) {
log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient.", className));
}
if (!isAsy... | if (className.endsWith(ASYNC_CLIENT) && !isAsync) { | private void checkServiceClientNaming(DetailAST classDefToken) {
final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText();
if (isAsync && !className.endsWith(ASYNC_CLIENT)) {
log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient ", className));
}
if (!isAsy... | class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client.
*
* @param classDefToken the CLASS_DEF AST node
*/ | class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client.
*
* @param classDefToken the CLASS_DEF AST node
*/ |
Error message says `class must be named AsyncClient` but condition only check if name ends with this string. So, a name like `thisIsMySuperMethodAsyncClient` would be valid right? If yes, update the error message to say that `class name must end with this string. | private void checkServiceClientNaming(DetailAST classDefToken) {
final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText();
if (isAsync && !className.endsWith(ASYNC_CLIENT)) {
log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient.", className));
}
if (!isAsy... | if (isAsync && !className.endsWith(ASYNC_CLIENT)) { | private void checkServiceClientNaming(DetailAST classDefToken) {
final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText();
if (isAsync && !className.endsWith(ASYNC_CLIENT)) {
log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient ", className));
}
if (!isAsy... | class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client.
*
* @param classDefToken the CLASS_DEF AST node
*/ | class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client.
*
* @param classDefToken the CLASS_DEF AST node
*/ |
Do we want to make this if statements `else if` statements? Do we need to check all condition even after we find one as true? | private void checkServiceClientNaming(DetailAST classDefToken) {
final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText();
if (isAsync && !className.endsWith(ASYNC_CLIENT)) {
log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient.", className));
}
if (!isAsy... | if (className.endsWith(CLIENT) && !className.endsWith(ASYNC_CLIENT) && isAsync) { | private void checkServiceClientNaming(DetailAST classDefToken) {
final String className = classDefToken.findFirstToken(TokenTypes.IDENT).getText();
if (isAsync && !className.endsWith(ASYNC_CLIENT)) {
log(classDefToken, String.format("Async class ''%s'' must be named <ServiceName>AsyncClient ", className));
}
if (!isAsy... | class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client.
*
* @param classDefToken the CLASS_DEF AST node
*/ | class name of Service Client. It should be named <ServiceName>AsyncClient or <ServiceName>Client.
*
* @param classDefToken the CLASS_DEF AST node
*/ |
If the class does not have `@ServiceClient` annotation, is it possible to terminate this custom checkstyle evaluation i.e. no more calls to `visitToken()`? If that's possible, you could simplify the other switch cases by not having to check `if (!hasServiceClientAnnotation)` | public void visitToken(DetailAST token) {
switch (token.getType()) {
case TokenTypes.IMPORT:
addImportedClassPath(token);
break;
case TokenTypes.CLASS_DEF:
hasServiceClientAnnotation = hasServiceClientAnnotation(token);
if (!hasServiceClientAnnotation) {
return;
}
checkServiceClientNaming(token);
break;
case TokenTypes... | if (!hasServiceClientAnnotation) { | public void visitToken(DetailAST token) {
if (isImplPackage) {
return;
}
switch (token.getType()) {
case TokenTypes.PACKAGE_DEF:
String packageName = FullIdent.createFullIdent(token.findFirstToken(TokenTypes.DOT)).getText();
isImplPackage = packageName.contains(".implementation");
break;
case TokenTypes.CLASS_DEF:
hasS... | class if it returns a ''sync'' single value.";
private static final Set<String> COMMON_NAMING_PREFIX_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"upsert", "set", "create", "update", "replace", "delete", "add", "get", "list"
)));
private static boolean isAsync;
private static boolean hasServiceClientA... | class ServiceClientInstantiationCheck extends AbstractCheck {
private static final String SERVICE_CLIENT = "ServiceClient";
private static final String BUILDER = "builder";
private static final String ASYNC_CLIENT = "AsyncClient";
private static final String CLIENT = "Client";
private static final String IS_ASYNC = "is... |
I found no way to do an earlier termination of tree traversal, | public void visitToken(DetailAST token) {
switch (token.getType()) {
case TokenTypes.IMPORT:
addImportedClassPath(token);
break;
case TokenTypes.CLASS_DEF:
hasServiceClientAnnotation = hasServiceClientAnnotation(token);
if (!hasServiceClientAnnotation) {
return;
}
checkServiceClientNaming(token);
break;
case TokenTypes... | if (!hasServiceClientAnnotation) { | public void visitToken(DetailAST token) {
if (isImplPackage) {
return;
}
switch (token.getType()) {
case TokenTypes.PACKAGE_DEF:
String packageName = FullIdent.createFullIdent(token.findFirstToken(TokenTypes.DOT)).getText();
isImplPackage = packageName.contains(".implementation");
break;
case TokenTypes.CLASS_DEF:
hasS... | class if it returns a ''sync'' single value.";
private static final Set<String> COMMON_NAMING_PREFIX_SET = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"upsert", "set", "create", "update", "replace", "delete", "add", "get", "list"
)));
private static boolean isAsync;
private static boolean hasServiceClientA... | class ServiceClientInstantiationCheck extends AbstractCheck {
private static final String SERVICE_CLIENT = "ServiceClient";
private static final String BUILDER = "builder";
private static final String ASYNC_CLIENT = "AsyncClient";
private static final String CLIENT = "Client";
private static final String IS_ASYNC = "is... |
What's the reason of removing the null checking? | 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... |
Instead of making the traversal twice, assign to a local variable. `parameterToken.findFirstToken(TokenTypes.TYPE).findFirstToken(TokenTypes.IDENT)` | private void checkContextInRightPlace(DetailAST methodDefToken) {
final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS);
final String returnType = getReturnType(methodDefToken.findFirstToken(TokenTypes.TYPE), new StringBuilder()).toString();
final boolean containsTypeParameter = TokenUt... | && parameterToken.findFirstToken(TokenTypes.TYPE).findFirstToken(TokenTypes.IDENT) != null | private void checkContextInRightPlace(DetailAST methodDefToken) {
final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS);
final String returnType = getReturnType(methodDefToken.findFirstToken(TokenTypes.TYPE), new StringBuilder()).toString();
final boolean containsContextParameter = Toke... | class annotated with @ServiceClient should
* follow below rules:
* 1) Follows method naming pattern. Refer to Java Spec.
* 2) Methods should not have "Async" added to the method name.
* 3) The return type of async and sync clients should be as per guidelines:
* 3.1) The return type for async collection... | class annotated with @ServiceClient should
* follow below rules:
* 1) Follows method naming pattern. Refer to Java Spec.
* 2) Methods should not have "Async" added to the method name.
* 3) The return type of async and sync clients should be as per guidelines:
* 3.1) The return type for async collection... |
`containsTypeParameter` is a misleading name. I spent a minute trying to understand if the code was wrong because it wasn't looking for a type parameter. You're looking to see if it contains a parameter of type Context. `containsContextParameter` is better. | private void checkContextInRightPlace(DetailAST methodDefToken) {
final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS);
final String returnType = getReturnType(methodDefToken.findFirstToken(TokenTypes.TYPE), new StringBuilder()).toString();
final boolean containsTypeParameter = TokenUt... | final boolean containsTypeParameter = TokenUtil.findFirstTokenByPredicate(parametersToken, | private void checkContextInRightPlace(DetailAST methodDefToken) {
final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS);
final String returnType = getReturnType(methodDefToken.findFirstToken(TokenTypes.TYPE), new StringBuilder()).toString();
final boolean containsContextParameter = Toke... | class annotated with @ServiceClient should
* follow below rules:
* 1) Follows method naming pattern. Refer to Java Spec.
* 2) Methods should not have "Async" added to the method name.
* 3) The return type of async and sync clients should be as per guidelines:
* 3.1) The return type for async collection... | class annotated with @ServiceClient should
* follow below rules:
* 1) Follows method naming pattern. Refer to Java Spec.
* 2) Methods should not have "Async" added to the method name.
* 3) The return type of async and sync clients should be as per guidelines:
* 3.1) The return type for async collection... |
It's nice to have expression lambdas, but using `node.findFirstToken(TokenTypes.IDENT)` results in evaluating the same node twice. Assign to a local variable. | private boolean hasServiceClientAnnotation(DetailAST classDefToken) {
final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS);
final Optional<DetailAST> serviceClientAnnotationOption = TokenUtil.findFirstTokenByPredicate(modifiersToken,
node -> node.getType() == TokenTypes.ANNOTATION && node... | node -> node.getType() == TokenTypes.ANNOTATION && node.findFirstToken(TokenTypes.IDENT) != null | private boolean hasServiceClientAnnotation(DetailAST classDefToken) {
final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS);
final Optional<DetailAST> serviceClientAnnotationOption = TokenUtil.findFirstTokenByPredicate(modifiersToken,
node -> {
if (node.getType() != TokenTypes.ANNOTATION) ... | class is annotated with @ServiceClient, false otherwise.
*/ | class is annotated with @ServiceClient, false otherwise.
*/ |
What's the justification of not null here? I think make a default one or silence it would be better. | public ConfigurationClientBuilder httpLogDetailLevel(HttpLogDetailLevel logLevel) {
httpLogDetailLevel = Objects.requireNonNull(logLevel);
return this;
} | httpLogDetailLevel = Objects.requireNonNull(logLevel); | public ConfigurationClientBuilder httpLogDetailLevel(HttpLogDetailLevel logLevel) {
httpLogDetailLevel = Objects.requireNonNull(logLevel);
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... |
Unlike HttpClient and HttpPipeline there is no default handling for HttpLogDetailLevel in the builder. This will end up passing in a null logging level into the logging policy and that will end up throwing a NullPointerException during execution. So add this prevent a consumer from getting further into the call stack t... | public ConfigurationClientBuilder httpLogDetailLevel(HttpLogDetailLevel logLevel) {
httpLogDetailLevel = Objects.requireNonNull(logLevel);
return this;
} | httpLogDetailLevel = Objects.requireNonNull(logLevel); | public ConfigurationClientBuilder httpLogDetailLevel(HttpLogDetailLevel logLevel) {
httpLogDetailLevel = Objects.requireNonNull(logLevel);
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... |
This kind of horizontal shuffling should be reverted. | Mono<Response<String>> startCopyFromURLWithResponse(URL sourceURL, Metadata metadata, ModifiedAccessConditions sourceModifiedAccessConditions, BlobAccessConditions destAccessConditions, Context context) {
metadata = metadata == null ? new Metadata() : metadata;
sourceModifiedAccessConditions = sourceModifiedAccessCondi... | .sourceIfNoneMatch(sourceModifiedAccessConditions.ifNoneMatch()); | 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... |
Would we want to make the mapping function a function on the class? ``` private PagedResponseBase<ServiceListContainersSegmentHeaders, ContainerItem> mapContainerListing(ServicesListContainersSegmentResponse response) { return new PagedResponseBase<>(response.request(), response.statusCode(), response.headers(), ... | public PagedFlux<ContainerItem> listContainers(ListContainersOptions options) {
return new PagedFlux<>(
() -> listContainersSegment(null, options)
.map(response -> new PagedResponseBase<>(
response.request(),
response.statusCode(),
response.headers(),
response.value().containerItems(),
response.value().nextMarker(),
re... | .map(response -> new PagedResponseBase<>( | public PagedFlux<ContainerItem> listContainers(ListContainersOptions options) {
return listContainersWithOptionalTimeout(options, null);
} | class BlobServiceAsyncClient {
private final AzureBlobStorageImpl azureBlobStorage;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param azureBlobStorageBuilder the API client builder for blob storage API
*/
BlobServiceAsyncClient(AzureBlobStorageBuilder azureBlobStorageBuilder) {
t... | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param azureBlobStorage the API client for blob storage
*/
BlobServic... |
Same question about making this mapping a class level method, this would reduce all four of these blocks into a single place. | public PagedFlux<BlobItem> listBlobsFlat(ListBlobsOptions options) {
return new PagedFlux<>(
() -> listBlobsFlatSegment(null, options)
.map(response -> new PagedResponseBase<>(
response.request(),
response.statusCode(),
response.headers(),
response.value().segment().blobItems(),
response.value().nextMarker(),
response.... | .map(response -> new PagedResponseBase<>( | public PagedFlux<BlobItem> listBlobsFlat(ListBlobsOptions options) {
return listBlobsFlatWithOptionalTimeout(options, null);
} | class ContainerAsyncClient {
public static final String ROOT_CONTAINER_NAME = "$root";
public static final String STATIC_WEBSITE_CONTAINER_NAME = "$web";
public static final String LOG_CONTAINER_NAME = "$logs";
private final AzureBlobStorageImpl azureBlobStorage;
/**
* Package-private constructor for use by {@link Cont... | class ContainerAsyncClient {
public static final String ROOT_CONTAINER_NAME = "$root";
public static final String STATIC_WEBSITE_CONTAINER_NAME = "$web";
public static final String LOG_CONTAINER_NAME = "$logs";
private final ClientLogger logger = new ClientLogger(ContainerAsyncClient.class);
private final AzureBlobStor... |
Each of these functions has it's own `Function<String, Mono<PagedResponse<T>>>` to reuse the mapping into PagedResponseBase. | public PagedFlux<ContainerItem> listContainers(ListContainersOptions options) {
return new PagedFlux<>(
() -> listContainersSegment(null, options)
.map(response -> new PagedResponseBase<>(
response.request(),
response.statusCode(),
response.headers(),
response.value().containerItems(),
response.value().nextMarker(),
re... | .map(response -> new PagedResponseBase<>( | public PagedFlux<ContainerItem> listContainers(ListContainersOptions options) {
return listContainersWithOptionalTimeout(options, null);
} | class BlobServiceAsyncClient {
private final AzureBlobStorageImpl azureBlobStorage;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param azureBlobStorageBuilder the API client builder for blob storage API
*/
BlobServiceAsyncClient(AzureBlobStorageBuilder azureBlobStorageBuilder) {
t... | class BlobServiceAsyncClient {
private final ClientLogger logger = new ClientLogger(BlobServiceAsyncClient.class);
private final AzureBlobStorageImpl azureBlobStorage;
/**
* Package-private constructor for use by {@link BlobServiceClientBuilder}.
*
* @param azureBlobStorage the API client for blob storage
*/
BlobServic... |
Each of these functions has it's own `Function<String, Mono<PagedResponse<T>>>` to reuse the mapping into PagedResponseBase. | public PagedFlux<BlobItem> listBlobsFlat(ListBlobsOptions options) {
return new PagedFlux<>(
() -> listBlobsFlatSegment(null, options)
.map(response -> new PagedResponseBase<>(
response.request(),
response.statusCode(),
response.headers(),
response.value().segment().blobItems(),
response.value().nextMarker(),
response.... | .map(response -> new PagedResponseBase<>( | public PagedFlux<BlobItem> listBlobsFlat(ListBlobsOptions options) {
return listBlobsFlatWithOptionalTimeout(options, null);
} | class ContainerAsyncClient {
public static final String ROOT_CONTAINER_NAME = "$root";
public static final String STATIC_WEBSITE_CONTAINER_NAME = "$web";
public static final String LOG_CONTAINER_NAME = "$logs";
private final AzureBlobStorageImpl azureBlobStorage;
/**
* Package-private constructor for use by {@link Cont... | class ContainerAsyncClient {
public static final String ROOT_CONTAINER_NAME = "$root";
public static final String STATIC_WEBSITE_CONTAINER_NAME = "$web";
public static final String LOG_CONTAINER_NAME = "$logs";
private final ClientLogger logger = new ClientLogger(ContainerAsyncClient.class);
private final AzureBlobStor... |
nit: ownership that have not `been` modified | 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... | * Remove all partitions' ownership that have not be modified for a configuration period of time. This means | 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... |
```suggestion "'connectionString' contains an Event Hub name [%s]. Please use the" ``` | public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
if (ImplUtils.isNullOrEmpty(eventHubName)) {
throw new IllegalArgumentException("'eventHubName' cannot be null or empty");
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final... | "'connectionString' contains an Event Hub path [%s]. Please use the" | public EventHubClientBuilder connectionString(String connectionString, String eventHubName) {
if (ImplUtils.isNullOrEmpty(eventHubName)) {
throw new IllegalArgumentException("'eventHubName' cannot be null or empty");
}
final ConnectionStringProperties properties = new ConnectionStringProperties(connectionString);
final... | class EventHubClientBuilder {
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final RetryOptions DEFAULT_RETRY = new RetryOptions()
.tryTimeout(ClientConstants.OPERATION_TIMEOUT);
private TokenCredential credentials;
private Configuration configurati... | class EventHubClientBuilder {
private static final String AZURE_EVENT_HUBS_CONNECTION_STRING = "AZURE_EVENT_HUBS_CONNECTION_STRING";
private static final RetryOptions DEFAULT_RETRY = new RetryOptions()
.tryTimeout(ClientConstants.OPERATION_TIMEOUT);
private TokenCredential credentials;
private Configuration configurati... |
Do you know why the context.httpRequest already contained this header? I'm not sure if we're covering up an underlying issue (ie. not resetting the HTTP request context for each HTTP request) | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
String header = context.httpRequest().headers().value("User-Agent");
if (header == null || header.startsWith(DEFAULT_USER_AGENT_HEADER)) {
header = userAgent;
} else {
header = userAgent + " " + header;
}
context.httpReque... | if (header == null || header.startsWith(DEFAULT_USER_AGENT_HEADER)) { | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
String header = context.httpRequest().headers().value("User-Agent");
if (header == null || header.startsWith(DEFAULT_USER_AGENT_HEADER)) {
header = userAgent;
} else {
header = userAgent + " " + header;
}
context.httpReque... | class UserAgentPolicy implements HttpPipelinePolicy {
private static final String DEFAULT_USER_AGENT_HEADER = "azsdk-java";
private static final String USER_AGENT_FORMAT = DEFAULT_USER_AGENT_HEADER + "-%s/%s %s";
private static final String DISABLED_TELEMETRY_USER_AGENT_FORMAT = DEFAULT_USER_AGENT_HEADER + "-%s/%s";
pr... | class UserAgentPolicy implements HttpPipelinePolicy {
private static final String DEFAULT_USER_AGENT_HEADER = "azsdk-java";
private static final String USER_AGENT_FORMAT = DEFAULT_USER_AGENT_HEADER + "-%s/%s %s";
private static final String DISABLED_TELEMETRY_USER_AGENT_FORMAT = DEFAULT_USER_AGENT_HEADER + "-%s/%s";
pr... |
The header information was being maintained due to the call being captured as a Mono value, every time the Mono was mapped or filtered it would re-run it again and the context was being maintained. Outside of blowing everything away on a successful completion, which just feels risky to do, I feel that making the check ... | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
String header = context.httpRequest().headers().value("User-Agent");
if (header == null || header.startsWith(DEFAULT_USER_AGENT_HEADER)) {
header = userAgent;
} else {
header = userAgent + " " + header;
}
context.httpReque... | if (header == null || header.startsWith(DEFAULT_USER_AGENT_HEADER)) { | public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) {
String header = context.httpRequest().headers().value("User-Agent");
if (header == null || header.startsWith(DEFAULT_USER_AGENT_HEADER)) {
header = userAgent;
} else {
header = userAgent + " " + header;
}
context.httpReque... | class UserAgentPolicy implements HttpPipelinePolicy {
private static final String DEFAULT_USER_AGENT_HEADER = "azsdk-java";
private static final String USER_AGENT_FORMAT = DEFAULT_USER_AGENT_HEADER + "-%s/%s %s";
private static final String DISABLED_TELEMETRY_USER_AGENT_FORMAT = DEFAULT_USER_AGENT_HEADER + "-%s/%s";
pr... | class UserAgentPolicy implements HttpPipelinePolicy {
private static final String DEFAULT_USER_AGENT_HEADER = "azsdk-java";
private static final String USER_AGENT_FORMAT = DEFAULT_USER_AGENT_HEADER + "-%s/%s %s";
private static final String DISABLED_TELEMETRY_USER_AGENT_FORMAT = DEFAULT_USER_AGENT_HEADER + "-%s/%s";
pr... |
eventHubPath -> eventHubName | public EventProcessorAsyncClient createInstance() {
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
+ "SharedAccessKey={sharedAccessKey};EntityPath={eventHubPath}";
EventProcessorAsyncClient eventProcessorAsyncClient = new EventHubClientBuilder()
.connectionString(connectionSt... | + "SharedAccessKey={sharedAccessKey};EntityPath={eventHubPath}"; | public EventProcessorAsyncClient createInstance() {
String connectionString = "Endpoint={endpoint};SharedAccessKeyName={sharedAccessKeyName};"
+ "SharedAccessKey={sharedAccessKey};EntityPath={eventHubName}";
EventProcessorAsyncClient eventProcessorAsyncClient = new EventHubClientBuilder()
.connectionString(connectionSt... | class EventProcessorJavaDocCodeSamples {
/**
* Code snippet for showing how to create a new instance of {@link EventProcessorAsyncClient}.
*
* @return An instance of {@link EventProcessorAsyncClient}.
*/
/**
* Code snippet for showing how to start and stop an {@link EventProcessorAsyncClient}.
*/
public void startStopS... | class EventProcessorJavaDocCodeSamples {
/**
* Code snippet for showing how to create a new instance of {@link EventProcessorAsyncClient}.
*
* @return An instance of {@link EventProcessorAsyncClient}.
*/
/**
* Code snippet for showing how to start and stop an {@link EventProcessorAsyncClient}.
*/
public void startStopS... |
nit: inconsistent `final`. I don't see you re-setting this variable. | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | DetailAST methodDefToken = methodDefStack.peek(); | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
Consider using `AnnotationUtil.getAnnotation(...)` | private boolean hasImmutableAnnotation(DetailAST classDefToken) {
final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS);
for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
if (ast.getType() == TokenTypes.ANNOTATION) {
final DetailAST annotationI... | for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { | private boolean hasImmutableAnnotation(DetailAST classDefToken) {
DetailAST immutableAnnotation = AnnotationUtil.getAnnotation(classDefToken, IMMUTABLE_NOTATION);
return immutableAnnotation != null;
} | class is annotated with @Immutable, false otherwise.
*/ | class is annotated with {@literal @Immutable} |
This could be simplified using `TokenUtil.findFirstTokenByPredicate`. Similar with other instances. | private void checkForOnlyFinalFields(DetailAST objBlockToken) {
for (DetailAST ast = objBlockToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
if (TokenTypes.VARIABLE_DEF == ast.getType()) {
final DetailAST modifiersToken = ast.findFirstToken(TokenTypes.MODIFIERS);
if (!modifiersToken.branchContains(Tok... | for (DetailAST ast = objBlockToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { | private void checkForOnlyFinalFields(DetailAST objBlockToken) {
Optional<DetailAST> nonFinalFieldFound = TokenUtil.findFirstTokenByPredicate(objBlockToken,
node -> TokenTypes.VARIABLE_DEF == node.getType() && !node.branchContains(TokenTypes.FINAL)
&& !Utils.hasIllegalCombination(node.findFirstToken(TokenTypes.MODIFIERS... | class are final
*
* @param objBlockToken the OBJBLOCK AST node
*/ | class are final
*
* @param objBlockToken the OBJBLOCK AST node
*/ |
uff.. I didn't know about those Util classes!! Super util! thank you! Updating... | private boolean hasImmutableAnnotation(DetailAST classDefToken) {
final DetailAST modifiersToken = classDefToken.findFirstToken(TokenTypes.MODIFIERS);
for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
if (ast.getType() == TokenTypes.ANNOTATION) {
final DetailAST annotationI... | for (DetailAST ast = modifiersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { | private boolean hasImmutableAnnotation(DetailAST classDefToken) {
DetailAST immutableAnnotation = AnnotationUtil.getAnnotation(classDefToken, IMMUTABLE_NOTATION);
return immutableAnnotation != null;
} | class is annotated with @Immutable, false otherwise.
*/ | class is annotated with {@literal @Immutable} |
updated. this TokenUtil would've made everything easier since the beginning. :) | private void checkForOnlyFinalFields(DetailAST objBlockToken) {
for (DetailAST ast = objBlockToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
if (TokenTypes.VARIABLE_DEF == ast.getType()) {
final DetailAST modifiersToken = ast.findFirstToken(TokenTypes.MODIFIERS);
if (!modifiersToken.branchContains(Tok... | for (DetailAST ast = objBlockToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) { | private void checkForOnlyFinalFields(DetailAST objBlockToken) {
Optional<DetailAST> nonFinalFieldFound = TokenUtil.findFirstTokenByPredicate(objBlockToken,
node -> TokenTypes.VARIABLE_DEF == node.getType() && !node.branchContains(TokenTypes.FINAL)
&& !Utils.hasIllegalCombination(node.findFirstToken(TokenTypes.MODIFIERS... | class are final
*
* @param objBlockToken the OBJBLOCK AST node
*/ | class are final
*
* @param objBlockToken the OBJBLOCK AST node
*/ |
I think this can be simplified to: ```java node -> { return TokenTypes.VARIABLE_DEF == node.getType() && !node.branchContains(TokenTypes.FINAL) && !Utils.hasIllegalCombination(node.findFirstToken(TokenTypes.MODIFIERS)); } ``` | private void checkForOnlyFinalFields(DetailAST objBlockToken) {
Optional<DetailAST> nonFinalFieldFound = TokenUtil.findFirstTokenByPredicate(objBlockToken, (node) -> {
if (TokenTypes.VARIABLE_DEF == node.getType()) {
return !node.branchContains(TokenTypes.FINAL)
&& !Utils.hasIllegalCombination(node.findFirstToken(Token... | if (TokenTypes.VARIABLE_DEF == node.getType()) { | private void checkForOnlyFinalFields(DetailAST objBlockToken) {
Optional<DetailAST> nonFinalFieldFound = TokenUtil.findFirstTokenByPredicate(objBlockToken,
node -> TokenTypes.VARIABLE_DEF == node.getType() && !node.branchContains(TokenTypes.FINAL)
&& !Utils.hasIllegalCombination(node.findFirstToken(TokenTypes.MODIFIERS... | class are final
*
* @param objBlockToken the OBJBLOCK AST node
*/ | class are final
*
* @param objBlockToken the OBJBLOCK AST node
*/ |
For this util method, the javadocs specifies this should be for a variable node, but you never do any checks to ensure that this isn't some random node like CLASS_DEF. Also, why protected? | protected static boolean hasIllegalCombination(DetailAST modifiers) {
for (DetailAST modifier = modifiers.getFirstChild(); modifier != null; modifier = modifier.getNextSibling()) {
int modifierType = modifier.getType();
if (TokenTypes.ANNOTATION == modifierType) {
if (INVALID_FINAL_ANNOTATIONS.contains(modifier.findFir... | for (DetailAST modifier = modifiers.getFirstChild(); modifier != null; modifier = modifier.getNextSibling()) { | protected static boolean hasIllegalCombination(DetailAST modifiers) {
if (modifiers.getType() != TokenTypes.MODIFIERS) {
return false;
}
Optional<DetailAST> illegalCombination = TokenUtil.findFirstTokenByPredicate(modifiers, (node) -> {
final int type = node.getType();
return INVALID_FINAL_COMBINATION.contains(node.get... | class Utils {
private static final Set INVALID_FINAL_COMBINATION = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
TokenTypes.LITERAL_TRANSIENT,
TokenTypes.LITERAL_VOLATILE
)));
private static final Set INVALID_FINAL_ANNOTATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"JsonProperty"
)));
/**... | class Utils {
private static final Set INVALID_FINAL_COMBINATION = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
TokenTypes.LITERAL_TRANSIENT,
TokenTypes.LITERAL_VOLATILE
)));
private static final Set INVALID_FINAL_ANNOTATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"JsonProperty"
)));
/**... |
can be replaced with: `TokenUtil.findFirstTokenByPredicate(...)`. I think this could be simplified. ```java node -> { int modifierType = modifier.getType(); return INVALID_FINAL_COMBINATION.contains(modifierType) || (TokenTypes.ANNOTATION == modifierType && INVALID_FINAL_ANNOTATIONS.contains(modifier.fi... | protected static boolean hasIllegalCombination(DetailAST modifiers) {
for (DetailAST modifier = modifiers.getFirstChild(); modifier != null; modifier = modifier.getNextSibling()) {
int modifierType = modifier.getType();
if (TokenTypes.ANNOTATION == modifierType) {
if (INVALID_FINAL_ANNOTATIONS.contains(modifier.findFir... | for (DetailAST modifier = modifiers.getFirstChild(); modifier != null; modifier = modifier.getNextSibling()) { | protected static boolean hasIllegalCombination(DetailAST modifiers) {
if (modifiers.getType() != TokenTypes.MODIFIERS) {
return false;
}
Optional<DetailAST> illegalCombination = TokenUtil.findFirstTokenByPredicate(modifiers, (node) -> {
final int type = node.getType();
return INVALID_FINAL_COMBINATION.contains(node.get... | class Utils {
private static final Set INVALID_FINAL_COMBINATION = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
TokenTypes.LITERAL_TRANSIENT,
TokenTypes.LITERAL_VOLATILE
)));
private static final Set INVALID_FINAL_ANNOTATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"JsonProperty"
)));
/**... | class Utils {
private static final Set INVALID_FINAL_COMBINATION = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
TokenTypes.LITERAL_TRANSIENT,
TokenTypes.LITERAL_VOLATILE
)));
private static final Set INVALID_FINAL_ANNOTATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"JsonProperty"
)));
/**... |
yes, 👍 . updated | private void checkForOnlyFinalFields(DetailAST objBlockToken) {
Optional<DetailAST> nonFinalFieldFound = TokenUtil.findFirstTokenByPredicate(objBlockToken, (node) -> {
if (TokenTypes.VARIABLE_DEF == node.getType()) {
return !node.branchContains(TokenTypes.FINAL)
&& !Utils.hasIllegalCombination(node.findFirstToken(Token... | if (TokenTypes.VARIABLE_DEF == node.getType()) { | private void checkForOnlyFinalFields(DetailAST objBlockToken) {
Optional<DetailAST> nonFinalFieldFound = TokenUtil.findFirstTokenByPredicate(objBlockToken,
node -> TokenTypes.VARIABLE_DEF == node.getType() && !node.branchContains(TokenTypes.FINAL)
&& !Utils.hasIllegalCombination(node.findFirstToken(TokenTypes.MODIFIERS... | class are final
*
* @param objBlockToken the OBJBLOCK AST node
*/ | class are final
*
* @param objBlockToken the OBJBLOCK AST node
*/ |
@conniey , thanks for the comments! - protected to have it only available for same package `com.azure.tools.checkstyle.checks` No need to use it outside from there. All custom checks are added to this package. - I like your proposal with `findFirstTokenByPredicate()` . I will update it. | protected static boolean hasIllegalCombination(DetailAST modifiers) {
for (DetailAST modifier = modifiers.getFirstChild(); modifier != null; modifier = modifier.getNextSibling()) {
int modifierType = modifier.getType();
if (TokenTypes.ANNOTATION == modifierType) {
if (INVALID_FINAL_ANNOTATIONS.contains(modifier.findFir... | for (DetailAST modifier = modifiers.getFirstChild(); modifier != null; modifier = modifier.getNextSibling()) { | protected static boolean hasIllegalCombination(DetailAST modifiers) {
if (modifiers.getType() != TokenTypes.MODIFIERS) {
return false;
}
Optional<DetailAST> illegalCombination = TokenUtil.findFirstTokenByPredicate(modifiers, (node) -> {
final int type = node.getType();
return INVALID_FINAL_COMBINATION.contains(node.get... | class Utils {
private static final Set INVALID_FINAL_COMBINATION = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
TokenTypes.LITERAL_TRANSIENT,
TokenTypes.LITERAL_VOLATILE
)));
private static final Set INVALID_FINAL_ANNOTATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"JsonProperty"
)));
/**... | class Utils {
private static final Set INVALID_FINAL_COMBINATION = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
TokenTypes.LITERAL_TRANSIENT,
TokenTypes.LITERAL_VOLATILE
)));
private static final Set INVALID_FINAL_ANNOTATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"JsonProperty"
)));
/**... |
`ImplUtils.isNullOrEmpty`? | public AsyncDocumentClient build() {
ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint");
ifThrowIllegalArgException(
this.masterKeyOrResourceToken == null && (permissionFeed == null || permissionFeed.isEmpty())
&& this.tokenResolver == null && this.cosmosKeyCredenti... | ifThrowIllegalArgException(cosmosKeyCredential != null && StringUtils.isEmpty(cosmosKeyCredential.key()), | public AsyncDocumentClient build() {
ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint");
ifThrowIllegalArgException(
this.masterKeyOrResourceToken == null && (permissionFeed == null || permissionFeed.isEmpty())
&& this.tokenResolver == null && this.cosmosKeyCredenti... | class Builder {
Configs configs = new Configs();
ConnectionPolicy connectionPolicy;
ConsistencyLevel desiredConsistencyLevel;
List<Permission> permissionFeed;
String masterKeyOrResourceToken;
URI serviceEndpoint;
TokenResolver tokenResolver;
CosmosKeyCredential cosmosKeyCredential;
public Builder withServiceEndpoint(St... | class Builder {
Configs configs = new Configs();
ConnectionPolicy connectionPolicy;
ConsistencyLevel desiredConsistencyLevel;
List<Permission> permissionFeed;
String masterKeyOrResourceToken;
URI serviceEndpoint;
TokenResolver tokenResolver;
CosmosKeyCredential cosmosKeyCredential;
public Builder withServiceEndpoint(St... |
Just a style suggestion: try to make the boolean expression more readable when writing long boolean expressions, e.g.: ```java return INVALID_FINAL_COMBINATION.contains(node.getType()) || (TokenTypes.ANNOTATION == type && INVALID_FINAL_ANNOTATIONS.contains(node.findFirstToken(TokenTypes.IDENT).getText())); ``` | protected static boolean hasIllegalCombination(DetailAST modifiers) {
if (modifiers.getType() != TokenTypes.MODIFIERS) {
return false;
}
Optional<DetailAST> illegalCombination = TokenUtil.findFirstTokenByPredicate(modifiers, (node) -> {
final int type = node.getType();
return INVALID_FINAL_COMBINATION.contains(node.get... | && INVALID_FINAL_ANNOTATIONS.contains(node.findFirstToken(TokenTypes.IDENT).getText())); | protected static boolean hasIllegalCombination(DetailAST modifiers) {
if (modifiers.getType() != TokenTypes.MODIFIERS) {
return false;
}
Optional<DetailAST> illegalCombination = TokenUtil.findFirstTokenByPredicate(modifiers, (node) -> {
final int type = node.getType();
return INVALID_FINAL_COMBINATION.contains(node.get... | class Utils {
private static final Set INVALID_FINAL_COMBINATION = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
TokenTypes.LITERAL_TRANSIENT,
TokenTypes.LITERAL_VOLATILE
)));
private static final Set INVALID_FINAL_ANNOTATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"JsonProperty"
)));
/**... | class Utils {
private static final Set INVALID_FINAL_COMBINATION = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
TokenTypes.LITERAL_TRANSIENT,
TokenTypes.LITERAL_VOLATILE
)));
private static final Set INVALID_FINAL_ANNOTATIONS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
"JsonProperty"
)));
/**... |
nit: this logic is duplicated from CosmosClient - should we only have it in one place? | public AsyncDocumentClient build() {
ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint");
ifThrowIllegalArgException(
this.masterKeyOrResourceToken == null && (permissionFeed == null || permissionFeed.isEmpty())
&& this.tokenResolver == null && this.cosmosKeyCredenti... | this.masterKeyOrResourceToken == null && (permissionFeed == null || permissionFeed.isEmpty()) | public AsyncDocumentClient build() {
ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint");
ifThrowIllegalArgException(
this.masterKeyOrResourceToken == null && (permissionFeed == null || permissionFeed.isEmpty())
&& this.tokenResolver == null && this.cosmosKeyCredenti... | class Builder {
Configs configs = new Configs();
ConnectionPolicy connectionPolicy;
ConsistencyLevel desiredConsistencyLevel;
List<Permission> permissionFeed;
String masterKeyOrResourceToken;
URI serviceEndpoint;
TokenResolver tokenResolver;
CosmosKeyCredential cosmosKeyCredential;
public Builder withServiceEndpoint(St... | class Builder {
Configs configs = new Configs();
ConnectionPolicy connectionPolicy;
ConsistencyLevel desiredConsistencyLevel;
List<Permission> permissionFeed;
String masterKeyOrResourceToken;
URI serviceEndpoint;
TokenResolver tokenResolver;
CosmosKeyCredential cosmosKeyCredential;
public Builder withServiceEndpoint(St... |
THere are multiple places you use `toLowerCase()`. If the same method was invoked on a JVM whose default locale is not en-US, this may not be what you want. In general, I'd suggest `toLowerCase(Locale.ROOT)` or `toLowerCase(Locale.US)`. | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | !isNamingMatched(customDescription.toLowerCase(), fullPath.toLowerCase(), parameters)) { | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
you are evaluating masterkey#hashCode on every single call. And seems your intention is to only use it for comparing the new hashcode with the old hashcode. String comparison directly should be faster that hashcode computation. As for hashcode computation you are iteratring over all chars of the string and doing some ... | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.cosmosKeyCredential.getMasterKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.cosmosKeyCredential.getMasterKey().getBytes();
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);... | int masterKeyLatestHashCode = this.cosmosKeyCredential.getMasterKey().hashCode(); | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.cosmosKeyCredential.keyHashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.cosmosKeyCredential.key().getBytes();
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final CosmosKeyCredential cosmosKeyCredential;
private Mac macInstance;
private int masterKeyHashCode;
public BaseAuthorizationTokenProvider(CosmosKeyCredential cosm... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final CosmosKeyCredential cosmosKeyCredential;
private final Mac macInstance;
private int masterKeyHashCode;
public BaseAuthorizationTokenProvider(CosmosKeyCredentia... |
Should be at one place, but there are lot of references in the code, where AsyncDocumentClient.build() is being used directly without CosmosClientBuilder, so didn't want to take chances and leave this check. | public AsyncDocumentClient build() {
ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint");
ifThrowIllegalArgException(
this.masterKeyOrResourceToken == null && (permissionFeed == null || permissionFeed.isEmpty())
&& this.tokenResolver == null && this.cosmosKeyCredenti... | this.masterKeyOrResourceToken == null && (permissionFeed == null || permissionFeed.isEmpty()) | public AsyncDocumentClient build() {
ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint");
ifThrowIllegalArgException(
this.masterKeyOrResourceToken == null && (permissionFeed == null || permissionFeed.isEmpty())
&& this.tokenResolver == null && this.cosmosKeyCredenti... | class Builder {
Configs configs = new Configs();
ConnectionPolicy connectionPolicy;
ConsistencyLevel desiredConsistencyLevel;
List<Permission> permissionFeed;
String masterKeyOrResourceToken;
URI serviceEndpoint;
TokenResolver tokenResolver;
CosmosKeyCredential cosmosKeyCredential;
public Builder withServiceEndpoint(St... | class Builder {
Configs configs = new Configs();
ConnectionPolicy connectionPolicy;
ConsistencyLevel desiredConsistencyLevel;
List<Permission> permissionFeed;
String masterKeyOrResourceToken;
URI serviceEndpoint;
TokenResolver tokenResolver;
CosmosKeyCredential cosmosKeyCredential;
public Builder withServiceEndpoint(St... |
Good point, but the reason for hashCode comparison was because of the fact that we don't want to store masterKey in BaseAuthorizationTokenProvider, because we always want to use cosmosKeyCredential reference to get the master key. But as you mentioned, string comparison is faster, I can store the master key and won't ... | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.cosmosKeyCredential.getMasterKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.cosmosKeyCredential.getMasterKey().getBytes();
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);... | int masterKeyLatestHashCode = this.cosmosKeyCredential.getMasterKey().hashCode(); | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.cosmosKeyCredential.keyHashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.cosmosKeyCredential.key().getBytes();
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final CosmosKeyCredential cosmosKeyCredential;
private Mac macInstance;
private int masterKeyHashCode;
public BaseAuthorizationTokenProvider(CosmosKeyCredential cosm... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final CosmosKeyCredential cosmosKeyCredential;
private final Mac macInstance;
private int masterKeyHashCode;
public BaseAuthorizationTokenProvider(CosmosKeyCredentia... |
do no-op on this. Thanks for the explanation. | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.cosmosKeyCredential.getMasterKey().hashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.cosmosKeyCredential.getMasterKey().getBytes();
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);... | int masterKeyLatestHashCode = this.cosmosKeyCredential.getMasterKey().hashCode(); | private Mac getMacInstance() {
int masterKeyLatestHashCode = this.cosmosKeyCredential.keyHashCode();
if (masterKeyLatestHashCode != this.masterKeyHashCode) {
byte[] masterKeyBytes = this.cosmosKeyCredential.key().getBytes();
byte[] masterKeyDecodedBytes = Utils.Base64Decoder.decode(masterKeyBytes);
SecretKey signingKey... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final CosmosKeyCredential cosmosKeyCredential;
private Mac macInstance;
private int masterKeyHashCode;
public BaseAuthorizationTokenProvider(CosmosKeyCredential cosm... | class BaseAuthorizationTokenProvider implements AuthorizationTokenProvider {
private static final String AUTH_PREFIX = "type=master&ver=1.0&sig=";
private final CosmosKeyCredential cosmosKeyCredential;
private final Mac macInstance;
private int masterKeyHashCode;
public BaseAuthorizationTokenProvider(CosmosKeyCredentia... |
All other samples are making this extra call for many APIs. Not doing here would be odd. | public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty());
}
for (KeyBase key : keyClient.listKeys(n... | Key keyWithMaterial = keyClient.getKey(value); | public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty());
}
for (KeyBase key : keyClient.listKeys(n... | 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... | 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... |
looks like we are not looking for the `@throws` statement any more. Is this comment out of date? | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | |
`ImplUtils.isNullOrEmpty` if possible | public CosmosClient build() {
ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint");
ifThrowIllegalArgException(
this.keyOrResourceToken == null && (permissions == null || permissions.isEmpty())
&& this.tokenResolver == null && this.cosmosKeyCredential == null,
"cannot... | ifThrowIllegalArgException(cosmosKeyCredential != null && StringUtils.isEmpty(cosmosKeyCredential.key()), | public CosmosClient build() {
ifThrowIllegalArgException(this.serviceEndpoint == null, "cannot build client without service endpoint");
ifThrowIllegalArgException(
this.keyOrResourceToken == null && (permissions == null || permissions.isEmpty())
&& this.tokenResolver == null && this.cosmosKeyCredential == null,
"cannot... | class CosmosClientBuilder {
private Configs configs = new Configs();
private String serviceEndpoint;
private String keyOrResourceToken;
private ConnectionPolicy connectionPolicy;
private ConsistencyLevel desiredConsistencyLevel;
private List<Permission> permissions;
private TokenResolver tokenResolver;
private CosmosKe... | class CosmosClientBuilder {
private Configs configs = new Configs();
private String serviceEndpoint;
private String keyOrResourceToken;
private ConnectionPolicy connectionPolicy;
private ConsistencyLevel desiredConsistencyLevel;
private List<Permission> permissions;
private TokenResolver tokenResolver;
private CosmosKe... |
logErrorAndThrow() will throw RuntimeError internally. A ClientLogger can't be static and the naming of ClientLogger variable has to be 'logger'. It applies to other changes as well. | public static X509Certificate publicKeyFromPem(byte[] pem) {
Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----");
Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8));
if (!matcher.find()) {
throw LOGGER.logErrorAndThrow(new IllegalArgumentException("PEM... | throw LOGGER.logErrorAndThrow(new IllegalArgumentException("PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); | public static X509Certificate publicKeyFromPem(byte[] pem) {
Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----");
Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8));
if (!matcher.find()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("... | class CertificateUtil {
private static final ClientLogger LOGGER = new ClientLogger(CertificateUtil.class);
/**
* Extracts the PrivateKey from a PEM certificate.
* @param pem the contents of a PEM certificate.
* @return the PrivateKey
*/
public static PrivateKey privateKeyFromPem(byte[] pem) {
Pattern pattern = Pattern... | class CertificateUtil {
private static final ClientLogger LOGGER = new ClientLogger(CertificateUtil.class);
/**
* Extracts the PrivateKey from a PEM certificate.
* @param pem the contents of a PEM certificate.
* @return the PrivateKey
*/
public static PrivateKey privateKeyFromPem(byte[] pem) {
Pattern pattern = Pattern... |
Rather than saying "Response value" can say "Key name %s, Key Version %s" here. | public void listKeyVersions() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeyVersions("keyName")) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty(), key... | System.out.printf("Response value is %d %n", value); | public void listKeyVersions() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeyVersions("keyName")) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty(), key... | 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... | 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... |
I've changed it to return the RuntimeException to be thrown as part of this change, having it throw inside the method and needing to return null afterwards in a lot of cases isn't a good pattern and may result in strange code to be used in cases where final variables need to be set. | public static X509Certificate publicKeyFromPem(byte[] pem) {
Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----");
Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8));
if (!matcher.find()) {
throw LOGGER.logErrorAndThrow(new IllegalArgumentException("PEM... | throw LOGGER.logErrorAndThrow(new IllegalArgumentException("PEM certificate provided does not contain -----BEGIN CERTIFICATE-----END CERTIFICATE----- block")); | public static X509Certificate publicKeyFromPem(byte[] pem) {
Pattern pattern = Pattern.compile("(?s)-----BEGIN CERTIFICATE-----.*-----END CERTIFICATE-----");
Matcher matcher = pattern.matcher(new String(pem, StandardCharsets.UTF_8));
if (!matcher.find()) {
throw LOGGER.logExceptionAsError(new IllegalArgumentException("... | class CertificateUtil {
private static final ClientLogger LOGGER = new ClientLogger(CertificateUtil.class);
/**
* Extracts the PrivateKey from a PEM certificate.
* @param pem the contents of a PEM certificate.
* @return the PrivateKey
*/
public static PrivateKey privateKeyFromPem(byte[] pem) {
Pattern pattern = Pattern... | class CertificateUtil {
private static final ClientLogger LOGGER = new ClientLogger(CertificateUtil.class);
/**
* Extracts the PrivateKey from a PEM certificate.
* @param pem the contents of a PEM certificate.
* @return the PrivateKey
*/
public static PrivateKey privateKeyFromPem(byte[] pem) {
Pattern pattern = Pattern... |
This is out of scope of this PR but while you are modifying this file, could you also instead import the package and remove this fully-qualified class name? | public boolean tryAdd(final EventData eventData) {
if (eventData == null) {
throw logger.logWarningAndThrow(new IllegalArgumentException("eventData cannot be null"));
}
final int size;
try {
size = getSize(eventData, events.isEmpty());
} catch (java.nio.BufferOverflowException exception) {
throw logger.logWarningAndThr... | } catch (java.nio.BufferOverflowException exception) { | public boolean tryAdd(final EventData eventData) {
if (eventData == null) {
throw logger.logExceptionAsWarning(new IllegalArgumentException("eventData cannot be null"));
}
final int size;
try {
size = getSize(eventData, events.isEmpty());
} catch (BufferOverflowException exception) {
throw logger.logExceptionAsWarning(... | class EventDataBatch {
private final ClientLogger logger = new ClientLogger(EventDataBatch.class);
private final Object lock = new Object();
private final int maxMessageSize;
private final String partitionKey;
private final ErrorContextProvider contextProvider;
private final List<EventData> events;
private final byte[]... | class EventDataBatch {
private final ClientLogger logger = new ClientLogger(EventDataBatch.class);
private final Object lock = new Object();
private final int maxMessageSize;
private final String partitionKey;
private final ErrorContextProvider contextProvider;
private final List<EventData> events;
private final byte[]... |
Is this going to `toString` correctly for the headers? If you want to do associations for URL and status code show it like this: `URL: %s, Status code: %d` | public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty());
}
for (KeyBase key : keyClient.listKeys(n... | System.out.printf("Response headers are %s. Url %s and status code %d %n", resp.headers(), | public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty());
}
for (KeyBase key : keyClient.listKeys(n... | 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... | 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... |
Do we want to make a call to get each key again? Why not just print the name? | public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty());
}
for (KeyBase key : keyClient.listKeys(n... | Key keyWithMaterial = keyClient.getKey(value); | public void listKeySnippets() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeys()) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key with name %s and type %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty());
}
for (KeyBase key : keyClient.listKeys(n... | 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... | 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... |
Let's just use values stored in `SecretBase` | public void listSecretsCodeSnippets() {
SecretClient secretClient = getSecretClient();
for (SecretBase secret : secretClient.listSecrets()) {
Secret secretWithValue = secretClient.getSecret(secret);
System.out.printf("Received secret with name %s and value %s",
secretWithValue.name(), secretWithValue.value());
}
for (... | Secret secretWithValue = secretClient.getSecret(value); | public void listSecretsCodeSnippets() {
SecretClient secretClient = getSecretClient();
for (SecretBase secret : secretClient.listSecrets()) {
Secret secretWithValue = secretClient.getSecret(secret);
System.out.printf("Received secret with name %s and value %s",
secretWithValue.name(), secretWithValue.value());
}
for (... | class SecretClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Method to insert code snippets for {@link SecretClient
*/
public void getSecretCodeSnippets() {
SecretClient secretClient = getSecretClient();
for (Se... | class SecretClientJavaDocCodeSnippets {
private String key1 = "key1";
private String key2 = "key2";
private String value1 = "val1";
private String value2 = "val2";
/**
* Method to insert code snippets for {@link SecretClient
*/
public void getSecretCodeSnippets() {
SecretClient secretClient = getSecretClient();
for (Se... |
+1 | public void listKeyVersions() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeyVersions("keyName")) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty(), key... | System.out.printf("Response value is %d %n", value); | public void listKeyVersions() {
KeyClient keyClient = createClient();
for (KeyBase key : keyClient.listKeyVersions("keyName")) {
Key keyWithMaterial = keyClient.getKey(key);
System.out.printf("Received key's version with name %s, type %s and version %s", keyWithMaterial.name(),
keyWithMaterial.keyMaterial().kty(), key... | 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... | 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... |
Why do we need Stack for this? Would a simple String variable work? It make sense for classes with inner classes to be able to pop() and come back to parent class... But, can we find a new Method_DEF inside a Method_def? | public void leaveToken(DetailAST token) {
switch (token.getType()) {
case TokenTypes.CLASS_DEF:
if (!classNameStack.isEmpty()) {
classNameStack.pop();
}
break;
case TokenTypes.METHOD_DEF:
if (!methodDefStack.isEmpty()) {
methodDefStack.pop();
}
break;
default:
break;
}
} | methodDefStack.pop(); | public void leaveToken(DetailAST token) {
if (token.getType() == TokenTypes.CLASS_DEF && !classNameStack.isEmpty()) {
classNameStack.pop();
}
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
Will this result in a NullReferenceException if you do not have text for your description node.. findFirstToken returns null? (ie. `{@codesnippet}`). | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | String customDescription = JavadocUtil.findFirstToken(descriptionNode, JavadocTokenTypes.TEXT).getText(); | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
```suggestion log(node.getLineNumber(), String.format("Naming pattern mismatch. The @codesnippet description " ``` | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | log(node.getLineNumber(), String.format("Naming pattern mismatch. The @codeSnippet description " | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
```suggestion final StringBuilder sb = new StringBuilder(); ``` | private String constructParametersString(DetailAST methodDefToken) {
StringBuilder sb = new StringBuilder();
final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS);
for (DetailAST ast = parametersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
if (ast.getType() != Token... | StringBuilder sb = new StringBuilder(); | private String constructParametersString(DetailAST methodDefToken) {
final StringBuilder sb = new StringBuilder();
final DetailAST parametersToken = methodDefToken.findFirstToken(TokenTypes.PARAMETERS);
for (DetailAST ast = parametersToken.getFirstChild(); ast != null; ast = ast.getNextSibling()) {
if (ast.getType() !=... | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
You are right, Looking for @codesnippet | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | |
Good point. A variable should be enough. | public void leaveToken(DetailAST token) {
switch (token.getType()) {
case TokenTypes.CLASS_DEF:
if (!classNameStack.isEmpty()) {
classNameStack.pop();
}
break;
case TokenTypes.METHOD_DEF:
if (!methodDefStack.isEmpty()) {
methodDefStack.pop();
}
break;
default:
break;
}
} | methodDefStack.pop(); | public void leaveToken(DetailAST token) {
if (token.getType() == TokenTypes.CLASS_DEF && !classNameStack.isEmpty()) {
classNameStack.pop();
}
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
There will always have TEXT token if there is DESCRIPTION token exists. Will add this comment to the above of this code section | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | String customDescription = JavadocUtil.findFirstToken(descriptionNode, JavadocTokenTypes.TEXT).getText(); | private void checkNamingPattern(DetailAST blockCommentToken) {
if (!BlockCommentPosition.isOnMethod(blockCommentToken)) {
return;
}
DetailNode javadocNode = null;
try {
javadocNode = DetailNodeTreeStringPrinter.parseJavadocAsDetailNode(blockCommentToken);
} catch (IllegalArgumentException ex) {
}
if (javadocNode == nul... | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private Deque<DetailAST> methodDefStack = new ArrayDeque<>();
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} | class name when leave the same token
private Deque<String> classNameStack = new ArrayDeque<>();
private DetailAST methodDefToken = null;
@Override
public int[] getDefaultTokens() {
return getRequiredTokens();
} |
This was a false positive in lts right ? mvn spotbugs:spotbugs doesn't think of it as a spotbug in java 8. | private void checkDigestLength(byte[] digest) {
if (digest.length != getDigestLength()) {
throw new IllegalArgumentException("Invalid digest length.");
}
} | if (digest.length != getDigestLength()) { | private void checkDigestLength(byte[] digest) {
if (digest.length != getDigestLength()) {
throw new IllegalArgumentException("Invalid digest length.");
}
} | class EcdsaSignatureTransform implements ISignatureTransform {
private static final String ALGORITHM = "NONEwithECDSA";
private final KeyPair keyPair;
private final Provider provider;
private final Ecdsa algorithm;
EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) {
this.keyPair = keyPair;
th... | class EcdsaSignatureTransform implements ISignatureTransform {
private static final String ALGORITHM = "NONEwithECDSA";
private final KeyPair keyPair;
private final Provider provider;
private final Ecdsa algorithm;
EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) {
this.keyPair = keyPair;
th... |
Yes, however, we want to ensure our code is LTS compatible. So, if spotbugs check fails for JDK 11, then it's better to fix it for JDK8 too. This is only to test that we get the same results in PR build as we get in post-merge CI builds. | private void checkDigestLength(byte[] digest) {
if (digest.length != getDigestLength()) {
throw new IllegalArgumentException("Invalid digest length.");
}
} | if (digest.length != getDigestLength()) { | private void checkDigestLength(byte[] digest) {
if (digest.length != getDigestLength()) {
throw new IllegalArgumentException("Invalid digest length.");
}
} | class EcdsaSignatureTransform implements ISignatureTransform {
private static final String ALGORITHM = "NONEwithECDSA";
private final KeyPair keyPair;
private final Provider provider;
private final Ecdsa algorithm;
EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) {
this.keyPair = keyPair;
th... | class EcdsaSignatureTransform implements ISignatureTransform {
private static final String ALGORITHM = "NONEwithECDSA";
private final KeyPair keyPair;
private final Provider provider;
private final Ecdsa algorithm;
EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) {
this.keyPair = keyPair;
th... |
This is 'package-private', not 'protected'. This means it is not public API and effectively private. | Mono<VoidResponse> createWithResponse(Map<String, String> metadata, Context context) {
return client.queues().createWithRestResponseAsync(queueName, null, metadata, null, context)
.map(VoidResponse::new);
} | } | Mono<VoidResponse> createWithResponse(Map<String, String> metadata, Context context) {
return client.queues().createWithRestResponseAsync(queueName, null, metadata, null, context)
.map(VoidResponse::new);
} | class QueueAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@code AzureQueueStorageImpl
* Each service call ... | class QueueAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@code AzureQueueStorageImpl
* Each service call ... |
Looks like the PR build failed due to spotbugs. So, the fix is working! | private void checkDigestLength(byte[] digest) {
if (digest.length != getDigestLength()) {
throw new IllegalArgumentException("Invalid digest length.");
}
} | if (digest.length != getDigestLength()) { | private void checkDigestLength(byte[] digest) {
if (digest.length != getDigestLength()) {
throw new IllegalArgumentException("Invalid digest length.");
}
} | class EcdsaSignatureTransform implements ISignatureTransform {
private static final String ALGORITHM = "NONEwithECDSA";
private final KeyPair keyPair;
private final Provider provider;
private final Ecdsa algorithm;
EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) {
this.keyPair = keyPair;
th... | class EcdsaSignatureTransform implements ISignatureTransform {
private static final String ALGORITHM = "NONEwithECDSA";
private final KeyPair keyPair;
private final Provider provider;
private final Ecdsa algorithm;
EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) {
this.keyPair = keyPair;
th... |
Yeah, I agree, this is a good idea to enable this in PR builds. It would be good to catch false positives at this stage itself and either refactor to fix or suppress them, which ever is the best option. | private void checkDigestLength(byte[] digest) {
if (digest.length != getDigestLength()) {
throw new IllegalArgumentException("Invalid digest length.");
}
} | if (digest.length != getDigestLength()) { | private void checkDigestLength(byte[] digest) {
if (digest.length != getDigestLength()) {
throw new IllegalArgumentException("Invalid digest length.");
}
} | class EcdsaSignatureTransform implements ISignatureTransform {
private static final String ALGORITHM = "NONEwithECDSA";
private final KeyPair keyPair;
private final Provider provider;
private final Ecdsa algorithm;
EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) {
this.keyPair = keyPair;
th... | class EcdsaSignatureTransform implements ISignatureTransform {
private static final String ALGORITHM = "NONEwithECDSA";
private final KeyPair keyPair;
private final Provider provider;
private final Ecdsa algorithm;
EcdsaSignatureTransform(KeyPair keyPair, Provider provider, Ecdsa algorithm) {
this.keyPair = keyPair;
th... |
Not quite understand why we make the API protected. If there is no need to have context in async one. Can we make it private? | Mono<VoidResponse> createWithResponse(Map<String, String> metadata, Context context) {
return client.queues().createWithRestResponseAsync(queueName, null, metadata, null, context)
.map(VoidResponse::new);
} | } | Mono<VoidResponse> createWithResponse(Map<String, String> metadata, Context context) {
return client.queues().createWithRestResponseAsync(queueName, null, metadata, null, context)
.map(VoidResponse::new);
} | class QueueAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@code AzureQueueStorageImpl
* Each service call ... | class QueueAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@code AzureQueueStorageImpl
* Each service call ... |
This is being called from the sync client methods in which we need explicit context argument passing, so protected. | Mono<VoidResponse> createWithResponse(Map<String, String> metadata, Context context) {
return client.queues().createWithRestResponseAsync(queueName, null, metadata, null, context)
.map(VoidResponse::new);
} | } | Mono<VoidResponse> createWithResponse(Map<String, String> metadata, Context context) {
return client.queues().createWithRestResponseAsync(queueName, null, metadata, null, context)
.map(VoidResponse::new);
} | class QueueAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@code AzureQueueStorageImpl
* Each service call ... | class QueueAsyncClient {
private static final ClientLogger LOGGER = new ClientLogger(QueueAsyncClient.class);
private final AzureQueueStorageImpl client;
private final String queueName;
/**
* Creates a QueueAsyncClient that sends requests to the storage queue service at {@code AzureQueueStorageImpl
* Each service call ... |
seems `buildAuthenticatedRequest` can throw exception if so `response.close();` won't be hit and that can leak connection. | public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
clientBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
HttpUrl url = chain.request().url();
Map<String, String> challengeMap = cache.getCach... | response.close(); | public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
clientBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
HttpUrl url = chain.request().url();
Map<String, String> challengeMap = cache.getCach... | class KeyVaultCredentials implements ServiceClientCredentials {
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String BEARER_TOKEP_REFIX = "Bearer ";
private static final String CLIENT_ENCRYPTION_KEY_TYPE = "RSA";
private static final int CLIENT_ENCRYPTION_KEY_SIZE = 2048;
priva... | class KeyVaultCredentials implements ServiceClientCredentials {
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String BEARER_TOKEP_REFIX = "Bearer ";
private static final String CLIENT_ENCRYPTION_KEY_TYPE = "RSA";
private static final int CLIENT_ENCRYPTION_KEY_SIZE = 2048;
priva... |
Valid point. Added a try finally block to ensure response gets cleaned up via close(). | public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
clientBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
HttpUrl url = chain.request().url();
Map<String, String> challengeMap = cache.getCach... | response.close(); | public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
clientBuilder.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request originalRequest = chain.request();
HttpUrl url = chain.request().url();
Map<String, String> challengeMap = cache.getCach... | class KeyVaultCredentials implements ServiceClientCredentials {
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String BEARER_TOKEP_REFIX = "Bearer ";
private static final String CLIENT_ENCRYPTION_KEY_TYPE = "RSA";
private static final int CLIENT_ENCRYPTION_KEY_SIZE = 2048;
priva... | class KeyVaultCredentials implements ServiceClientCredentials {
private static final String WWW_AUTHENTICATE = "WWW-Authenticate";
private static final String BEARER_TOKEP_REFIX = "Bearer ";
private static final String CLIENT_ENCRYPTION_KEY_TYPE = "RSA";
private static final int CLIENT_ENCRYPTION_KEY_SIZE = 2048;
priva... |
It may be my ignorance of language specifics, but these look like they're stubbed out and not implemented. Is that intentional? | IterableResponse<EventData> receive(int maximumMessageCount) {
return new IterableResponse<>(Flux.empty());
} | return new IterableResponse<>(Flux.empty()); | IterableResponse<EventData> receive(int maximumMessageCount) {
return new IterableResponse<>(Flux.empty());
} | class EventHubConsumer implements Closeable {
private final EventHubAsyncConsumer consumer;
private final EventHubConsumerOptions options;
EventHubConsumer(EventHubAsyncConsumer consumer, EventHubConsumerOptions options) {
this.consumer = Objects.requireNonNull(consumer);
this.options = Objects.requireNonNull(options);... | class EventHubConsumer implements Closeable {
private final EventHubAsyncConsumer consumer;
private final EventHubConsumerOptions options;
EventHubConsumer(EventHubAsyncConsumer consumer, EventHubConsumerOptions options) {
this.consumer = Objects.requireNonNull(consumer);
this.options = Objects.requireNonNull(options);... |
Check for `null` before using `options`. | public EventHubProducer createProducer(EventHubProducerOptions options) {
final EventHubAsyncProducer producer = client.createProducer();
return new EventHubProducer(producer, options.retry().tryTimeout());
} | return new EventHubProducer(producer, options.retry().tryTimeout()); | public EventHubProducer createProducer(EventHubProducerOptions options) {
Objects.requireNonNull(options);
final EventHubAsyncProducer producer = client.createProducer(options);
final Duration tryTimeout = options.retry() != null && options.retry().tryTimeout() != null
? options.retry().tryTimeout()
: defaultProducerOp... | class EventHubClient implements Closeable {
private final EventHubAsyncClient client;
private final RetryOptions retry;
private final EventHubProducerOptions defaultProducerOptions;
private final EventHubConsumerOptions defaultConsumerOptions;
EventHubClient(EventHubAsyncClient client, ConnectionOptions connectionOptio... | class EventHubClient implements Closeable {
private final EventHubAsyncClient client;
private final RetryOptions retry;
private final EventHubProducerOptions defaultProducerOptions;
private final EventHubConsumerOptions defaultConsumerOptions;
EventHubClient(EventHubAsyncClient client, ConnectionOptions connectionOptio... |
This is intentional. This PR is focused only on the synchronous producer for user study starting on Thursday. The synch Consumer will be implemented later. | IterableResponse<EventData> receive(int maximumMessageCount) {
return new IterableResponse<>(Flux.empty());
} | return new IterableResponse<>(Flux.empty()); | IterableResponse<EventData> receive(int maximumMessageCount) {
return new IterableResponse<>(Flux.empty());
} | class EventHubConsumer implements Closeable {
private final EventHubAsyncConsumer consumer;
private final EventHubConsumerOptions options;
EventHubConsumer(EventHubAsyncConsumer consumer, EventHubConsumerOptions options) {
this.consumer = Objects.requireNonNull(consumer);
this.options = Objects.requireNonNull(options);... | class EventHubConsumer implements Closeable {
private final EventHubAsyncConsumer consumer;
private final EventHubConsumerOptions options;
EventHubConsumer(EventHubAsyncConsumer consumer, EventHubConsumerOptions options) {
this.consumer = Objects.requireNonNull(consumer);
this.options = Objects.requireNonNull(options);... |
"application/octet-stream" mime-type is well known. I'd use `.equalsIgnoreCase()` because they are also case-insensitive. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | if (contentType != null && contentType.contains("octet-stream")) { | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... |
in the RFC, headers are case insensitive. It is by convention that you see "Content-Type" rather than "content-type". But they amount to the same thing. | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | if (contentType != null && contentType.contains("octet-stream")) { | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... |
Playback client is not validator. Is it better to ignore the case for all the hard-code string checking? | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | if (contentType != null && contentType.contains("octet-stream")) { | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... |
RecordNetworkCallPolicy encounters the same issues. I added a comment about that. | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | if (contentType != null && contentType.contains("octet-stream")) { | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... |
While RFC headers are case-insensitive the data structure, `Map`, we use to store this information in playback isn't. This is another cleanup we should do to either use `HttpHeaders` or a case-insensitive `Map` implementation. | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | if (contentType != null && contentType.contains("octet-stream")) { | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... |
SO has revealed that there is a way to have case insensitive key comparison. One thing that .NET provides over HashMap. https://stackoverflow.com/a/22336599 | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | if (contentType != null && contentType.contains("octet-stream")) { | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... |
Updated to the case ignores check. | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | if (contentType != null && contentType.contains("octet-stream")) { | private Mono<HttpResponse> playbackHttpResponse(final HttpRequest request) {
final String incomingUrl = applyReplacementRule(request.url().toString());
final String incomingMethod = request.httpMethod().toString();
final String matchingUrl = removeHost(incomingUrl);
NetworkCallRecord networkCallRecord = recordedData.fi... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... | class PlaybackClient implements HttpClient {
private final ClientLogger logger = new ClientLogger(PlaybackClient.class);
private final AtomicInteger count = new AtomicInteger(0);
private final Map<String, String> textReplacementRules;
private final RecordedData recordedData;
/**
* Creates a PlaybackClient that replays ... |
... or do we just reset the state to assume that things are not balanced each time we stop? ... or do we assume things are balanced and then slowly realize they're not and re balance them? I don't have a strong opinion, I think either case works - its just a matter of how aggressive we pursue work stealing. Howev... | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (ImplUtils.isNullOrEmpty(partitionIds)) {
return Mono.error(new IllegalStateException("There are no par... | return Mono.empty(); | 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... |
"Ideally" or "under normal circumstances"... What I'm asking is whether this is something that would potentially occur and is expected or is an indicator that something is wrong. The comment implies the former, but the implementation seems to imply the latter. | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (ImplUtils.isNullOrEmpty(partitionIds)) {
return Mono.error(new IllegalStateException("There are no par... | 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... | |
Assuming this is reading the actual Event Hub metadata, this is impossible and would indicate a service failure of some sort. Based on that, I think the comment is the artifact that is out of sync here. | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (ImplUtils.isNullOrEmpty(partitionIds)) {
return Mono.error(new IllegalStateException("There are no par... | 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... | |
"A long time" is ambiguous. You may wish to consider offering context around how that is determined. "Remove ownership that have not been modified within the configured period" or similar? _(also, "ownership" is both singular and plural)_ | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (ImplUtils.isNullOrEmpty(partitionIds)) {
return Mono.error(new IllegalStateException("There are no par... | * Remove all partitions ownerships that have not be modified for a long time. This means that the previous | 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... |
nit: This may be a lack of understanding of language idioms, but you're making several calls to the `size()` methods in this logic. Maybe it is worth considering reading them once and caching in a local variable for efficiency? | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (ImplUtils.isNullOrEmpty(partitionIds)) {
return Mono.error(new IllegalStateException("There are no par... | int minPartitionsPerEventProcessor = partitionIds.size() / ownerPartitionMap.size(); | 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... |
Why is this returning `Mono<Void>`? The work itself is synchronous until we return Mono.empty() at the very end. One way to make this more async is to return a `Mono.fromRunnable(() -> { // work in here. });` So the work is run asynchronously and completes when it ends. | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (ImplUtils.isNullOrEmpty(partitionIds)) {
return Mono.error(new IllegalStateException("There are no par... | Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1(); | 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... |
Lets say we have an Event Hub with 3 partitions and we follow the below steps- * Create Event Processor instance `processor1` * Call `processor1.start()` * After some delay call `processor1.stop()` * Now `processor1` owns all the 3 partitions and the load is balanced * If we call `processor1.start()` again, `isLoadBal... | private Mono<Void> loadBalance(final Tuple2<Map<String, PartitionOwnership>, List<String>> tuple) {
Map<String, PartitionOwnership> partitionOwnershipMap = tuple.getT1();
List<String> partitionIds = tuple.getT2();
if (ImplUtils.isNullOrEmpty(partitionIds)) {
return Mono.error(new IllegalStateException("There are no par... | return Mono.empty(); | 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... |
I think the `CLEAR` enum should be used and remove the statement about clearing a range of 4MB, clear is allowed to be as large as the file size. Additionally, clearing will throw an exception is the Content-Length header is set. | public Mono<Response<FileUploadInfo>> clearRange(long length) {
FileRange range = new FileRange(0, length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, 0, null, null, null, Context.NONE)
.map(this::uploadResponse);
} | return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, 0, null, null, null, Context.NONE) | new FileRange(0, length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)
.map(this::uploadResponse);
}
/**
* Uploads a range of bytes to specific of a file in storage file service. Upload ope... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... |
Should be `CLEAR` | public Mono<Response<FileUploadInfo>> clearRange(long length, long offset) {
FileRange range = new FileRange(offset, offset + length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, 0, null, null, null, Context.NONE)
.map(this... | return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, 0, null, null, null, Context.NONE) | new FileRange(offset, offset + length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)
.map(this::uploadResponse);
}
/**
* Clear a range of bytes to specific of a file in storage file service... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... |
Done. | public Mono<Response<FileUploadInfo>> clearRange(long length) {
FileRange range = new FileRange(0, length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, 0, null, null, null, Context.NONE)
.map(this::uploadResponse);
} | return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, 0, null, null, null, Context.NONE) | new FileRange(0, length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)
.map(this::uploadResponse);
}
/**
* Uploads a range of bytes to specific of a file in storage file service. Upload ope... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... |
Done. | public Mono<Response<FileUploadInfo>> clearRange(long length, long offset) {
FileRange range = new FileRange(offset, offset + length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, 0, null, null, null, Context.NONE)
.map(this... | return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, 0, null, null, null, Context.NONE) | new FileRange(offset, offset + length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)
.map(this::uploadResponse);
}
/**
* Clear a range of bytes to specific of a file in storage file service... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... |
`context` is being ignored here. Need to pass it down to the service call. | Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) {
FileRange range = new FileRange(offset, offset + length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, C... | return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, Context.NONE) | new FileRange(offset, offset + length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)
.map(this::uploadResponse);
}
/**
* Clear a range of bytes to specific of a file in storage file service... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... |
Done. | Mono<Response<FileUploadInfo>> clearRangeWithResponse(long length, long offset, Context context) {
FileRange range = new FileRange(offset, offset + length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, C... | return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.CLEAR, 0L, null, null, null, Context.NONE) | new FileRange(offset, offset + length - 1);
return azureFileStorageClient.files().uploadRangeWithRestResponseAsync(shareName, filePath, range.toString(), FileRangeWriteType.UPDATE, length, data, null, null, context)
.map(this::uploadResponse);
}
/**
* Clear a range of bytes to specific of a file in storage file service... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... | class FileAsyncClient {
private final ClientLogger logger = new ClientLogger(FileAsyncClient.class);
private static final long FILE_DEFAULT_BLOCK_SIZE = 4 * 1024 * 1024L;
private static final long DOWNLOAD_UPLOAD_CHUNK_TIMEOUT = 300;
private final AzureFileStorageImpl azureFileStorageClient;
private final String shareN... |
This can be undone? It looks like the comments are not at the same indentation level. | private void receiveEvents(PartitionOwnership partitionOwnership) {
EventHubConsumerOptions consumerOptions = new EventHubConsumerOptions();
consumerOptions.ownerLevel(0L);
EventPosition startFromEventPosition = partitionOwnership.sequenceNumber() == null ? this.initialEventPosition
: EventPosition.fromSequenceNumber(p... | private void receiveEvents(PartitionOwnership partitionOwnership) {
EventHubConsumerOptions consumerOptions = new EventHubConsumerOptions();
consumerOptions.ownerLevel(0L);
EventPosition startFromEventPosition = partitionOwnership.sequenceNumber() == null ? this.initialEventPosition
: EventPosition.fromSequenceNumber(p... | class EventProcessor {
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 static final String SPAN_CONTEXT = Tracer.OPENTELEMETRY_AMQP_EVENT_SPAN_CONTEXT;
private static f... | class EventProcessor {
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(EventProcessor.class);
private final EventHubAsyncCl... | |
Is there a spec to look at for this? | public static String getDiagnosticId(SpanContext spanContext) {
char[] chars = new char[55];
chars[0] = '0';
chars[1] = '0';
chars[2] = '-';
spanContext.getTraceId().copyLowerBase16To(chars, 3);
chars[35] = '-';
spanContext.getSpanId().copyLowerBase16To(chars, 36);
chars[52] = '-';
spanContext.getTraceOptions().copyLow... | char[] chars = new char[55]; | public static String getDiagnosticId(SpanContext spanContext) {
char[] chars = new char[55];
chars[0] = '0';
chars[1] = '0';
chars[2] = '-';
spanContext.getTraceId().copyLowerBase16To(chars, 3);
chars[35] = '-';
spanContext.getSpanId().copyLowerBase16To(chars, 36);
chars[52] = '-';
spanContext.getTraceOptions().copyLow... | class AmqpPropagationFormatUtil {
private static final String SPAN_CONTEXT = Tracer.OPENTELEMETRY_AMQP_EVENT_SPAN_CONTEXT;
private AmqpPropagationFormatUtil() { }
/**
* This method is called to extract the Span Context information from the received event's diagnostic Id.
*
* @param diagnosticId The diagnostic Id for th... | class AmqpPropagationFormatUtil {
private AmqpPropagationFormatUtil() { }
/**
* This method is called to extract the Span Context information from the received event's diagnostic Id.
*
* @param diagnosticId The dignostic Id providing an unique identifier for individual traces and requests
* @return {@link Context} whic... |
can you please leave a TODO here (or where we call this method) that once we switch to OpenTelemetry, we need to add links before span is starter (and no link type - parent - is needed) | public void addLink(Context eventContext) {
Optional<Object> spanContextOptional = eventContext.getData(SPAN_CONTEXT);
Optional<Object> spanOptional = eventContext.getData(OPENTELEMETRY_SPAN_KEY);
if (!spanOptional.isPresent()) {
logger.warning("Failed to find span to link it.");
return;
}
SpanContext spanContext = (Sp... | span.addLink(Link.fromSpanContext(spanContext, PARENT_LINKED_SPAN)); | public void addLink(Context eventContext) {
final Span span = getSpan(eventContext);
if (span == null) {
logger.warning("Failed to find span to link it.");
return;
}
final Optional<Object> spanContextOptional = eventContext.getData(SPAN_CONTEXT);
if (!spanContextOptional.isPresent()) {
logger.warning("Failed to find Sp... | class OpenTelemetryTracer implements com.azure.core.implementation.tracing.Tracer {
private static final Tracer TRACER = Tracing.getTracer();
private static final String OPENTELEMETRY_SPAN_KEY = com.azure.core.implementation.tracing.Tracer.OPENTELEMETRY_SPAN_KEY;
private static final String OPENTELEMETRY_SPAN_NAME_KEY ... | class OpenTelemetryTracer implements com.azure.core.implementation.tracing.Tracer {
private static final Tracer TRACER = Tracing.getTracer();
private static final String COMPONENT = "component";
private static final String MESSAGE_BUS_DESTINATION = "message_bus.destination";
private static final String PEER_ENDPOINT = ... |
This is the spec - https://gist.github.com/lmolkova/e4215c0f44a49ef824983382762e6b92#file-minimal_instrumentation-md | public static String getDiagnosticId(SpanContext spanContext) {
char[] chars = new char[55];
chars[0] = '0';
chars[1] = '0';
chars[2] = '-';
spanContext.getTraceId().copyLowerBase16To(chars, 3);
chars[35] = '-';
spanContext.getSpanId().copyLowerBase16To(chars, 36);
chars[52] = '-';
spanContext.getTraceOptions().copyLow... | char[] chars = new char[55]; | public static String getDiagnosticId(SpanContext spanContext) {
char[] chars = new char[55];
chars[0] = '0';
chars[1] = '0';
chars[2] = '-';
spanContext.getTraceId().copyLowerBase16To(chars, 3);
chars[35] = '-';
spanContext.getSpanId().copyLowerBase16To(chars, 36);
chars[52] = '-';
spanContext.getTraceOptions().copyLow... | class AmqpPropagationFormatUtil {
private static final String SPAN_CONTEXT = Tracer.OPENTELEMETRY_AMQP_EVENT_SPAN_CONTEXT;
private AmqpPropagationFormatUtil() { }
/**
* This method is called to extract the Span Context information from the received event's diagnostic Id.
*
* @param diagnosticId The diagnostic Id for th... | class AmqpPropagationFormatUtil {
private AmqpPropagationFormatUtil() { }
/**
* This method is called to extract the Span Context information from the received event's diagnostic Id.
*
* @param diagnosticId The dignostic Id providing an unique identifier for individual traces and requests
* @return {@link Context} whic... |
Can we add documentation in the javadocs how this gets created? A year from now, someone else looking at this would have no idea. | public static String getDiagnosticId(SpanContext spanContext) {
char[] chars = new char[55];
chars[0] = '0';
chars[1] = '0';
chars[2] = '-';
spanContext.getTraceId().copyLowerBase16To(chars, 3);
chars[35] = '-';
spanContext.getSpanId().copyLowerBase16To(chars, 36);
chars[52] = '-';
spanContext.getTraceOptions().copyLow... | char[] chars = new char[55]; | public static String getDiagnosticId(SpanContext spanContext) {
char[] chars = new char[55];
chars[0] = '0';
chars[1] = '0';
chars[2] = '-';
spanContext.getTraceId().copyLowerBase16To(chars, 3);
chars[35] = '-';
spanContext.getSpanId().copyLowerBase16To(chars, 36);
chars[52] = '-';
spanContext.getTraceOptions().copyLow... | class AmqpPropagationFormatUtil {
private static final String SPAN_CONTEXT = Tracer.OPENTELEMETRY_AMQP_EVENT_SPAN_CONTEXT;
private AmqpPropagationFormatUtil() { }
/**
* This method is called to extract the Span Context information from the received event's diagnostic Id.
*
* @param diagnosticId The diagnostic Id for th... | class AmqpPropagationFormatUtil {
private AmqpPropagationFormatUtil() { }
/**
* This method is called to extract the Span Context information from the received event's diagnostic Id.
*
* @param diagnosticId The dignostic Id providing an unique identifier for individual traces and requests
* @return {@link Context} whic... |
I recall this is asyn call `partitionProcessor.processEvent`, right? If so, `endScopedTracingSpan(processSpanContext)` happens before user code returns? Or am I missing something? | private void receiveEvents(PartitionOwnership partitionOwnership) {
EventHubConsumerOptions consumerOptions = new EventHubConsumerOptions();
consumerOptions.ownerLevel(0L);
EventPosition startFromEventPosition = partitionOwnership.sequenceNumber() == null ? this.initialEventPosition
: EventPosition.fromSequenceNumber(p... | partitionProcessor.processEvent(eventData).subscribe(unused -> { | private void receiveEvents(PartitionOwnership partitionOwnership) {
EventHubConsumerOptions consumerOptions = new EventHubConsumerOptions();
consumerOptions.ownerLevel(0L);
EventPosition startFromEventPosition = partitionOwnership.sequenceNumber() == null ? this.initialEventPosition
: EventPosition.fromSequenceNumber(p... | class EventProcessor {
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(EventProcessor.class);
private final EventHubAsyncCl... | class EventProcessor {
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(EventProcessor.class);
private final EventHubAsyncCl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.