muttakin2301/ccr_train_1000 huggingface dataset:
Code review comment: ```suggestion             : String.format("/file/%s/%s", account, shareName); ```

Code before review:
private static String getCanonicalName(String account, String shareName, String filePath) {
return ImplUtils.isNullOrEmpty(filePath)
? String.format("/file/%s/%s/%s",account, shareName, filePath.replace("\\", "/"))
: String.format("/file/%s/%s",account, shareName);
}

Line under review: : String.format("/file/%s/%s",account, shareName);

Code after addressing the review:
private static String getCanonicalName(String account, String shareName, String filePath) {
return !ImplUtils.isNullOrEmpty(filePath)
? String.format("/file/%s/%s/%s", account, shareName, filePath.replace("\\", "/"))
: String.format("/file/%s/%s", account, shareName);
}
Code review comment: I think for clarity I'd make this just return the UUID without the `-` and have the caller handle doing the substring. Seeing `32 - length` is fairly confusing and likely could be error prone as you pass `15` for the length but you really get `17`.

Code before review:
private static String getRandomId(int length) {
return CoreUtils.randomUuid().toString()
.replace("-", "")
.substring(32 - length);
}

Line under review: .substring(32 - length);

Code after addressing the review:
private static String getRandomId(int length) {
return CoreUtils.randomUuid().toString()
.replace("-", "")
.substring(32 - length);
}
Code review comment: ```suggestion         this.deliveryGuarantee = checkNotNull(deliveryGuarantee, "deliveryGuarantee"); ``` or leave that param out as discussed.

Code before review:
KafkaSinkBuilder<IN> setDeliverGuarantee(DeliveryGuarantee deliveryGuarantee) {
this.deliveryGuarantee = checkNotNull(deliveryGuarantee, "semantic");
return this;
}

Line under review: this.deliveryGuarantee = checkNotNull(deliveryGuarantee, "semantic");

Code after addressing the review:
KafkaSinkBuilder<IN> setDeliverGuarantee(DeliveryGuarantee deliveryGuarantee) {
this.deliveryGuarantee = checkNotNull(deliveryGuarantee, "deliveryGuarantee");
return this;
}
Code review comment: I think it would be helpful to print the expected signature in case the user passes wrong arguments?

Code before review:
public List<Signature> getExpectedSignatures(FunctionDefinition definition) {
return Collections.singletonList(Signature.of(Signature.Argument.of("*")));
}

Line under review: return Collections.singletonList(Signature.of(Signature.Argument.of("*")));

Code after addressing the review:
public List<Signature> getExpectedSignatures(FunctionDefinition definition) {
return Collections.singletonList(Signature.of(Signature.Argument.of("*")));
}
Code review comment: nit: this comment basically repeats what the code does, I think it's unnecessary

Code before review:
public void testExpiredCheckpointExceedsTolerableFailureNumber() {
ExecutionVertex vertex1 = mockExecutionVertex(new ExecutionAttemptID());
ExecutionVertex vertex2 = mockExecutionVertex(new ExecutionAttemptID());
final String errorMsg = "Exceeded checkpoint failure tolerance number!";
CheckpointFailureManager checkpointFailureManager = getCheckpointFailureManager(errorMsg);
CheckpointCoordinator coord = getCheckpointCoordinator(new JobID(), vertex1, vertex2, checkpointFailureManager);
try {
final CompletableFuture<CompletedCheckpoint> checkPointFuture = coord.triggerCheckpoint(false);
manuallyTriggeredScheduledExecutor.triggerAll();
assertFalse(checkPointFuture.isCompletedExceptionally());
coord.abortPendingCheckpoints(new CheckpointException(CHECKPOINT_EXPIRED));
fail("Test failed.");
}
catch (Exception e) {
assertTrue(e instanceof RuntimeException);
assertEquals(errorMsg, e.getMessage());
} finally {
try {
coord.shutdown(JobStatus.FINISHED);
} catch (Exception e) {
e.printStackTrace();
fail(e.getMessage());
}
}
}


Code after addressing the review:
public void testExpiredCheckpointExceedsTolerableFailureNumber() throws Exception {
ExecutionVertex vertex1 = mockExecutionVertex(new ExecutionAttemptID());
ExecutionVertex vertex2 = mockExecutionVertex(new ExecutionAttemptID());
final String errorMsg = "Exceeded checkpoint failure tolerance number!";
CheckpointFailureManager checkpointFailureManager = getCheckpointFailureManager(errorMsg);
CheckpointCoordinator coord = getCheckpointCoordinator(new JobID(), vertex1, vertex2, checkpointFailureManager);
try {
coord.triggerCheckpoint(false);
manuallyTriggeredScheduledExecutor.triggerAll();
coord.abortPendingCheckpoints(new CheckpointException(CHECKPOINT_EXPIRED));
fail("Test failed.");
}
catch (Exception e) {
assertTrue(e instanceof RuntimeException);
assertEquals(errorMsg, e.getMessage());
} finally {
coord.shutdown(JobStatus.FINISHED);
}
}
Code review comment: ? I think it's indented correctly.

Code before review:
private static List<SubtaskCheckpointStatistics> createSubtaskCheckpointStatistics(SubtaskStateStats[] subtaskStateStats, long triggerTimestamp) {
final List<SubtaskCheckpointStatistics> result = new ArrayList<>(subtaskStateStats.length);
for (int i = 0; i < subtaskStateStats.length; i++) {
final SubtaskStateStats subtask = subtaskStateStats[i];
if (subtask == null) {
result.add(new SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics(i));
} else {
result.add(new SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics(
i,
subtask.getAckTimestamp(),
subtask.getEndToEndDuration(triggerTimestamp),
subtask.getStateSize(),
new SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.CheckpointDuration(
subtask.getSyncCheckpointDuration(),
subtask.getAsyncCheckpointDuration()),
new SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.CheckpointAlignment(
subtask.getAlignmentBuffered(),
subtask.getAlignmentDuration()),
subtask.getCheckpointStartDelay()
));
}
}
return result;
}

Line under review: subtask.getCheckpointStartDelay()

Code after addressing the review:
private static List<SubtaskCheckpointStatistics> createSubtaskCheckpointStatistics(SubtaskStateStats[] subtaskStateStats, long triggerTimestamp) {
final List<SubtaskCheckpointStatistics> result = new ArrayList<>(subtaskStateStats.length);
for (int i = 0; i < subtaskStateStats.length; i++) {
final SubtaskStateStats subtask = subtaskStateStats[i];
if (subtask == null) {
result.add(new SubtaskCheckpointStatistics.PendingSubtaskCheckpointStatistics(i));
} else {
result.add(new SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics(
i,
subtask.getAckTimestamp(),
subtask.getEndToEndDuration(triggerTimestamp),
subtask.getStateSize(),
new SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.CheckpointDuration(
subtask.getSyncCheckpointDuration(),
subtask.getAsyncCheckpointDuration()),
new SubtaskCheckpointStatistics.CompletedSubtaskCheckpointStatistics.CheckpointAlignment(
subtask.getAlignmentBuffered(),
subtask.getAlignmentDuration()),
subtask.getCheckpointStartDelay()
));
}
}
return result;
}
Code review comment: Shoud we print out the info log that we're adding automatically inferred extra packages?

Code before review:
public PCollection<OutputT> expand(PCollection<?> input) {
Coder<OutputT> outputCoder;
if (this.keyCoder == null) {
outputCoder = (Coder<OutputT>) RowCoder.of(schema);
} else {
outputCoder = (Coder<OutputT>) KvCoder.of(keyCoder, RowCoder.of(schema));
}
if (this.extraPackages.isEmpty()) {
this.extraPackages.addAll(mayBeInferExtraPackagesFromModelHandler());
}
return (PCollection<OutputT>)
input.apply(
PythonExternalTransform.<PCollection<?>, PCollection<Row>>from(
"apache_beam.ml.inference.base.RunInference.from_callable", expansionService)
.withKwarg("model_handler_provider", PythonCallableSource.of(modelLoader))
.withOutputCoder(outputCoder)
.withExtraPackages(this.extraPackages)
.withKwargs(kwargs));
}

Line under review: this.extraPackages.addAll(mayBeInferExtraPackagesFromModelHandler());

Code after addressing the review:
public PCollection<OutputT> expand(PCollection<?> input) {
Coder<OutputT> outputCoder;
if (this.keyCoder == null) {
outputCoder = (Coder<OutputT>) RowCoder.of(schema);
} else {
outputCoder = (Coder<OutputT>) KvCoder.of(keyCoder, RowCoder.of(schema));
}
if (this.extraPackages.isEmpty()) {
this.extraPackages.addAll(inferExtraPackagesFromModelHandler());
}
return (PCollection<OutputT>)
input.apply(
PythonExternalTransform.<PCollection<?>, PCollection<Row>>from(
"apache_beam.ml.inference.base.RunInference.from_callable", expansionService)
.withKwarg("model_handler_provider", PythonCallableSource.of(modelLoader))
.withOutputCoder(outputCoder)
.withExtraPackages(this.extraPackages)
.withKwargs(kwargs));
}
Code review comment: ```suggestion 			AccessExecutionVertex[] taskVertices = ejv.getTaskVertices(); ``` Could we do this renaming to improve the readability since we're dealing with different types of vertices in this code segment?

Code before review:
public static JobDetails createDetailsForJob(AccessExecutionGraph job) {
JobStatus status = job.getState();
long started = job.getStatusTimestamp(JobStatus.INITIALIZING);
long finished = status.isGloballyTerminalState() ? job.getStatusTimestamp(status) : -1L;
long duration = (finished >= 0L ? finished : System.currentTimeMillis()) - started;
int[] countsPerStatus = new int[ExecutionState.values().length];
long lastChanged = 0;
int numTotalTasks = 0;
for (AccessExecutionJobVertex ejv : job.getVerticesTopologically()) {
AccessExecutionVertex[] vertices = ejv.getTaskVertices();
numTotalTasks += vertices.length;
for (AccessExecutionVertex vertex : vertices) {
ExecutionState state = vertex.getExecutionState();
countsPerStatus[state.ordinal()]++;
lastChanged = Math.max(lastChanged, vertex.getStateTimestamp(state));
}
}
lastChanged = Math.max(lastChanged, finished);
return new JobDetails(
job.getJobID(),
job.getJobName(),
started,
finished,
duration,
status,
lastChanged,
countsPerStatus,
numTotalTasks);
}

Line under review: AccessExecutionVertex[] vertices = ejv.getTaskVertices();

Code after addressing the review:
public static JobDetails createDetailsForJob(AccessExecutionGraph job) {
JobStatus status = job.getState();
long started = job.getStatusTimestamp(JobStatus.INITIALIZING);
long finished = status.isGloballyTerminalState() ? job.getStatusTimestamp(status) : -1L;
long duration = (finished >= 0L ? finished : System.currentTimeMillis()) - started;
int[] countsPerStatus = new int[ExecutionState.values().length];
long lastChanged = 0;
int numTotalTasks = 0;
for (AccessExecutionJobVertex ejv : job.getVerticesTopologically()) {
AccessExecutionVertex[] taskVertices = ejv.getTaskVertices();
numTotalTasks += taskVertices.length;
for (AccessExecutionVertex taskVertex : taskVertices) {
ExecutionState state = taskVertex.getExecutionState();
countsPerStatus[state.ordinal()]++;
lastChanged = Math.max(lastChanged, taskVertex.getStateTimestamp(state));
}
}
lastChanged = Math.max(lastChanged, finished);
return new JobDetails(
job.getJobID(),
job.getJobName(),
started,
finished,
duration,
status,
lastChanged,
countsPerStatus,
numTotalTasks);
}
Code review comment: why only the first? not all children?

Code before review:
public boolean isSelfMonotonic() {
return children.get(0).isSelfMonotonic();
}

Line under review: return children.get(0).isSelfMonotonic();

Code after addressing the review:
public boolean isSelfMonotonic() {
return children.get(0).isSelfMonotonic();
}
Code review comment: This input stream could be closed properly.

Code before review:
public void testStreamWithEmptyByteArray() throws IOException {
final byte[] data = new byte[0];
final ByteStreamStateHandle handle = new ByteStreamStateHandle("name", data);
FSDataInputStream in = handle.openInputStream();
in.seek(0);
byte[] dataGot = new byte[1];
assertEquals(0, in.read(dataGot, 0, 0));
}

Line under review: FSDataInputStream in = handle.openInputStream();

Code after addressing the review:
public void testStreamWithEmptyByteArray() throws IOException {
final byte[] data = new byte[0];
final ByteStreamStateHandle handle = new ByteStreamStateHandle("name", data);
try (FSDataInputStream in = handle.openInputStream()) {
byte[] dataGot = new byte[1];
assertEquals(0, in.read(dataGot, 0, 0));
assertEquals(-1, in.read());
}
}
Code review comment: No idea, please look at the most up-to-date close() functionality to make sure it is fine. 

Code before review:
public void close() throws IOException {
if (session == null) {
return;
}
try (Closer closer = Closer.create()) {
session.close();
} finally {
session = null;
}
}

Line under review: }

Code after addressing the review:
public void close() throws IOException {
if (session == null) {
return;
}
try (Closer closer = Closer.create()) {
if (results != null) {
closer.register(results);
results = null;
}
session.close();
} finally {
session = null;
}
}
Code review comment: should we also do this optimisation for other strategies to compare performance in a cleaner way?

Code before review:
private void maybeScheduleRegion(final SchedulingPipelinedRegion region) {
if (!areRegionInputsAllConsumable(region)) {
return;
}
checkState(areRegionVerticesAllInCreatedState(region), "BUG: trying to schedule a region which is not in CREATED state");
final List<ExecutionVertexDeploymentOption> vertexDeploymentOptions =
SchedulingStrategyUtils.createExecutionVertexDeploymentOptions(
regionVerticesSorted.get(region),
id -> deploymentOption);
schedulerOperations.allocateSlotsAndDeploy(vertexDeploymentOptions);
}

Line under review: SchedulingStrategyUtils.createExecutionVertexDeploymentOptions(

Code after addressing the review:
private void maybeScheduleRegion(final SchedulingPipelinedRegion region) {
if (!areRegionInputsAllConsumable(region)) {
return;
}
checkState(areRegionVerticesAllInCreatedState(region), "BUG: trying to schedule a region which is not in CREATED state");
final List<ExecutionVertexDeploymentOption> vertexDeploymentOptions =
SchedulingStrategyUtils.createExecutionVertexDeploymentOptions(
regionVerticesSorted.get(region),
id -> deploymentOption);
schedulerOperations.allocateSlotsAndDeploy(vertexDeploymentOptions);
}
Code review comment: Ah, I see what you mean.  Yes, we can certainly do that.

Code before review:
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
if (serviceBindings.isEmpty()) {
return Collections.emptyList();
}
List<ConfigSource> result = new ArrayList<>();
for (ServiceBindingConverter converter : serviceBindingConverters) {
Optional<ServiceBindingConfigSource> optional = converter.convert(serviceBindings);
if (optional.isPresent()) {
result.add(optional.get());
}
}
return result;
}

Line under review: if (optional.isPresent()) {

Code after addressing the review:
public Iterable<ConfigSource> getConfigSources(ClassLoader forClassLoader) {
if (serviceBindings.isEmpty()) {
return Collections.emptyList();
}
List<ConfigSource> result = new ArrayList<>();
for (ServiceBindingConverter converter : serviceBindingConverters) {
Optional<ServiceBindingConfigSource> optional = converter.convert(serviceBindings);
if (optional.isPresent()) {
result.add(optional.get());
}
}
for (ServiceBinding serviceBinding : serviceBindings) {
Map<String, String> serviceBindingProperties = serviceBinding.getProperties();
Map<String, String> rawConfigSourceProperties = new HashMap<>();
for (Map.Entry<String, String> entry : serviceBindingProperties.entrySet()) {
rawConfigSourceProperties.put("quarkus." + serviceBinding.getName() + "." + entry.getKey(), entry.getValue());
}
result.add(new ServiceBindingConfigSource("service-binding-" + serviceBinding.getName() + "-raw",
rawConfigSourceProperties));
}
return result;
}
Code review comment: thoughts on moving 429 and 503 checks to `RetryStrategy::calculateRetryDelay(HttpResponse, int)` as well? this way we ensure `RetryStrategy::calculateRetryDelay(HttpResponse, int)` is always gets called

Code before review:
private Duration determineDelayDuration(HttpResponse response, int tryCount) {
int code = response.getStatusCode();
if (code != 429
&& code != 503) {
return retryStrategy.calculateRetryDelay(tryCount);
}
return retryStrategy.calculateRetryDelay(response, tryCount);
}

Line under review: && code != 503) {

Code after addressing the review:
private Duration determineDelayDuration(HttpResponse response, int tryCount) {
int code = response.getStatusCode();
if (code != 429
&& code != 503) {
return retryStrategy.calculateRetryDelay(tryCount);
}
String retryHeaderValue = null;
if (!isNullOrEmpty(this.retryAfterHeader)) {
retryHeaderValue = response.getHeaderValue(this.retryAfterHeader);
}
if (isNullOrEmpty(retryHeaderValue)) {
return this.retryStrategy.calculateRetryDelay(tryCount);
}
return Duration.of(Integer.parseInt(retryHeaderValue), this.retryAfterTimeUnit);
}
Code review comment: I thick there will be read/write conflict if you do not get the read lock here.

Code before review:
public void removeOldTaskInfo() {
long currentTimeMs = System.currentTimeMillis();
List<Task> currentTask = showTasks(null);
Iterator<Task> iterator = currentTask.iterator();
List<Long> taskIdToDelete = Lists.newArrayList();
while (iterator.hasNext()) {
Task task = iterator.next();
Long expireTime = task.getExpireTime();
if (expireTime > 0 && currentTimeMs > expireTime) {
taskIdToDelete.add(task.getId());
}
}
dropTasks(taskIdToDelete, true);
}

Line under review: Task task = iterator.next();

Code after addressing the review:
public void removeOldTaskInfo() {
long currentTimeMs = System.currentTimeMillis();
List<Long> taskIdToDelete = Lists.newArrayList();
if (!tryTaskLock()) {
return;
}
try {
List<Task> currentTask = showTasks(null);
for (Task task : currentTask) {
Long expireTime = task.getExpireTime();
if (expireTime > 0 && currentTimeMs > expireTime) {
taskIdToDelete.add(task.getId());
}
}
} finally {
taskUnlock();
}
dropTasks(taskIdToDelete, true);
}
Code review comment: Just to be sure - there is no way we can be on the I/O thread here, right?

Code before review:
public Iterable<ConfigSource> getConfigSources(ClassLoader cl) {
Map<String, ValueType> keys = config.keysAsMap();
if (keys.isEmpty()) {
log.debug("No keys were configured for config source lookup");
return Collections.emptyList();
}
List<ConfigSource> result = new ArrayList<>(keys.size());
List<Uni<?>> allUnis = new ArrayList<>();
for (Map.Entry<String, ValueType> entry : keys.entrySet()) {
String fullKey = config.prefix.isPresent() ? config.prefix.get() + "/" + entry.getKey() : entry.getKey();
allUnis.add(consulConfigGateway.getValue(fullKey).chain(new Function<Response, Uni<?>>() {
@Override
public Uni<?> apply(Response response) {
if (response != null) {
result.add(
responseConfigSourceUtil.toConfigSource(response, entry.getValue(),
config.prefix));
} else {
String message = "Key '" + fullKey + "' not found in Consul.";
if (config.failOnMissingKey) {
return Uni.createFrom().failure(new RuntimeException(message));
} else {
log.info(message);
return Uni.createFrom().nullItem();
}
}
return Uni.createFrom().nullItem();
}
}));
}
try {
Uni.combine().all().unis(allUnis).discardItems().await()
.atMost(config.agent.connectionTimeout.plus(config.agent.readTimeout.multipliedBy(2)));
} catch (CompletionException e) {
throw new RuntimeException("An error occurred while attempting to fetch configuration from Consul.", e);
} finally {
consulConfigGateway.close();
}
return result;
}

Line under review: }

Code after addressing the review:
public Iterable<ConfigSource> getConfigSources(ClassLoader cl) {
Map<String, ValueType> keys = config.keysAsMap();
if (keys.isEmpty()) {
log.debug("No keys were configured for config source lookup");
return Collections.emptyList();
}
List<ConfigSource> result = new ArrayList<>(keys.size());
List<Uni<?>> allUnis = new ArrayList<>();
for (Map.Entry<String, ValueType> entry : keys.entrySet()) {
String fullKey = config.prefix.isPresent() ? config.prefix.get() + "/" + entry.getKey() : entry.getKey();
allUnis.add(consulConfigGateway.getValue(fullKey).invoke(new Consumer<Response>() {
@Override
public void accept(Response response) {
if (response != null) {
result.add(
responseConfigSourceUtil.toConfigSource(response, entry.getValue(),
config.prefix));
} else {
String message = "Key '" + fullKey + "' not found in Consul.";
if (config.failOnMissingKey) {
throw new RuntimeException(message);
} else {
log.info(message);
}
}
}
}));
}
try {
Uni.combine().all().unis(allUnis).discardItems().await()
.atMost(config.agent.connectionTimeout.plus(config.agent.readTimeout.multipliedBy(2)));
} catch (CompletionException e) {
throw new RuntimeException("An error occurred while attempting to fetch configuration from Consul.", e);
} finally {
consulConfigGateway.close();
}
return result;
}
Code review comment: You should close it before set client null

Code before review:
private void close() {
logger.trace("Connect status before close with '{}' is '{}'.", routing, isConnected);
isConnected = false;
if (null != client) {
client = null;
}
if ((transport != null) && transport.isOpen()) {
transport.close();
logger.info("Closed a connection to {}.", routing);
}
}

Line under review: if (null != client) {

Code after addressing the review:
private void close() {
logger.trace("Connect status before close with '{}' is '{}'.", routing, isConnected);
isConnected = false;
if ((transport != null) && transport.isOpen()) {
transport.close();
logger.info("Closed a connection to {}.", routing);
}
if (null != client) {
client = null;
}
}
Code review comment: > It shouldn't be calling `toString` unless it was enabled already.  ah right. Sorry I was thinking of the method whith takes String. nevermind then.  > However you bring up a different point, ...  JBoss Logger was actually enhanced to specifically allow dead code removal from ranges which are disabled at compile time. I suppose adding the guard I suggested makes the whole block eligible for removal - including the string message should be removed.  

Code before review:
BeanContainerListenerBuildItem build(InfinispanTemplate template, PropertiesBuildItem builderBuildItem) {
Properties properties = builderBuildItem.getProperties();
InfinispanClientConfiguration conf = infinispanClient;
final Optional<String> serverList = conf.serverList;
log.debugf("Applying micro profile configuration: %s", conf);
if (serverList.isPresent()) {
properties.putIfAbsent(ConfigurationProperties.SERVER_LIST, serverList.get());
}
int maxEntries = conf.nearCacheMaxEntries;
if (maxEntries > 0 && !properties.containsKey(ConfigurationProperties.NEAR_CACHE_MODE)) {
properties.put(ConfigurationProperties.NEAR_CACHE_MODE, NearCacheMode.INVALIDATED);
properties.putIfAbsent(ConfigurationProperties.NEAR_CACHE_MAX_ENTRIES, maxEntries);
}
final Optional<String> namePattern = conf.nearCacheNamePattern;
if (namePattern.isPresent()) {
properties.putIfAbsent(ConfigurationProperties.NEAR_CACHE_NAME_PATTERN, namePattern);
}
return new BeanContainerListenerBuildItem(template.configureInfinispan(properties));
}

Line under review: log.debugf("Applying micro profile configuration: %s", conf);

Code after addressing the review:
BeanContainerListenerBuildItem build(InfinispanTemplate template, PropertiesBuildItem builderBuildItem) {
Properties properties = builderBuildItem.getProperties();
InfinispanClientConfiguration conf = infinispanClient;
final Optional<String> serverList = conf.serverList;
if (log.isDebugEnabled()) {
log.debugf("Applying micro profile configuration: %s", conf);
}
if (serverList.isPresent()) {
properties.putIfAbsent(ConfigurationProperties.SERVER_LIST, serverList.get());
}
int maxEntries = conf.nearCacheMaxEntries;
if (maxEntries > 0 && !properties.containsKey(ConfigurationProperties.NEAR_CACHE_MODE)) {
properties.put(ConfigurationProperties.NEAR_CACHE_MODE, NearCacheMode.INVALIDATED);
properties.putIfAbsent(ConfigurationProperties.NEAR_CACHE_MAX_ENTRIES, maxEntries);
}
return new BeanContainerListenerBuildItem(template.configureInfinispan(properties));
}
Code review comment: `containsExactlyInAnyOrder` would be more precise here

Code before review:
public void testLeaderInformationChangeNotifiesListener() throws Exception {
new TestFixture() {
{
runTest(
() -> {
leaderCallbackGrantLeadership();
final String componentA = "componentA";
final LeaderInformation leaderInformationA =
LeaderInformation.known(UUID.randomUUID(), "localhost");
final String componentB = "componentB";
final LeaderInformation leaderInformationB =
LeaderInformation.known(UUID.randomUUID(), "localhost");
leaderElectionDriver.publishLeaderInformation(
componentA, leaderInformationA);
leaderElectionDriver.publishLeaderInformation(
componentB, leaderInformationB);
notifyLeaderElectionWatchOnModifiedConfigMap();
final LeaderElectionEvent.AllKnownLeaderInformationEvent
allKnownLeaderInformationEvent =
leaderElectionListener.await(
LeaderElectionEvent
.AllKnownLeaderInformationEvent.class);
assertThat(
allKnownLeaderInformationEvent
.getLeaderInformationWithComponentIds())
.contains(
LeaderInformationWithComponentId.create(
componentA, leaderInformationA),
LeaderInformationWithComponentId.create(
componentB, leaderInformationB));
});
}
};
}

Line under review: .contains(

Code after addressing the review:
public void testLeaderInformationChangeNotifiesListener() throws Exception {
new TestFixture() {
{
runTest(
() -> {
leaderCallbackGrantLeadership();
final String componentA = "componentA";
final LeaderInformation leaderInformationA =
LeaderInformation.known(UUID.randomUUID(), "localhost");
final String componentB = "componentB";
final LeaderInformation leaderInformationB =
LeaderInformation.known(UUID.randomUUID(), "localhost");
leaderElectionDriver.publishLeaderInformation(
componentA, leaderInformationA);
leaderElectionDriver.publishLeaderInformation(
componentB, leaderInformationB);
notifyLeaderElectionWatchOnModifiedConfigMap();
final LeaderElectionEvent.AllKnownLeaderInformationEvent
allKnownLeaderInformationEvent =
leaderElectionListener.await(
LeaderElectionEvent
.AllKnownLeaderInformationEvent.class);
assertThat(
allKnownLeaderInformationEvent
.getLeaderInformationWithComponentIds())
.containsExactlyInAnyOrder(
LeaderInformationWithComponentId.create(
componentA, leaderInformationA),
LeaderInformationWithComponentId.create(
componentB, leaderInformationB));
});
}
};
}
Code review comment: Lets use System.out to OUT static variable

Code before review:
private static void handleProfilerArguments(String[] args) {
String invalidArgument = "Invalid CLI Argument";
if (args.length != 0) {
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--file":
balJarName = args[i + 1];
if (balJarName.startsWith("[") && balJarName.endsWith("]")) {
balJarName = balJarName.substring(1, balJarName.length() - 1);
} else {
System.out.printf(invalidArgument + "\n");
}
break;
case "--args":
balJarArgs = args[i + 1];
if (balJarArgs != null && balJarArgs.startsWith("[") && balJarArgs.endsWith("]")) {
balJarArgs = balJarArgs.substring(1, balJarArgs.length() - 1);
} else {
System.out.printf(invalidArgument + "\n");
}
break;
case "--skip":
skipFunctionString = args[i + 1];
if (skipFunctionString != null && skipFunctionString.matches("\\[.*\\]")) {
skipFunctionString = skipFunctionString.substring(1, skipFunctionString.length() - 1);
} else {
System.out.printf(invalidArgument + "\n");
}
break;
default:
System.out.printf(invalidArgument + "\n");
break;
}
}
}
}

Line under review: System.out.printf(invalidArgument + "\n");

Code after addressing the review:
private static void handleProfilerArguments(String[] args) {
String invalidArgument = "Invalid CLI Argument";
if (args.length != 0) {
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--file":
balJarName = args[i + 1];
if (balJarName.startsWith("[") && balJarName.endsWith("]")) {
balJarName = balJarName.substring(1, balJarName.length() - 1);
} else {
OUT.printf(invalidArgument + "\n");
}
break;
case "--args":
balJarArgs = args[i + 1];
if (balJarArgs != null && balJarArgs.startsWith("[") && balJarArgs.endsWith("]")) {
balJarArgs = balJarArgs.substring(1, balJarArgs.length() - 1);
} else {
OUT.printf(invalidArgument + "\n");
}
break;
case "--skip":
skipFunctionString = args[i + 1];
if (skipFunctionString != null && skipFunctionString.matches("\\[.*\\]")) {
skipFunctionString = skipFunctionString.substring(1, skipFunctionString.length() - 1);
} else {
OUT.printf(invalidArgument + "\n");
}
break;
default:
break;
}
}
}
}
Code review comment: One already created bean, which generally won't happen until runtime when you actually have vert.x.   Currently if you fail in static init then this method is called, but vert.x is not ready yet (as it is a runtime bean), so you get an extra unrelated exception in your logs (and possible unclean shutdown).

Code before review:
void undeployVerticles(@Observes @BeforeDestroyed(ApplicationScoped.class) Object event, BeanManager beanManager) {
Set<Bean<?>> beans = beanManager.getBeans(AbstractVerticle.class, Any.Literal.INSTANCE);
Context applicationContext = beanManager.getContext(ApplicationScoped.class);
for (Bean<?> bean : beans) {
if (ApplicationScoped.class.equals(bean.getScope())) {
Object instance = applicationContext.get(bean);
if (instance != null) {
try {
AbstractVerticle verticle = (AbstractVerticle) instance;
io.vertx.mutiny.core.Vertx mutiny = beanManager.createInstance()
.select(io.vertx.mutiny.core.Vertx.class).get();
mutiny.undeploy(verticle.deploymentID()).await().indefinitely();
LOGGER.debugf("Undeployed verticle: %s", instance.getClass());
} catch (Exception e) {
LOGGER.debugf("Unable to undeploy verticle %s: %s", instance.getClass(), e.toString());
}
}
}
}
}

Line under review: io.vertx.mutiny.core.Vertx mutiny = beanManager.createInstance()

Code after addressing the review:
void undeployVerticles(@Observes @BeforeDestroyed(ApplicationScoped.class) Object event, BeanManager beanManager) {
Set<Bean<?>> beans = beanManager.getBeans(AbstractVerticle.class, Any.Literal.INSTANCE);
Context applicationContext = beanManager.getContext(ApplicationScoped.class);
for (Bean<?> bean : beans) {
if (ApplicationScoped.class.equals(bean.getScope())) {
Object instance = applicationContext.get(bean);
if (instance != null) {
try {
AbstractVerticle verticle = (AbstractVerticle) instance;
io.vertx.mutiny.core.Vertx mutiny = beanManager.createInstance()
.select(io.vertx.mutiny.core.Vertx.class).get();
mutiny.undeploy(verticle.deploymentID()).await().indefinitely();
LOGGER.debugf("Undeployed verticle: %s", instance.getClass());
} catch (Exception e) {
LOGGER.debugf("Unable to undeploy verticle %s: %s", instance.getClass(), e.toString());
}
}
}
}
}
Code review comment: It want it to fail hard if it's not `X509Certificate[]`.

Code before review:
public List<X509Certificate> getClientCertificateChain() {
return Optional.ofNullable(parent.context().get(ServletRequest.JDISC_REQUEST_X509CERT))
.map(X509Certificate[].class::cast)
.map(Arrays::asList)
.orElse(Collections.emptyList());
}

Line under review: .map(X509Certificate[].class::cast)

Code after addressing the review:
public List<X509Certificate> getClientCertificateChain() {
return Optional.ofNullable(parent.context().get(ServletRequest.JDISC_REQUEST_X509CERT))
.map(X509Certificate[].class::cast)
.map(Arrays::asList)
.orElse(Collections.emptyList());
}
Code review comment: make this variable static and final?

Code before review:
public static String generatePartitionName(PartitionKeyDesc desc) {
String partitionName = "p_";
Pattern pattern = Pattern.compile("[^a-zA-Z0-9,]");
Matcher matcher = pattern.matcher(desc.toSql());
partitionName += matcher.replaceAll("").replaceAll("\\,", "_");
if (partitionName.length() > 50) {
partitionName = partitionName.substring(0, 30) + Math.abs(Objects.hash(partitionName))
+ "_" + System.currentTimeMillis();
}
return partitionName;
}

Line under review: Pattern pattern = Pattern.compile("[^a-zA-Z0-9,]");

Code after addressing the review:
public static String generatePartitionName(PartitionKeyDesc desc) {
Matcher matcher = PARTITION_NAME_PATTERN.matcher(desc.toSql());
String partitionName = PARTITION_NAME_PREFIX + matcher.replaceAll("").replaceAll("\\,", "_");
if (partitionName.length() > 50) {
partitionName = partitionName.substring(0, 30) + Math.abs(Objects.hash(partitionName))
+ "_" + System.currentTimeMillis();
}
return partitionName;
}
Code review comment: Didn't see the purpose of re-wrapping an IOException

Code before review:
public boolean start() throws IOException {
try {
ConnectionHandler connectionHandler = new ConnectionHandler(source.spec.uri());
connectionHandler.start();
Channel channel = connectionHandler.getChannel();
String queueName = source.spec.queue();
if (source.spec.queueDeclare()) {
channel.queueDeclare(queueName, false, false, false, null);
}
if (source.spec.exchange() != null) {
if (source.spec.exchangeDeclare()) {
channel.exchangeDeclare(source.spec.exchange(), source.spec.exchangeType());
}
if (queueName == null) {
queueName = channel.queueDeclare().getQueue();
}
channel.queueBind(queueName, source.spec.exchange(), source.spec.routingKey());
}
checkpointMark.channel = channel;
consumer = new QueueingConsumer(channel);
channel.txSelect();
channel.setDefaultConsumer(consumer);
channel.basicConsume(queueName, false, consumer);
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
return advance();
}

Line under review: channel.queueBind(queueName, source.spec.exchange(), source.spec.routingKey());

Code after addressing the review:
public boolean start() throws IOException {
try {
connectionHandler = new ConnectionHandler(source.spec.uri());
connectionHandler.start();
Channel channel = connectionHandler.getChannel();
queueName = source.spec.queue();
if (source.spec.queueDeclare()) {
channel.queueDeclare(queueName, false, false, false, null);
}
if (source.spec.exchange() != null) {
if (source.spec.exchangeDeclare()) {
channel.exchangeDeclare(source.spec.exchange(), source.spec.exchangeType());
}
if (queueName == null) {
queueName = channel.queueDeclare().getQueue();
}
channel.queueBind(queueName, source.spec.exchange(), source.spec.routingKey());
}
checkpointMark.channel = channel;
channel.txSelect();
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOException(e);
}
return advance();
}
Code review comment: Better check !isAbsolute() and append else set the abosolute path

Code before review:
private void setLogProperties() {
final Path projectRoot = Paths.get(System.getProperty(USER_DIR));
if (projectRoot != null) {
String logDir = getTransactionLogDirectory();
String logPath = projectRoot.toAbsolutePath().toString() + File.separatorChar + logDir;
Path transactionLogDirectory = Paths.get(logPath);
if (!Files.exists(transactionLogDirectory)) {
try {
Files.createDirectory(transactionLogDirectory);
} catch (IOException e) {
stderr.println("error: failed to create '" + logDir + "' transaction log directory");
}
}
System.setProperty(ATOMIKOS_LOG_BASE_PROPERTY, logPath);
System.setProperty(ATOMIKOS_LOG_NAME_PROPERTY, "transaction_recovery");
System.setProperty(ATOMIKOS_REGISTERED_PROPERTY, "not-registered");
}
}

Line under review: String logPath = projectRoot.toAbsolutePath().toString() + File.separatorChar + logDir;

Code after addressing the review:
private void setLogProperties() {
final Path projectRoot = Paths.get(RuntimeUtils.USER_DIR);
if (projectRoot != null) {
String logDir = getTransactionLogDirectory();
Path logDirPath = Paths.get(logDir);
Path transactionLogDirectory;
if (!logDirPath.isAbsolute()) {
logDir = projectRoot.toAbsolutePath().toString() + File.separatorChar + logDir;
transactionLogDirectory = Paths.get(logDir);
} else {
transactionLogDirectory = logDirPath;
}
if (!Files.exists(transactionLogDirectory)) {
try {
Files.createDirectory(transactionLogDirectory);
} catch (IOException e) {
stderr.println("error: failed to create transaction log directory in " + logDir);
}
}
System.setProperty(ATOMIKOS_LOG_BASE_PROPERTY, logDir);
System.setProperty(ATOMIKOS_LOG_NAME_PROPERTY, "transaction_recovery");
System.setProperty(ATOMIKOS_REGISTERED_PROPERTY, "not-registered");
}
}
Code review comment: Shall we do this like `return A && B && C`

Code before review:
private boolean checkInvalidActionInvocation(BLangInvocation.BLangActionInvocation aInv) {
if (aInv.expr.getKind() == NodeKind.SIMPLE_VARIABLE_REF &&
(((((BLangSimpleVarRef) aInv.expr).symbol.tag & SymTag.ENDPOINT) !=
SymTag.ENDPOINT) && !aInv.async)) {
return true;
} else {
return false;
}
}

Line under review: if (aInv.expr.getKind() == NodeKind.SIMPLE_VARIABLE_REF &&

Code after addressing the review:
private boolean checkInvalidActionInvocation(BLangInvocation.BLangActionInvocation aInv) {
return aInv.expr.getKind() == NodeKind.SIMPLE_VARIABLE_REF &&
(((((BLangSimpleVarRef) aInv.expr).symbol.tag & SymTag.ENDPOINT) !=
SymTag.ENDPOINT) && !aInv.async);
}
Code review comment: Moved and fixed other issues with 3954b14

Code before review:
public void visit(BLangBinaryExpr binaryExpr) {
if (OperatorKind.AND.equals(binaryExpr.opKind)) {
visitAndExpression(binaryExpr);
} else if (OperatorKind.OR.equals(binaryExpr.opKind)) {
visitOrExpression(binaryExpr);
} else if (binaryExpr.opSymbol.opcode == InstructionCodes.REQ_NULL ||
binaryExpr.opSymbol.opcode == InstructionCodes.RNE_NULL ||
binaryExpr.opSymbol.opcode == InstructionCodes.SEQ_NULL ||
binaryExpr.opSymbol.opcode == InstructionCodes.SNE_NULL) {
BLangExpression expr = (binaryExpr.lhsExpr.type.tag == TypeTags.NIL) ?
binaryExpr.rhsExpr : binaryExpr.lhsExpr;
genNode(expr, this.env);
emit(binaryExpr.opSymbol.opcode, expr.regIndex, calcAndGetExprRegIndex(binaryExpr));
} else {
genNode(binaryExpr.lhsExpr, this.env);
genNode(binaryExpr.rhsExpr, this.env);
RegIndex regIndex = calcAndGetExprRegIndex(binaryExpr);
int opCode = binaryExpr.opSymbol.opcode;
if (opCode == InstructionCodes.INT_RANGE) {
RegIndex endValRegIndex = binaryExpr.rhsExpr.regIndex;
if (OperatorKind.HALF_OPEN_RANGE.equals(binaryExpr.opKind)) {
endValRegIndex = getRegIndex(TypeTags.INT);
RegIndex constOneRegIndex = getRegIndex(TypeTags.INT);
emit(InstructionCodes.ICONST_1, constOneRegIndex);
emit(InstructionCodes.ISUB, binaryExpr.rhsExpr.regIndex, constOneRegIndex, endValRegIndex);
}
if (binaryExpr.parent instanceof BLangForeach) {
emit(InstructionCodes.NEW_INT_RANGE, binaryExpr.lhsExpr.regIndex, endValRegIndex, regIndex);
} else {
emit(opCode, binaryExpr.lhsExpr.regIndex, endValRegIndex, regIndex);
}
} else {
emit(opCode, binaryExpr.lhsExpr.regIndex, binaryExpr.rhsExpr.regIndex, regIndex);
}
}
}

Line under review: if (OperatorKind.HALF_OPEN_RANGE.equals(binaryExpr.opKind)) {

Code after addressing the review:
public void visit(BLangBinaryExpr binaryExpr) {
if (OperatorKind.AND.equals(binaryExpr.opKind)) {
visitAndExpression(binaryExpr);
} else if (OperatorKind.OR.equals(binaryExpr.opKind)) {
visitOrExpression(binaryExpr);
} else if (binaryExpr.opSymbol.opcode == InstructionCodes.REQ_NULL ||
binaryExpr.opSymbol.opcode == InstructionCodes.RNE_NULL ||
binaryExpr.opSymbol.opcode == InstructionCodes.SEQ_NULL ||
binaryExpr.opSymbol.opcode == InstructionCodes.SNE_NULL) {
BLangExpression expr = (binaryExpr.lhsExpr.type.tag == TypeTags.NIL) ?
binaryExpr.rhsExpr : binaryExpr.lhsExpr;
genNode(expr, this.env);
emit(binaryExpr.opSymbol.opcode, expr.regIndex, calcAndGetExprRegIndex(binaryExpr));
} else {
genNode(binaryExpr.lhsExpr, this.env);
genNode(binaryExpr.rhsExpr, this.env);
RegIndex regIndex = calcAndGetExprRegIndex(binaryExpr);
int opCode = binaryExpr.opSymbol.opcode;
if (opCode == InstructionCodes.INT_RANGE) {
if (binaryExpr.parent instanceof BLangForeach) {
emit(InstructionCodes.NEW_INT_RANGE, binaryExpr.lhsExpr.regIndex, binaryExpr.rhsExpr.regIndex,
regIndex);
} else {
emit(opCode, binaryExpr.lhsExpr.regIndex, binaryExpr.rhsExpr.regIndex, regIndex);
}
} else {
emit(opCode, binaryExpr.lhsExpr.regIndex, binaryExpr.rhsExpr.regIndex, regIndex);
}
}
}
Code review comment: If we are handling only the `versionFlag` and `helpFlag`, then we can get rid of this outer `if` block.

Code before review:
public void execute() {
if (versionFlag) {
printVersionInfo();
return;
}
if (helpFlag) {
if (!argList.isEmpty()) {
printUsageInfo(argList.get(0));
return;
}
}
printUsageInfo(BallerinaCliCommands.HELP);
}

Line under review: if (helpFlag) {

Code after addressing the review:
public void execute() {
if (helpCommands == null) {
printUsageInfo(BallerinaCliCommands.HELP);
return;
} else if (helpCommands.size() > 1) {
throw LauncherUtils.createUsageExceptionWithHelp("too many arguments given");
}
String userCommand = helpCommands.get(0);
if (parentCmdParser.getSubcommands().get(userCommand) == null) {
throw LauncherUtils.createUsageExceptionWithHelp("unknown help topic `" + userCommand + "`");
}
String commandUsageInfo = BLauncherCmd.getCommandUsageInfo(userCommand);
errStream.println(commandUsageInfo);
}
Code review comment: Instead of having a global variable, I think we should either write a separate type visitor to check if both belong to the same ordered type or even just a util method to get the minimum type representing the type of each operand and check if they represent the same basic type, which has to be ordered. Please create an issue, let's fix this separately. 

Code before review:
public Boolean visit(BFiniteType t, BType s) {
if (inOrderedType) {
inOrderedType = false;
return checkValueSpaceHasSameType(t, s);
}
return s == t;
}

Line under review: if (inOrderedType) {

Code after addressing the review:
public Boolean visit(BFiniteType t, BType s) {
if (inOrderedType) {
inOrderedType = false;
return checkValueSpaceHasSameType(t, s);
}
return s == t;
}
Code review comment: internal method should have a blank line

Code before review:
public void watch(final String key, final EventListener eventListener) {
final String path = key + "/";
if (!caches.containsKey(path)) {
addCacheData(key);
}
final PathTree cache = caches.get(path);
cache.watch(new Listener() {
@Override
public void process(final WatchedEvent event) {
if (!Strings.isNullOrEmpty(event.getPath())) {
eventListener.onChange(new DataChangedEvent(getEventType(event), event.getPath(), getWithoutCache(event.getPath())));
}
}
private DataChangedEvent.Type getEventType(final WatchedEvent event) {
switch (event.getType()) {
case NodeDataChanged:
case NodeChildrenChanged:
return DataChangedEvent.Type.UPDATED;
case NodeDeleted:
return DataChangedEvent.Type.DELETED;
default:
return DataChangedEvent.Type.IGNORED;
}
}
});
}

Line under review: @Override

Code after addressing the review:
public void watch(final String key, final EventListener eventListener) {
final String path = key + "/";
if (!caches.containsKey(path)) {
addCacheData(key);
}
final PathTree cache = caches.get(path);
cache.watch(new ZookeeperEventListener() {
@Override
public void process(final WatchedEvent event) {
if (!Strings.isNullOrEmpty(event.getPath())) {
eventListener.onChange(new DataChangedEvent(getEventType(event), event.getPath(), getWithoutCache(event.getPath())));
}
}
private DataChangedEvent.Type getEventType(final WatchedEvent event) {
return extractEventType(event);
}
});
}
Code review comment:  I mean that with [this change](https://github.com/apache/flink/pull/20306#discussion_r930161714), neither wrapping, nor additional flag check (`wrappedStreamClosed`) would be required.  Currently, the composition of streams looks like this: 1. `OutputStreamWithPos` <-- closed by the inner `try` block 1. `BufferedOutputStream` 1. `SnappyFramedOutputStream` or `UncompressedStreamCompressionDecorator` 1. maybe `NonClosingOutputStreamDecorator` <- doesn't proxy `close()` 1. `FSDataOutputStream` <-- closed by the outer `try` block  Where (4) `NonClosingOutputStreamDecorator` is conditional in `wrap()`. But that condition is unnecessary because `StreamCompressionDecorator` instance is already choosen in (3).  So if `decorateWithCompression` would **always** add `NonClosingOutputStreamDecorator` then it should solve the problem.  WDYT? 

Code before review:
private UploadTasksResult upload(Path path, Collection<UploadTask> tasks) throws IOException {
boolean wrappedStreamClosed = false;
FSDataOutputStream fsStream = fileSystem.create(path, NO_OVERWRITE);
try {
fsStream.write(compression ? 1 : 0);
try (OutputStreamWithPos stream = wrap(fsStream)) {
final Map<UploadTask, Map<StateChangeSet, Long>> tasksOffsets = new HashMap<>();
for (UploadTask task : tasks) {
tasksOffsets.put(task, format.write(stream, task.changeSets));
}
StreamStateHandle handle = handleFactory.apply(path, stream.getPos());
changelogRegistry.startTracking(
handle,
tasks.stream()
.flatMap(t -> t.getChangeSets().stream())
.map(StateChangeSet::getLogId)
.collect(Collectors.toSet()));
return new UploadTasksResult(tasksOffsets, handle);
} finally {
wrappedStreamClosed = true;
}
} finally {
if (!wrappedStreamClosed || compression) {
fsStream.close();
}
}
}


Code after addressing the review:
private UploadTasksResult upload(Path path, Collection<UploadTask> tasks) throws IOException {
try (FSDataOutputStream fsStream = fileSystem.create(path, NO_OVERWRITE)) {
fsStream.write(compression ? 1 : 0);
try (OutputStreamWithPos stream = wrap(fsStream)) {
final Map<UploadTask, Map<StateChangeSet, Long>> tasksOffsets = new HashMap<>();
for (UploadTask task : tasks) {
tasksOffsets.put(task, format.write(stream, task.changeSets));
}
StreamStateHandle handle = handleFactory.apply(path, stream.getPos());
changelogRegistry.startTracking(
handle,
tasks.stream()
.flatMap(t -> t.getChangeSets().stream())
.map(StateChangeSet::getLogId)
.collect(Collectors.toSet()));
return new UploadTasksResult(tasksOffsets, handle);
}
}
}
Code review comment: You mean the `tenant-id` and `subscription-id`? it's required for AzureResourceManagerAutoConfiguration, https://github.com/Azure/azure-sdk-for-java/blob/15dda6cdc3219e9128a4d5207cb66d891fd1baf8/sdk/spring/spring-cloud-azure-autoconfigure/src/main/java/com/azure/spring/cloud/autoconfigure/resourcemanager/AzureResourceManagerAutoConfiguration.java#L25

Code before review:
void testAzureProfileWithAzureChina() {
this.contextRunner
.withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class)
.withBean(AzureResourceManager.class, AzureResourceManagerExt::getAzureResourceManager)
.withPropertyValues(
"spring.cloud.azure.profile.tenant-id=test-tenant-id",
"spring.cloud.azure.profile.subscription-id=test-subscription-id",
"spring.cloud.azure.profile.cloud=AZURE_CHINA"
)
.run(context -> {
assertThat(context).hasSingleBean(AzureProfile.class);
AzureProfile azureProfile = context.getBean(AzureProfile.class);
Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(),
AZURE_CHINA.getActiveDirectoryEndpoint());
});
}

Line under review: Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(),

Code after addressing the review:
void testAzureProfileWithAzureChina() {
this.contextRunner
.withUserConfiguration(AzureGlobalPropertiesAutoConfiguration.class)
.withBean(AzureResourceManager.class, TestAzureResourceManager::getAzureResourceManager)
.withPropertyValues(
"spring.cloud.azure.profile.tenant-id=test-tenant-id",
"spring.cloud.azure.profile.subscription-id=test-subscription-id",
"spring.cloud.azure.profile.cloud=AZURE_CHINA"
)
.run(context -> {
assertThat(context).hasSingleBean(AzureProfile.class);
AzureProfile azureProfile = context.getBean(AzureProfile.class);
Assertions.assertEquals(azureProfile.getEnvironment().getActiveDirectoryEndpoint(),
AZURE_CHINA.getActiveDirectoryEndpoint());
});
}
Code review comment: Please remove useless blank line here.

Code before review:
public void assertGetEncryptFuzzyQueryValues() {
List<Object> encryptFuzzyQueryValues = new EncryptRule(createEncryptRuleConfiguration())
.getEncryptFuzzyQueryValues(DefaultDatabase.LOGIC_NAME, DefaultDatabase.LOGIC_NAME, "t_encrypt", "pwd", Collections.singletonList(null));
for (final Object value : encryptFuzzyQueryValues) {
assertNull(value);
}
}

Line under review: .getEncryptFuzzyQueryValues(DefaultDatabase.LOGIC_NAME, DefaultDatabase.LOGIC_NAME, "t_encrypt", "pwd", Collections.singletonList(null));

Code after addressing the review:
public void assertGetEncryptFuzzyQueryValues() {
List<Object> encryptFuzzyQueryValues = new EncryptRule(createEncryptRuleConfiguration())
.getEncryptFuzzyQueryValues(DefaultDatabase.LOGIC_NAME, DefaultDatabase.LOGIC_NAME, "t_encrypt", "pwd", Collections.singletonList(null));
for (Object actual : encryptFuzzyQueryValues) {
assertNull(actual);
}
}