muttakin2301/ccr_train_1000 huggingface dataset:
Code review comment: The grammar seems to allow annotations, but are we handling them?  https://github.com/ballerina-platform/ballerina-lang/pull/21209/files#diff-0e72b59e6b830c29e9c6161f3bb4177aR844  The following should fail since an annotation allowed only on const is being used with a let var, but doesn't.  ```ballerina int globalVar = 5;  const annotation v1 on source const;  public function main() {     int b = let @v1 int x = 4 in 2 * x * globalVar; } ```

Code before review:
public void exitServiceConstructorExpression(BallerinaParser.ServiceConstructorExpressionContext ctx) {
if (isInErrorState) {
return;
}
final DiagnosticPos serviceDefPos = getCurrentPos(ctx);
final String serviceVarName = null;
final DiagnosticPos varPos = serviceDefPos;
this.pkgBuilder.endServiceDef(serviceDefPos, getWS(ctx), serviceVarName, varPos, true,
ctx.serviceConstructorExpr().annotationAttachment().size());
}

Line under review: }

Code after addressing the review:
public void exitServiceConstructorExpression(BallerinaParser.ServiceConstructorExpressionContext ctx) {
if (isInErrorState) {
return;
}
final DiagnosticPos serviceDefPos = getCurrentPos(ctx);
final String serviceVarName = null;
final DiagnosticPos varPos = serviceDefPos;
this.pkgBuilder.endServiceDef(serviceDefPos, getWS(ctx), serviceVarName, varPos, true,
ctx.serviceConstructorExpr().annotationAttachment().size());
}
Code review comment: Would you confirm if it's possible to reconnect to the old JM? if it can happen, the retained partitions will be leaked.

Code before review:
public void jobManagerLostLeadership(final JobID jobId, final JobMasterId jobMasterId) {
log.info(
"JobManager for job {} with leader id {} lost leadership.", jobId, jobMasterId);
runAsync(
() -> {
Optional<JobTable.Connection> connection = jobTable.getConnection(jobId);
if (connection.isPresent()) {
Exception cause =
new Exception(
"Job leader for job id " + jobId + " lost leadership.");
if (isJobRecoveryEnabled()) {
disconnectJobManagerConnectionAndCleanupPartitionLater(
connection.get(), cause);
} else {
disconnectJobManagerConnection(connection.get(), cause);
}
}
});
}

Line under review: disconnectJobManagerConnectionAndCleanupPartitionLater(

Code after addressing the review:
public void jobManagerLostLeadership(final JobID jobId, final JobMasterId jobMasterId) {
log.info(
"JobManager for job {} with leader id {} lost leadership.", jobId, jobMasterId);
runAsync(
() ->
jobTable.getConnection(jobId)
.ifPresent(
jobManagerConnection ->
disconnectJobManagerConnection(
jobManagerConnection,
new Exception(
"Job leader for job id "
+ jobId
+ " lost leadership."),
!shouldRetainPartitionsOnJobManagerConnectionLost())));
}
Code review comment: The difference between `CalciteSqlDialect` and `AntiSqlDialect` is the method `withIdentifierQuoteString()`. Would replacing `\"`  to ```  have any other impact in Flink? 

Code before review:
public String toQuotedSqlString(SqlNode sqlNode) {
SqlParser.Config parserConfig = flinkPlanner.config().getParserConfig();
SqlDialect dialect =
new AnsiSqlDialect(
SqlDialect.EMPTY_CONTEXT
.withQuotedCasing(parserConfig.unquotedCasing())
.withConformance(parserConfig.conformance())
.withUnquotedCasing(parserConfig.unquotedCasing())
.withIdentifierQuoteString(parserConfig.quoting().string));
return sqlNode.toSqlString(dialect).getSql();
}

Line under review: new AnsiSqlDialect(

Code after addressing the review:
public String toQuotedSqlString(SqlNode sqlNode) {
SqlParser.Config parserConfig = flinkPlanner.config().getParserConfig();
SqlDialect dialect =
new AnsiSqlDialect(
SqlDialect.EMPTY_CONTEXT
.withQuotedCasing(parserConfig.unquotedCasing())
.withConformance(parserConfig.conformance())
.withUnquotedCasing(parserConfig.unquotedCasing())
.withIdentifierQuoteString(parserConfig.quoting().string));
return sqlNode.toSqlString(dialect).getSql();
}
Code review comment: The error should be updated?  Let's use something like INCOMPATIBLE_ARGUMENTS. Need to update the actual error also. Maybe   ``` arguments of incompatible types: expected argument(s) of types '[int]', found '[int,int,int]' ```

Code before review:
public static Object call(BFunctionPointer<Object, Object> func, Object... args) {
BFunctionType functionType = (BFunctionType) func.getType();
List<Type> paramTypes = new LinkedList<>();
List<Type> argTypes = new LinkedList<>();
List<Object> argsList = new java.util.ArrayList<>(List.of(Scheduler.getStrand()));
if (checkIsValidPositionalArgs(args, argsList, functionType, paramTypes, argTypes) ||
checkIsValidRestArgs(args, argsList, functionType, paramTypes, argTypes)) {
Type restType =
functionType.restType != null ? ((BArrayType) functionType.restType).getElementType() : null;
throw ErrorCreator.createError(
getModulePrefixedReason(FUNCTION_LANG_LIB, INCOMPATIBLE_TYPES),
BLangExceptionHelper.getErrorDetails(RuntimeErrors.INCOMPATIBLE_TYPE,
new BTupleType(paramTypes, restType), new BTupleType(argTypes)));
}
return func.asyncCall(argsList.toArray(), METADATA);
}

Line under review: BLangExceptionHelper.getErrorDetails(RuntimeErrors.INCOMPATIBLE_TYPE,

Code after addressing the review:
public static Object call(BFunctionPointer<Object, Object> func, Object... args) {
BFunctionType functionType = (BFunctionType) func.getType();
List<Type> paramTypes = new LinkedList<>();
List<Type> argTypes = new LinkedList<>();
List<Object> argsList = new java.util.ArrayList<>(List.of(Scheduler.getStrand()));
if (checkIsValidPositionalArgs(args, argsList, functionType, paramTypes, argTypes) ||
checkIsValidRestArgs(args, argsList, functionType, paramTypes, argTypes)) {
Type restType =
functionType.restType != null ? ((BArrayType) functionType.restType).getElementType() : null;
throw ErrorCreator.createError(
getModulePrefixedReason(FUNCTION_LANG_LIB, INCOMPATIBLE_ARGUMENTS),
BLangExceptionHelper.getErrorDetails(RuntimeErrors.INCOMPATIBLE_ARGUMENTS,
new BTupleType(paramTypes, restType, 0, false), new BTupleType(argTypes)));
}
return func.asyncCall(argsList.toArray(), METADATA);
}
Code review comment: move the logic to a function since it's repeated.

Code before review:
private void cleanup() throws Exception {
ballerinaClient.stopServer();
Files.walk(tempHomeDirectory)
.sorted(Comparator.reverseOrder())
.forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
Assert.fail(e.getMessage(), e);
}
});
Files.walk(tempProjectDirectory)
.sorted(Comparator.reverseOrder())
.forEach(path -> {
try {
Files.delete(path);
} catch (IOException e) {
Assert.fail(e.getMessage(), e);
}
});
}

Line under review: Files.walk(tempHomeDirectory)

Code after addressing the review:
private void cleanup() throws Exception {
ballerinaClient.stopServer();
deleteFiles(tempHomeDirectory);
deleteFiles(tempProjectDirectory);
}
Code review comment: sequence column will keep the original value

Code before review:
private void constructInsertStmt() {
FromClause fromUsedInInsert;
TableRef tableRef = new TableRef(tableName, null);
if (fromClause == null) {
fromUsedInInsert = new FromClause(Lists.newArrayList(tableRef));
} else {
fromUsedInInsert = fromClause.clone();
fromUsedInInsert.getTableRefs().add(0, tableRef);
}
SelectStmt selectStmt = new SelectStmt(
new SelectList(selectListItems, false),
fromUsedInInsert,
whereExpr,
null,
null,
null,
LimitElement.NO_LIMIT
);
insertStmt = new InsertStmt(
new InsertTarget(tableName, null),
null,
cols,
new InsertSource(selectStmt),
null);
}


Code after addressing the review:
private void constructInsertStmt() {
FromClause fromUsedInInsert;
TableRef tableRef = new TableRef(tableName, null);
if (fromClause == null) {
fromUsedInInsert = new FromClause(Lists.newArrayList(tableRef));
} else {
fromUsedInInsert = fromClause.clone();
fromUsedInInsert.getTableRefs().add(0, tableRef);
}
SelectStmt selectStmt = new SelectStmt(
new SelectList(selectListItems, false),
fromUsedInInsert,
whereExpr,
null,
null,
null,
LimitElement.NO_LIMIT
);
insertStmt = new InsertStmt(
new InsertTarget(tableName, null),
null,
cols,
new InsertSource(selectStmt),
null);
}
Code review comment: nit: maybe we could add some `checkState` that we are indeed in the `timer` thread? But I'm not sure if it's possible/easily do-able?

Code before review:
private void onTriggerFailure(@Nullable PendingCheckpoint checkpoint, Throwable throwable) {
try {
if (checkpoint != null && !checkpoint.isDiscarded()) {
int numUnsuccessful = numUnsuccessfulCheckpointsTriggers.incrementAndGet();
LOG.warn(
"Failed to trigger checkpoint {} for job {}. ({} consecutive failed attempts so far)",
checkpoint.getCheckpointId(),
job,
numUnsuccessful,
throwable);
final CheckpointException cause =
getCheckpointException(
CheckpointFailureReason.TRIGGER_CHECKPOINT_FAILURE, throwable);
synchronized (lock) {
abortPendingCheckpoint(checkpoint, cause);
}
}
} finally {
isTriggering = false;
checkQueuedCheckpointTriggerRequest();
}
}

Line under review: LOG.warn(

Code after addressing the review:
private void onTriggerFailure(@Nullable PendingCheckpoint checkpoint, Throwable throwable) {
try {
if (checkpoint != null && !checkpoint.isDiscarded()) {
int numUnsuccessful = numUnsuccessfulCheckpointsTriggers.incrementAndGet();
LOG.warn(
"Failed to trigger checkpoint {} for job {}. ({} consecutive failed attempts so far)",
checkpoint.getCheckpointId(),
job,
numUnsuccessful,
throwable);
final CheckpointException cause =
getCheckpointException(
CheckpointFailureReason.TRIGGER_CHECKPOINT_FAILURE, throwable);
synchronized (lock) {
abortPendingCheckpoint(checkpoint, cause);
}
}
} finally {
isTriggering = false;
checkQueuedCheckpointTriggerRequest();
}
}
Code review comment: Also I would prefer taking a snapshot of out.writerIndex() to be used for the check state condition and the output message to address any thread-safety concerns

Code before review:
void encode(final ByteBuf out) {
final int expectedLength = RntbdRequestFrame.LENGTH + this.headers.computeLength();
final int start = out.writerIndex();
out.writeIntLE(expectedLength);
this.frame.encode(out);
this.headers.encode(out);
checkState(out.writerIndex() - start == expectedLength,
"encoding error: {\"expectedLength\": %s, \"observedLength\": %s}",
expectedLength,
out.writerIndex() - expectedLength);
if (this.payload.length > 0) {
out.writeIntLE(this.payload.length);
out.writeBytes(this.payload);
}
}

Line under review: out.writerIndex() - expectedLength);

Code after addressing the review:
void encode(final ByteBuf out) {
final int expectedLength = RntbdRequestFrame.LENGTH + this.headers.computeLength();
final int start = out.writerIndex();
out.writeIntLE(expectedLength);
this.frame.encode(out);
this.headers.encode(out);
final int observedLength = out.writerIndex() - start;
checkState(observedLength == expectedLength,
"encoding error: {\"expectedLength\": %s, \"observedLength\": %s}",
expectedLength,
observedLength);
if (this.payload.length > 0) {
out.writeIntLE(this.payload.length);
out.writeBytes(this.payload);
}
}
Code review comment: is `serviceRegistry.id()` guaranteed not null?

Code before review:
public boolean hasServiceRegistryBinding() {
Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs();
if (addonConfigs == null) {
return false;
}
SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry();
if (serviceRegistry == null) {
return false;
}
return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null
&& serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID));
}

Line under review: && serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID));

Code after addressing the review:
public boolean hasServiceRegistryBinding() {
Map<String, Map<String, Object>> addonConfigs = innerModel().properties().addonConfigs();
if (addonConfigs == null) {
return false;
}
SpringServiceRegistry serviceRegistry = parent().getDefaultServiceRegistry();
if (serviceRegistry == null) {
return false;
}
return addonConfigs.get(Constants.SERVICE_REGISTRY_KEY) != null
&& serviceRegistry.id().equalsIgnoreCase((String) addonConfigs.get(Constants.SERVICE_REGISTRY_KEY).get(Constants.BINDING_RESOURCE_ID));
}
Code review comment: We need to check the size of `memTypes` before creating a union type. We shouldn't be creating a union type when there are 0 or 1 members. 0 should probably be neverType or semanticError.

Code before review:
public BType getSafeType(BType type, boolean liftNil, boolean liftError) {
if (liftNil) {
switch (type.tag) {
case TypeTags.JSON:
return new BJSONType((BJSONType) type, false);
case TypeTags.ANY:
return new BAnyType(type.tag, type.tsymbol, false);
case TypeTags.ANYDATA:
return new BAnydataType((BAnydataType) type, false);
case TypeTags.READONLY:
if (liftError) {
return symTable.anyAndReadonly;
}
return new BReadonlyType(type.tag, type.tsymbol, false);
}
}
if (type.tag != TypeTags.UNION) {
return type;
}
BUnionType unionType = (BUnionType) type;
LinkedHashSet<BType> memTypes = new LinkedHashSet<>(unionType.getMemberTypes());
BUnionType errorLiftedType = BUnionType.create(null, memTypes);
if (liftNil) {
errorLiftedType.remove(symTable.nilType);
}
if (liftError) {
memTypes = errorLiftedType.getMemberTypes().stream().filter(t -> t.tag != TypeTags.ERROR)
.collect(Collectors.toCollection(LinkedHashSet::new));
errorLiftedType = BUnionType.create(null, memTypes);
}
if (errorLiftedType.getMemberTypes().size() == 1) {
return errorLiftedType.getMemberTypes().toArray(new BType[0])[0];
}
return errorLiftedType;
}

Line under review: errorLiftedType = BUnionType.create(null, memTypes);

Code after addressing the review:
public BType getSafeType(BType type, boolean liftNil, boolean liftError) {
if (liftNil) {
switch (type.tag) {
case TypeTags.JSON:
return new BJSONType((BJSONType) type, false);
case TypeTags.ANY:
return new BAnyType(type.tag, type.tsymbol, false);
case TypeTags.ANYDATA:
return new BAnydataType((BAnydataType) type, false);
case TypeTags.READONLY:
if (liftError) {
return symTable.anyAndReadonly;
}
return new BReadonlyType(type.tag, type.tsymbol, false);
}
}
if (type.tag != TypeTags.UNION) {
return type;
}
BUnionType unionType = (BUnionType) type;
LinkedHashSet<BType> memTypes = new LinkedHashSet<>(unionType.getMemberTypes());
BUnionType errorLiftedType = BUnionType.create(null, memTypes);
if (liftNil) {
errorLiftedType.remove(symTable.nilType);
}
if (liftError) {
LinkedHashSet<BType> bTypes = new LinkedHashSet<>();
for (BType t : errorLiftedType.getMemberTypes()) {
if (t.tag != TypeTags.ERROR) {
bTypes.add(t);
}
}
memTypes = bTypes;
errorLiftedType = BUnionType.create(null, memTypes);
}
if (errorLiftedType.getMemberTypes().size() == 1) {
return errorLiftedType.getMemberTypes().toArray(new BType[0])[0];
}
if (errorLiftedType.getMemberTypes().size() == 0) {
return symTable.semanticError;
}
return errorLiftedType;
}
Code review comment: ```suggestion         }         return Relation.NO_RELATION; ```

Code before review:
private Relation getSemTypeRelation(SemType t1, SemType t2) {
boolean s1 = Core.isSubtype(ctx, t1, t2);
boolean s2 = Core.isSubtype(ctx, t2, t1);
if (s1 && s2) {
return Relation.EQUAL;
} else if (s1) {
return Relation.SUBTYPE;
} else if (s2) {
throw new IllegalStateException("'>' relation found which can be converted to a '<' relation");
} else {
return Relation.NO_RELATION;
}
}

Line under review: return Relation.NO_RELATION;

Code after addressing the review:
private Relation getSemTypeRelation(SemType t1, SemType t2) {
boolean s1 = Core.isSubtype(ctx, t1, t2);
boolean s2 = Core.isSubtype(ctx, t2, t1);
if (s1 && s2) {
return Relation.EQUAL;
} else if (s1) {
return Relation.SUBTYPE;
} else if (s2) {
throw new IllegalStateException("'>' relation found which can be converted to a '<' relation");
} else {
return Relation.NO_RELATION;
}
}
Code review comment: Can't we return this as `return new ArrayValueImpl(cacheMap.keySet().toArray(new String[0]));` ?

Code before review:
public static BArray externKeys(ObjectValue cache) {
cacheMap = (ConcurrentLinkedHashMap<String, BMap<String, Object>>) cache.getNativeData(CACHE);
String[] keySets = cacheMap.keySet().toArray(new String[0]);
HandleValue[] handleValues = new HandleValue[keySets.length];
for (int i = 0; i < keySets.length; i++) {
handleValues[i] = new HandleValue(keySets[i]);
}
return BValueCreator.createArrayValue(handleValues, new BArrayType(BTypes.typeHandle));
}

Line under review: String[] keySets = cacheMap.keySet().toArray(new String[0]);

Code after addressing the review:
public static BArray externKeys(ObjectValue cache) {
cacheMap = (ConcurrentLinkedHashMap<String, BMap<String, Object>>) cache.getNativeData(CACHE);
String[] keySets = cacheMap.keySet().toArray(new String[0]);
HandleValue[] handleValues = new HandleValue[keySets.length];
for (int i = 0; i < keySets.length; i++) {
handleValues[i] = new HandleValue(keySets[i]);
}
return BValueCreator.createArrayValue(handleValues, new BArrayType(BTypes.typeHandle));
}
Code review comment: Hm, the `renderTemplate()` method is called from the `handle()` above...

Code before review:
protected void renderTemplate(RoutingContext event, TemplateInstance template) {
for (Map.Entry<String, Object> global : globalData.entrySet()) {
template.data(global.getKey(), global.getValue());
}
template.renderAsync().handle(new BiFunction<String, Throwable, Object>() {
@Override
public Object apply(String s, Throwable throwable) {
if (throwable != null) {
event.fail(throwable);
} else {
event.response().putHeader(HttpHeaderNames.CONTENT_TYPE, HTML_CONTENT_TYPE).end(s);
}
return null;
}
});
}

Line under review: event.response().putHeader(HttpHeaderNames.CONTENT_TYPE, HTML_CONTENT_TYPE).end(s);

Code after addressing the review:
protected void renderTemplate(RoutingContext event, TemplateInstance template) {
for (Map.Entry<String, Object> global : globalData.entrySet()) {
template.data(global.getKey(), global.getValue());
}
template.renderAsync().handle(new BiFunction<String, Throwable, Object>() {
@Override
public Object apply(String s, Throwable throwable) {
if (throwable != null) {
event.fail(throwable);
} else {
event.response().end(s);
}
return null;
}
});
}
Code review comment: I'm not sure about this. My concern is that, the <2.6 test case might eventually not executed in most cases.  Take `testDoesntCallGetContainersFromPreviousAttemptsMethodIfAbsent` as an example. If we make this test case only executed with Hadoop <2.2, then it's practically not executed. Currently we have Hadoop 2.8 for travis ci test, 2.4 & 2.8 for nightly test, and 2.4 (pom default) for local maven verify unless another version is intentionally specified.

Code before review:
public void testCallsGetSchedulerResourceTypesMethodIfPresent() {
final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector =
new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class);
final Optional<Set<String>> schedulerResourceTypeNames =
registerApplicationMasterResponseReflector.getSchedulerResourceTypeNamesUnsafe(new HasMethod());
assertTrue(schedulerResourceTypeNames.isPresent());
assertThat(schedulerResourceTypeNames.get(), containsInAnyOrder("MEMORY", "CPU"));
}

Line under review: new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class);

Code after addressing the review:
public void testCallsGetSchedulerResourceTypesMethodIfPresent() {
final RegisterApplicationMasterResponseReflector registerApplicationMasterResponseReflector =
new RegisterApplicationMasterResponseReflector(LOG, HasMethod.class);
final Optional<Set<String>> schedulerResourceTypeNames =
registerApplicationMasterResponseReflector.getSchedulerResourceTypeNamesUnsafe(new HasMethod());
assertTrue(schedulerResourceTypeNames.isPresent());
assertThat(schedulerResourceTypeNames.get(), containsInAnyOrder("MEMORY", "CPU"));
}
Code review comment: yes, you are right. It is a bug, I will fix it.

Code before review:
public static boolean isAllEqualInnerJoin(OptExpression root) {
Operator operator = root.getOp();
if (!(operator instanceof LogicalOperator)) {
return false;
}
if (operator instanceof LogicalJoinOperator) {
LogicalJoinOperator joinOperator = (LogicalJoinOperator) operator;
boolean isEqualPredicate = isColumnEqualPredicate(joinOperator.getOnPredicate());
if (joinOperator.getJoinType() == JoinOperator.INNER_JOIN && isEqualPredicate) {
return true;
}
return false;
}
for (OptExpression child : root.getInputs()) {
if (!isAllEqualInnerJoin(child)) {
return false;
}
}
return true;
}

Line under review: if (joinOperator.getJoinType() == JoinOperator.INNER_JOIN && isEqualPredicate) {

Code after addressing the review:
public static boolean isAllEqualInnerJoin(OptExpression root) {
Operator operator = root.getOp();
if (!(operator instanceof LogicalOperator)) {
return false;
}
if (operator instanceof LogicalJoinOperator) {
LogicalJoinOperator joinOperator = (LogicalJoinOperator) operator;
boolean isEqualPredicate = isColumnEqualPredicate(joinOperator.getOnPredicate());
if (joinOperator.getJoinType() != JoinOperator.INNER_JOIN || !isEqualPredicate) {
return false;
}
}
for (OptExpression child : root.getInputs()) {
if (!isAllEqualInnerJoin(child)) {
return false;
}
}
return true;
}
Code review comment: Can we explicitly set `this.index` to 0 in the constructor - for readability reasons?

Code before review:
public void setIndex(int index) {
if (this.index == 0) {
this.index = index;
}
}

Line under review: if (this.index == 0) {

Code after addressing the review:
public void setIndex(int index) {
if (this.index == 0) {
this.index = index;
}
}
Code review comment: It should throw ```new SQLException("can not start in a Active transaction")``` immediately but not ```commit``` the current transaction.

Code before review:
public ResponseHeader execute() throws SQLException {
switch (tclStatement.getOp()) {
case "START":
case "BEGIN":
/**
* we have to let session occupy the thread when doing xa transaction.
* according to https:
*/
if (connectionSession.getTransactionStatus().isInTransaction()) {
if (TransactionType.MANUALXA != connectionSession.getTransactionStatus().getTransactionType()) {
BackendTransactionManager backendTransactionManager = new BackendTransactionManager((JDBCBackendConnection) connectionSession.getBackendConnection());
backendTransactionManager.commit();
} else {
throw new SQLException("already in XA transaction");
}
}
TransactionHolder.setInTransaction();
connectionSession.setAutoCommit(false);
connectionSession.getTransactionStatus().setManualXA(true);
JDBCBackendConnection connection = (JDBCBackendConnection) connectionSession.getBackendConnection();
connection.closeDatabaseCommunicationEngines(true);
connection.closeConnections(false);
return backendHandler.execute();
case "END":
case "PREPARE":
case "RECOVER":
return backendHandler.execute();
case "COMMIT":
case "ROLLBACK":
try {
return backendHandler.execute();
} finally {
connectionSession.getTransactionStatus().setManualXA(false);
TransactionHolder.clear();
}
default:
throw new SQLException("unrecognized XA statement");
}
}

Line under review: * according to https:

Code after addressing the review:
public ResponseHeader execute() throws SQLException {
switch (tclStatement.getOp()) {
case "START":
case "BEGIN":
/**
* we have to let session occupy the thread when doing xa transaction.
* according to https:
*/
if (connectionSession.getTransactionStatus().isInTransaction()) {
throw new SQLException("can not start in a Active transaction");
}
ResponseHeader header = backendHandler.execute();
TransactionHolder.setInTransaction();
connectionSession.getTransactionStatus().setManualXA(true);
return header;
case "END":
case "PREPARE":
case "RECOVER":
return backendHandler.execute();
case "COMMIT":
case "ROLLBACK":
try {
return backendHandler.execute();
} finally {
connectionSession.getTransactionStatus().setManualXA(false);
TransactionHolder.clear();
}
default:
throw new SQLException("unrecognized XA statement " + tclStatement.getOp());
}
}
Code review comment: Should we make matching case-insensitive?  ```java Pattern pattern = Pattern.compile("/subscriptions/([\\w-]+)/", Pattern.CASE_INSENSITIVE); ```

Code before review:
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (!response.isSuccessful()) {
String content = errorBody(response.body());
RestClient restClient = new RestClient.Builder()
.withBaseUrl("https:
.withCredentials(credentials)
.withSerializerAdapter(new AzureJacksonAdapter())
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.build();
CloudError cloudError = restClient.serializerAdapter().deserialize(content, CloudError.class);
if ("MissingSubscriptionRegistration".equals(cloudError.code())) {
Pattern pattern = Pattern.compile("/subscriptions/([\\w-]+)/");
Matcher matcher = pattern.matcher(chain.request().url().toString());
matcher.find();
ResourceManager resourceManager = ResourceManager.authenticate(restClient)
.withSubscription(matcher.group(1));
pattern = Pattern.compile(".*'(.*)'");
matcher = pattern.matcher(cloudError.message());
matcher.find();
Provider provider = registerProvider(matcher.group(1), resourceManager);
while (provider.registrationState().equals("Unregistered")
|| provider.registrationState().equalsIgnoreCase("Registering")) {
SdkContext.sleep(5 * 1000);
provider = resourceManager.providers().getByName(provider.namespace());
}
response = chain.proceed(chain.request());
}
}
return response;
}

Line under review: Pattern pattern = Pattern.compile("/subscriptions/([\\w-]+)/");

Code after addressing the review:
public Response intercept(Chain chain) throws IOException {
Response response = chain.proceed(chain.request());
if (!response.isSuccessful()) {
String content = errorBody(response.body());
AzureJacksonAdapter jacksonAdapter = new AzureJacksonAdapter();
CloudError cloudError = jacksonAdapter.deserialize(content, CloudError.class);
if ("MissingSubscriptionRegistration".equals(cloudError.code())) {
Pattern pattern = Pattern.compile("/subscriptions/([\\w-]+)/", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(chain.request().url().toString());
matcher.find();
RestClient restClient = new RestClient.Builder()
.withBaseUrl("https:
.withCredentials(credentials)
.withSerializerAdapter(jacksonAdapter)
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.build();
ResourceManager resourceManager = ResourceManager.authenticate(restClient)
.withSubscription(matcher.group(1));
pattern = Pattern.compile(".*'(.*)'");
matcher = pattern.matcher(cloudError.message());
matcher.find();
Provider provider = registerProvider(matcher.group(1), resourceManager);
while (provider.registrationState().equalsIgnoreCase("Unregistered")
|| provider.registrationState().equalsIgnoreCase("Registering")) {
SdkContext.sleep(5 * 1000);
provider = resourceManager.providers().getByName(provider.namespace());
}
response = chain.proceed(chain.request());
}
}
return response;
}
Code review comment: I kind of don't like the current solution as well, but your suggestion implies that we have a `@Nullable` argument as ctor argument, which is also not great.  Afaict in your suggestion, we also have to check whether the checkpointId is set and fail eventually.

Code before review:
public int getVersion() {
return 0;
}

Line under review: return 0;

Code after addressing the review:
public int getVersion() {
return 2;
}
Code review comment: I've addressed this in another PR https://github.com/apache/beam/pull/9820/files#r335994291 but tl;dr: the ConnectionHandler used in the constructor and `close` is not the same one used in `start`. I now defer initializing the class-level ConnectionHandler to `start` as it feels more in-line with start/stop semantics.

Code before review:
public Instant getWatermark() {
return checkpointMark.oldestTimestamp;
}

Line under review: return checkpointMark.oldestTimestamp;

Code after addressing the review:
public Instant getWatermark() {
return checkpointMark.oldestTimestamp;
}
Code review comment: I left it because for our infra tests here, when we change something for a playback we re-record it with the same method. So this is the "record" path that isn't persisted but handy to have around. 

Code before review:
public void testRedactRequestBodyRegex() {
HttpClient client = interceptorManager.getPlaybackClient();
HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build();
HttpRequest request = new HttpRequest(HttpMethod.POST, "http:
request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/x-www-form-urlencoded");
request.setBody("first_value=value&client_secret=aVerySecretSecret&other=value&is=cool");
try (HttpResponse response = pipeline.sendSync(request, Context.NONE)) {
assertEquals(200, response.getStatusCode());
}
RecordedTestProxyData recordedTestProxyData = readDataFromFile();
RecordedTestProxyData.TestProxyDataRecord record = recordedTestProxyData.getTestProxyDataRecords().get(0);
assertEquals(record.getRequestBody(), "first_value=value&client_secret=REDACTED&other=value&is=cool");
}


Code after addressing the review:
public void testRedactRequestBodyRegex() {
HttpClient client = interceptorManager.getPlaybackClient();
HttpPipeline pipeline = new HttpPipelineBuilder().httpClient(client).build();
interceptorManager.addMatchers(new CustomMatcher().setHeadersKeyOnlyMatch(Collections.singletonList("Accept")));
HttpRequest request = new HttpRequest(HttpMethod.POST, "http:
request.setHeader(HttpHeaderName.CONTENT_TYPE, "application/x-www-form-urlencoded");
request.setBody("first_value=value&client_secret=aVerySecretSecret&other=value&is=cool");
try (HttpResponse response = pipeline.sendSync(request, Context.NONE)) {
assertEquals(200, response.getStatusCode());
}
RecordedTestProxyData recordedTestProxyData = readDataFromFile();
RecordedTestProxyData.TestProxyDataRecord record = recordedTestProxyData.getTestProxyDataRecords().get(0);
assertEquals(record.getRequestBody(), "first_value=value&client_secret=REDACTED&other=value&is=cool");
}
Code review comment: Why use array list here?

Code before review:
private Collection<String> parseResultColumnNames(final Result result) {
Collection<String> row = new ArrayList<>(result.listCells().size() + 2);
row.add(ROW_KEY_COLUMN_NAME);
for (Cell each : result.listCells()) {
String column = new String(CellUtil.cloneQualifier(each), StandardCharsets.UTF_8);
row.add(column);
}
row.add(TIMESTAMP_COLUMN_NAME);
return row;
}

Line under review: Collection<String> row = new ArrayList<>(result.listCells().size() + 2);

Code after addressing the review:
private Collection<String> parseResultColumnNames(final Result result) {
Collection<String> columnNames = new LinkedList<>();
columnNames.add(ROW_KEY_COLUMN_NAME);
for (Cell each : result.listCells()) {
String column = new String(CellUtil.cloneQualifier(each), StandardCharsets.UTF_8);
columnNames.add(column);
}
columnNames.add(TIMESTAMP_COLUMN_NAME);
return columnNames;
}
Code review comment: It will throw an exception in the `fe.log`. The debug log is un-necessary. 

Code before review:
public boolean exceedLimit(boolean usingHardLimit) {
LOG.debug("using hard limit: {}, diskAvailableCapacityB: {}, totalCapacityB: {}",
usingHardLimit, diskAvailableCapacityB, totalCapacityB);
return DiskInfo.exceedLimit(diskAvailableCapacityB, totalCapacityB, usingHardLimit);
}

Line under review: LOG.debug("using hard limit: {}, diskAvailableCapacityB: {}, totalCapacityB: {}",

Code after addressing the review:
public boolean exceedLimit(boolean usingHardLimit) {
LOG.debug("using hard limit: {}, diskAvailableCapacityB: {}, totalCapacityB: {}",
usingHardLimit, diskAvailableCapacityB, totalCapacityB);
return DiskInfo.exceedLimit(diskAvailableCapacityB, totalCapacityB, usingHardLimit);
}
Code review comment: Fixed, replaced `org.junit.Assert.assertEquals` with `org.junit.jupiter.api.Assertions.assertEquals`

Code before review:
void testUpdate() {
assertThatThrownBy(
() -> {
String value = aggrState.get();
assertEquals("42", value);
aggrState.add(54L);
})
.isInstanceOf(UnsupportedOperationException.class);
}

Line under review: assertEquals("42", value);

Code after addressing the review:
void testUpdate() throws Exception {
String value = aggrState.get();
assertThat(value).isEqualTo("42");
assertThatThrownBy(() -> aggrState.add(54L))
.isInstanceOf(UnsupportedOperationException.class);
}
Code review comment: @radcortez Thanks, I forgot there is no dedicated property yet exists for Regex origins so for now it won't work.

Code before review:
public static List<Pattern> parseAllowedOriginsRegex(Optional<List<String>> allowedOrigins) {
if (allowedOrigins == null || !allowedOrigins.isPresent()) {
return Collections.emptyList();
}
List<Pattern> allowOriginsRegex = new ArrayList<>();
allowedOrigins.get().stream()
.forEach(o -> {
if (o != null && o.startsWith("/") && o.endsWith("/")) {
allowOriginsRegex.add(Pattern.compile(o.substring(1, o.length() - 1)));
}
});
return allowOriginsRegex;
}

Line under review: allowedOrigins.get().stream()

Code after addressing the review:
public static List<Pattern> parseAllowedOriginsRegex(Optional<List<String>> allowedOrigins) {
if (allowedOrigins == null || !allowedOrigins.isPresent()) {
return Collections.emptyList();
}
List<Pattern> allowOriginsRegex = new ArrayList<>();
for (String o : allowedOrigins.get()) {
if (o != null && o.startsWith("/") && o.endsWith("/")) {
allowOriginsRegex.add(Pattern.compile(o.substring(1, o.length() - 1)));
}
}
return allowOriginsRegex;
}
Code review comment: catch refresh table exception and then invalidate the cache of cachingIcebergCatalog. 

Code before review:
public void alterTable(AlterTableStmt stmt) throws UserException {
String dbName = stmt.getDbName();
String tableName = stmt.getTableName();
org.apache.iceberg.Table table = icebergCatalog.getTable(dbName, tableName);
if (table == null) {
throw new StarRocksConnectorException(
"Failed to load iceberg table: " + stmt.getTbl().toString());
}
List<AlterClause> alterClauses = stmt.getOps();
List<AlterClause> tableChanges = Lists.newArrayList();
List<AlterClause> schemaChanges = Lists.newArrayList();
for (AlterClause clause : alterClauses) {
if (clause instanceof AddColumnClause
|| clause instanceof AddColumnsClause
|| clause instanceof DropColumnClause
|| clause instanceof ColumnRenameClause
|| clause instanceof ModifyColumnClause) {
schemaChanges.add(clause);
} else if (clause instanceof ModifyTablePropertiesClause
|| clause instanceof TableRenameClause
|| clause instanceof AlterTableCommentClause
) {
tableChanges.add(clause);
} else {
throw new StarRocksConnectorException(
"Unsupported alter operation for iceberg connector: " + clause.toString());
}
}
commitAlterTable(table, schemaChanges, tableChanges);
synchronized(this) {
tables.remove(TableIdentifier.of(dbName, tableName));
icebergCatalog.refreshTable(dbName, tableName, jobPlanningExecutor);
asyncRefreshOthersFeMetadataCache(dbName, tableName);
}
}

Line under review: icebergCatalog.refreshTable(dbName, tableName, jobPlanningExecutor);

Code after addressing the review:
public void alterTable(AlterTableStmt stmt) throws UserException {
String dbName = stmt.getDbName();
String tableName = stmt.getTableName();
org.apache.iceberg.Table table = icebergCatalog.getTable(dbName, tableName);
if (table == null) {
throw new StarRocksConnectorException(
"Failed to load iceberg table: " + stmt.getTbl().toString());
}
List<AlterClause> alterClauses = stmt.getOps();
List<AlterClause> tableChanges = Lists.newArrayList();
List<AlterClause> schemaChanges = Lists.newArrayList();
for (AlterClause clause : alterClauses) {
if (clause instanceof AddColumnClause
|| clause instanceof AddColumnsClause
|| clause instanceof DropColumnClause
|| clause instanceof ColumnRenameClause
|| clause instanceof ModifyColumnClause) {
schemaChanges.add(clause);
} else if (clause instanceof ModifyTablePropertiesClause
|| clause instanceof TableRenameClause
|| clause instanceof AlterTableCommentClause
) {
tableChanges.add(clause);
} else {
throw new StarRocksConnectorException(
"Unsupported alter operation for iceberg connector: " + clause.toString());
}
}
commitAlterTable(table, schemaChanges, tableChanges);
synchronized (this) {
tables.remove(TableIdentifier.of(dbName, tableName));
try {
icebergCatalog.refreshTable(dbName, tableName, jobPlanningExecutor);
} catch (Exception exception) {
LOG.error("Failed to refresh caching iceberg table.");
icebergCatalog.invalidateCache(new CachingIcebergCatalog.IcebergTableName(dbName, tableName));
}
asyncRefreshOthersFeMetadataCache(dbName, tableName);
}
}
Code review comment: That is true, except I thought (maybe incorrectly) that Quarkus shades Caffeine so it would only apply to your extension if you disable the logger at the shaded path? I might be completely wrong, in which case you're very much right.

Code before review:
public CompletableFuture<Object> get(Object key, Function<Object, Object> valueLoader) {
if (key == null) {
throw new NullPointerException(NULL_KEYS_NOT_SUPPORTED_MSG);
}
CompletableFuture<Object> newCacheValue = new CompletableFuture<Object>();
CompletableFuture<Object> existingCacheValue = cache.asMap().putIfAbsent(key, newCacheValue);
if (existingCacheValue == null) {
try {
Object value = valueLoader.apply(key);
newCacheValue.complete(NullValueConverter.toCacheValue(value));
return unwrapCacheValue(newCacheValue);
} catch (Throwable t) {
cache.asMap().remove(key, newCacheValue);
newCacheValue.completeExceptionally(t);
return newCacheValue;
}
} else {
return unwrapCacheValue(existingCacheValue);
}
}

Line under review: newCacheValue.completeExceptionally(t);

Code after addressing the review:
public CompletableFuture<Object> get(Object key, Function<Object, Object> valueLoader) {
if (key == null) {
throw new NullPointerException(NULL_KEYS_NOT_SUPPORTED_MSG);
}
CompletableFuture<Object> newCacheValue = new CompletableFuture<Object>();
CompletableFuture<Object> existingCacheValue = cache.asMap().putIfAbsent(key, newCacheValue);
if (existingCacheValue == null) {
try {
Object value = valueLoader.apply(key);
newCacheValue.complete(NullValueConverter.toCacheValue(value));
} catch (Throwable t) {
cache.asMap().remove(key, newCacheValue);
newCacheValue.complete(new CaffeineComputationThrowable(t));
}
return unwrapCacheValueOrThrowable(key, newCacheValue);
} else {
return unwrapCacheValueOrThrowable(key, existingCacheValue);
}
}
Code review comment: Earlier we were getting `null` for the returnTypeSymbol? Asking for my understanding for this change.

Code before review:
public void visit(StartActionNode startActionNode) {
startActionNode.parent().accept(this);
if (resultFound && returnTypeSymbol.typeKind() == TypeDescKind.FUTURE) {
FutureTypeSymbol futureTypeSymbol = (FutureTypeSymbol) returnTypeSymbol;
TypeSymbol typeSymbol = futureTypeSymbol.typeParameter().orElse(null);
checkAndSetTypeResult(typeSymbol);
} else {
TypeSymbol nilTypeSymbol = semanticModel.types().NIL;
checkAndSetTypeResult(nilTypeSymbol);
}
}

Line under review: TypeSymbol nilTypeSymbol = semanticModel.types().NIL;

Code after addressing the review:
public void visit(StartActionNode startActionNode) {
startActionNode.parent().accept(this);
if (resultFound && returnTypeSymbol.typeKind() == TypeDescKind.FUTURE) {
FutureTypeSymbol futureTypeSymbol = (FutureTypeSymbol) returnTypeSymbol;
TypeSymbol typeSymbol = futureTypeSymbol.typeParameter().orElse(null);
checkAndSetTypeResult(typeSymbol);
} else {
TypeSymbol nilTypeSymbol = semanticModel.types().NIL;
checkAndSetTypeResult(nilTypeSymbol);
}
}
Code review comment: Actually we should maybe also add `@Nullable` to `resourceManagerId` and `resourceActions`.

Code before review:
public void suspend() {
LOG.info("Suspending the slot manager.");
resourceTracker.clear();
if (taskExecutorManager != null) {
taskExecutorManager.close();
for (InstanceID registeredTaskManager : taskExecutorManager.getTaskExecutors()) {
unregisterTaskManager(registeredTaskManager, new SlotManagerException("The slot manager is being suspended."));
}
}
taskExecutorManager = null;
resourceManagerId = null;
resourceActions = null;
started = false;
}

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

Code after addressing the review:
public void suspend() {
if (!started) {
return;
}
LOG.info("Suspending the slot manager.");
resourceTracker.clear();
if (taskExecutorManager != null) {
taskExecutorManager.close();
for (InstanceID registeredTaskManager : taskExecutorManager.getTaskExecutors()) {
unregisterTaskManager(registeredTaskManager, new SlotManagerException("The slot manager is being suspended."));
}
}
taskExecutorManager = null;
resourceManagerId = null;
resourceActions = null;
started = false;
}
Code review comment: Again, not a change introduced by this PR, but shouldn't we handle other possible exceptions too? Not sure why we've handled (only) a NPE here?

Code before review:
private static BValue getRecord(BType entityBodyType, BValue bjson) {
try {
return JSONUtils.convertJSONToStruct(bjson, (BStructureType) entityBodyType);
} catch (NullPointerException ex) {
throw new BallerinaConnectorException("cannot convert payload to record type: " +
entityBodyType.getName());
}
}

Line under review: } catch (NullPointerException ex) {

Code after addressing the review:
private static BValue getRecord(BType entityBodyType, BValue bjson) {
try {
return JSONUtils.convertJSONToStruct(bjson, (BStructureType) entityBodyType);
} catch (NullPointerException ex) {
throw new BallerinaConnectorException("cannot convert payload to record type: " +
entityBodyType.getName());
}
}
Code review comment: > No need to lowercase. "." lower-case still "."  done

Code before review:
private boolean isValidDirectory(FileStatus fileStatus) {
if (!fileStatus.isDirectory()) {
return false;
}
String lcFileName = fileStatus.getPath().getName().toLowerCase();
return !(lcFileName.startsWith("."));
}

Line under review: String lcFileName = fileStatus.getPath().getName().toLowerCase();

Code after addressing the review:
private boolean isValidDirectory(FileStatus fileStatus) {
if (!fileStatus.isDirectory()) {
return false;
}
String dirName = fileStatus.getPath().getName();
return !(dirName.startsWith("."));
}
Code review comment: Before: the time contains two parts: part one is the time usage for waiting for all instances to report profile(i.d. `endProfile`), the second is the profile merge time usage(i.e. `buildMergedQueryProfile`).  After: the time only contains the first part.

Code before review:
private void initProfile(long beginTimeInNanoSecond) {
profile = buildTopLevelProfile();
if (coord != null) {
if (coord.getQueryProfile() != null) {
coord.getQueryProfile().getCounterTotalTime()
.setValue(TimeUtils.getEstimatedTime(beginTimeInNanoSecond));
long profileCollectStartTime = System.currentTimeMillis();
coord.endProfile();
profile.getChild("Summary").addInfoString(ProfileManager.PROFILE_TIME,
DebugUtil.getPrettyStringMs(System.currentTimeMillis() - profileCollectStartTime));
profile.addChild(coord.buildMergedQueryProfile());
}
}
profile.computeTimeInChildProfile();
}

Line under review: coord.endProfile();

Code after addressing the review:
private void initProfile(long beginTimeInNanoSecond) {
profile = buildTopLevelProfile();
if (coord != null) {
if (coord.getQueryProfile() != null) {
coord.getQueryProfile().getCounterTotalTime()
.setValue(TimeUtils.getEstimatedTime(beginTimeInNanoSecond));
long profileCollectStartTime = System.currentTimeMillis();
coord.endProfile();
profile.getChild("Summary").addInfoString(ProfileManager.PROFILE_TIME,
DebugUtil.getPrettyStringMs(System.currentTimeMillis() - profileCollectStartTime));
profile.addChild(coord.buildMergedQueryProfile());
}
}
profile.computeTimeInChildProfile();
}
Code review comment: Same statement as above where this could just call into the `setBody(BinaryData)` method

Code before review:
public HttpRequest setBody(byte[] content) {
setContentLength(content.length);
this.body = BinaryData.fromBytes(content);
return this;
}

Line under review: return this;

Code after addressing the review:
public HttpRequest setBody(byte[] content) {
return setBody(BinaryData.fromBytes(content));
}
Code review comment: Better wording. Response and value are returned from service not coming from caller. We can't blame the caller here. :-)  E.g. Service failed to return a response or expected value.  

Code before review:
public Response<CommunicationUserIdentifier> createUserWithResponse(Context context) {
context = context == null ? Context.NONE : context;
Response<CommunicationIdentityAccessTokenResult> response =
client.createWithResponseAsync(new CommunicationIdentityCreateRequest(), context).block();
if (response == null || response.getValue() == null) {
throw logger.logExceptionAsError(new IllegalStateException("Create user response and value cannot be null"));
}
String id = response.getValue().getIdentity().getId();
return new SimpleResponse<CommunicationUserIdentifier>(
response,
new CommunicationUserIdentifier(id));
}

Line under review: throw logger.logExceptionAsError(new IllegalStateException("Create user response and value cannot be null"));

Code after addressing the review:
public Response<CommunicationUserIdentifier> createUserWithResponse(Context context) {
context = context == null ? Context.NONE : context;
Response<CommunicationIdentityAccessTokenResult> response =
client.createWithResponseAsync(new CommunicationIdentityCreateRequest(), context).block();
if (response == null || response.getValue() == null) {
throw logger.logExceptionAsError(new IllegalStateException("Service failed to return a response or expected value."));
}
String id = response.getValue().getIdentity().getId();
return new SimpleResponse<CommunicationUserIdentifier>(
response,
new CommunicationUserIdentifier(id));
}
Code review comment: Would it be possible to add test case for bw compatible code path?

Code before review:
public Params decode(InputStream inStream) throws IOException {
String prefix = STRING_CODER.decode(inStream);
String shardTemplate = STRING_CODER.decode(inStream);
String suffix = STRING_CODER.decode(inStream);
ResourceId baseFilename;
if (inStream.available() > 0) {
baseFilename = FileSystems.matchNewResource(prefix, BOOLEAN_CODER.decode(inStream));
} else {
baseFilename = FileBasedSink.convertToFileResourceIfPossible(prefix);
}
return new Params()
.withBaseFilename(baseFilename)
.withShardTemplate(shardTemplate)
.withSuffix(suffix);
}

Line under review: baseFilename = FileBasedSink.convertToFileResourceIfPossible(prefix);

Code after addressing the review:
public Params decode(InputStream inStream) throws IOException {
ResourceId prefix =
FileBasedSink.convertToFileResourceIfPossible(STRING_CODER.decode(inStream));
String shardTemplate = STRING_CODER.decode(inStream);
String suffix = STRING_CODER.decode(inStream);
return new Params()
.withBaseFilename(prefix)
.withShardTemplate(shardTemplate)
.withSuffix(suffix);
}
Code review comment: After checking the implementation, I found the port is 0 in default configuration used by sqlGatewayRestEndpoint.start(), and that means  server would bind a random port.

Code before review:
public void beforeAll(ExtensionContext context) {
String address = InetAddress.getLoopbackAddress().getHostAddress();
Configuration config = getBaseConfig(getFlinkConfig(address, address, "0"));
try {
sqlGatewayRestEndpoint = new SqlGatewayRestEndpoint(config, serviceSupplier.get());
sqlGatewayRestEndpoint.start();
} catch (Exception e) {
throw new SqlGatewayException(
"Unexpected error occurred when trying to start the rest endpoint of sql gateway.",
e);
}
InetSocketAddress serverAddress = checkNotNull(sqlGatewayRestEndpoint.getServerAddress());
targetAddress = serverAddress.getHostName();
targetPort = serverAddress.getPort();
}

Line under review: targetAddress = serverAddress.getHostName();

Code after addressing the review:
public void beforeAll(ExtensionContext context) {
String address = InetAddress.getLoopbackAddress().getHostAddress();
Configuration config = getBaseConfig(getFlinkConfig(address, address, "0"));
try {
sqlGatewayRestEndpoint = new SqlGatewayRestEndpoint(config, serviceSupplier.get());
sqlGatewayRestEndpoint.start();
} catch (Exception e) {
throw new SqlGatewayException(
"Unexpected error occurred when trying to start the rest endpoint of sql gateway.",
e);
}
InetSocketAddress serverAddress = checkNotNull(sqlGatewayRestEndpoint.getServerAddress());
targetAddress = serverAddress.getHostName();
targetPort = serverAddress.getPort();
}