muttakin2301/ccr_train_1000 huggingface dataset:
Code review comment: Lets handle float and decimal diffrently and other types use same isEqual which will minimise code duplication.

Code before review:
public static boolean isReferenceEqual(Object lhsValue, Object rhsValue) {
if (lhsValue == rhsValue) {
return true;
}
if (lhsValue == null || rhsValue == null) {
return false;
}
Type lhsType = getType(lhsValue);
Type rhsType = getType(rhsValue);
switch(lhsType.getTag()) {
case TypeTags.INT_TAG:
if (rhsType.getTag() != TypeTags.BYTE_TAG || rhsType.getTag() != TypeTags.INT_TAG) {
return false;
}
return lhsValue.equals(((Number) rhsValue).longValue());
case TypeTags.BYTE_TAG:
if (rhsType.getTag() != TypeTags.BYTE_TAG || rhsType.getTag() != TypeTags.INT_TAG) {
return false;
}
return lhsValue.equals(((Number) rhsValue).byteValue());
case TypeTags.FLOAT_TAG:
if (rhsType.getTag() != TypeTags.FLOAT_TAG) {
return false;
}
return lhsValue.equals(((Number) rhsValue).doubleValue());
case TypeTags.DECIMAL_TAG:
if (rhsType.getTag() != TypeTags.DECIMAL_TAG) {
return false;
}
return checkDecimalExactEqual((DecimalValue) lhsValue, (DecimalValue) rhsValue);
case TypeTags.BOOLEAN_TAG:
case TypeTags.STRING_TAG:
return lhsValue.equals(rhsValue);
}
if (TypeTags.isXMLTypeTag(lhsType.getTag()) && TypeTags.isXMLTypeTag(rhsType.getTag())) {
return isXMLValueRefEqual((XmlValue) lhsValue, (XmlValue) rhsValue);
}
if (isHandleType(lhsType) && isHandleType(rhsType)) {
return isHandleValueRefEqual(lhsValue, rhsValue);
}
return false;
}

Line under review: if (rhsType.getTag() != TypeTags.BYTE_TAG || rhsType.getTag() != TypeTags.INT_TAG) {

Code after addressing the review:
public static boolean isReferenceEqual(Object lhsValue, Object rhsValue) {
if (lhsValue == rhsValue) {
return true;
}
if (lhsValue == null || rhsValue == null) {
return false;
}
Type lhsType = getType(lhsValue);
Type rhsType = getType(rhsValue);
switch (lhsType.getTag()) {
case TypeTags.FLOAT_TAG:
if (rhsType.getTag() != TypeTags.FLOAT_TAG) {
return false;
}
return lhsValue.equals(((Number) rhsValue).doubleValue());
case TypeTags.DECIMAL_TAG:
if (rhsType.getTag() != TypeTags.DECIMAL_TAG) {
return false;
}
return checkDecimalExactEqual((DecimalValue) lhsValue, (DecimalValue) rhsValue);
case TypeTags.INT_TAG:
case TypeTags.BYTE_TAG:
case TypeTags.BOOLEAN_TAG:
case TypeTags.STRING_TAG:
return isEqual(lhsValue, rhsValue);
case TypeTags.XML_TAG:
case TypeTags.XML_COMMENT_TAG:
case TypeTags.XML_ELEMENT_TAG:
case TypeTags.XML_PI_TAG:
case TypeTags.XML_TEXT_TAG:
if (!TypeTags.isXMLTypeTag(rhsType.getTag())) {
return false;
}
return isXMLValueRefEqual((XmlValue) lhsValue, (XmlValue) rhsValue);
case TypeTags.HANDLE_TAG:
if (rhsType.getTag() != TypeTags.HANDLE_TAG) {
return false;
}
return isHandleValueRefEqual(lhsValue, rhsValue);
}
return false;
}
Code review comment: Because we can definitively say that a if-else statement causes a function to return only when there are return statements inside all if, if else and else blocks. If at least one such block does not contain the return statement, the whole if-else statement is marked as a statement which will not cause a function to return. In this case, absence of an else block => absence of a return statement. 

Code before review:
public void visit(IfElseStmt ifElseStmt) {
boolean stmtReturns = true;
Expression expr = ifElseStmt.getCondition();
visitSingleValueExpr(expr);
if (expr.getType() != BTypes.typeBoolean) {
BLangExceptionHelper
.throwSemanticError(ifElseStmt, SemanticErrors.INCOMPATIBLE_TYPES_BOOLEAN_EXPECTED, expr.getType());
}
Statement thenBody = ifElseStmt.getThenBody();
thenBody.accept(this);
stmtReturns &= thenBody.resultsInAReturn();
for (IfElseStmt.ElseIfBlock elseIfBlock : ifElseStmt.getElseIfBlocks()) {
Expression elseIfCondition = elseIfBlock.getElseIfCondition();
visitSingleValueExpr(elseIfCondition);
if (elseIfCondition.getType() != BTypes.typeBoolean) {
BLangExceptionHelper.throwSemanticError(ifElseStmt, SemanticErrors.INCOMPATIBLE_TYPES_BOOLEAN_EXPECTED,
elseIfCondition.getType());
}
Statement elseIfBody = elseIfBlock.getElseIfBody();
elseIfBody.accept(this);
stmtReturns &= elseIfBody.resultsInAReturn();
}
Statement elseBody = ifElseStmt.getElseBody();
if (elseBody != null) {
elseBody.accept(this);
stmtReturns &= elseBody.resultsInAReturn();
} else {
stmtReturns = false;
}
ifElseStmt.setReturns(stmtReturns);
}

Line under review: stmtReturns = false;

Code after addressing the review:
public void visit(IfElseStmt ifElseStmt) {
boolean stmtReturns = true;
Expression expr = ifElseStmt.getCondition();
visitSingleValueExpr(expr);
if (expr.getType() != BTypes.typeBoolean) {
BLangExceptionHelper
.throwSemanticError(ifElseStmt, SemanticErrors.INCOMPATIBLE_TYPES_BOOLEAN_EXPECTED, expr.getType());
}
Statement thenBody = ifElseStmt.getThenBody();
thenBody.accept(this);
stmtReturns &= thenBody.isAlwaysReturns();
for (IfElseStmt.ElseIfBlock elseIfBlock : ifElseStmt.getElseIfBlocks()) {
Expression elseIfCondition = elseIfBlock.getElseIfCondition();
visitSingleValueExpr(elseIfCondition);
if (elseIfCondition.getType() != BTypes.typeBoolean) {
BLangExceptionHelper.throwSemanticError(ifElseStmt, SemanticErrors.INCOMPATIBLE_TYPES_BOOLEAN_EXPECTED,
elseIfCondition.getType());
}
Statement elseIfBody = elseIfBlock.getElseIfBody();
elseIfBody.accept(this);
stmtReturns &= elseIfBody.isAlwaysReturns();
}
Statement elseBody = ifElseStmt.getElseBody();
if (elseBody != null) {
elseBody.accept(this);
stmtReturns &= elseBody.isAlwaysReturns();
} else {
stmtReturns = false;
}
ifElseStmt.setAlwaysReturns(stmtReturns);
}
Code review comment: Periodic tasks are added to the Task framework later.

Code before review:
public List<Task> showTask() {
List<Task> taskList = Lists.newArrayList();
taskList.addAll(manualTaskMap.values());
return taskList;
}

Line under review: taskList.addAll(manualTaskMap.values());

Code after addressing the review:
public List<Task> showTask() {
List<Task> taskList = Lists.newArrayList();
taskList.addAll(manualTaskMap.values());
return taskList;
}
Code review comment: Removes the use of a Supplier function to store the TableSchema and simply uses a class property to hold the TableSchema.

Code before review:
public T read(T reuse, Decoder in) throws IOException {
GenericRecord record = (GenericRecord) this.reader.read(reuse, in);
return parseFn.apply(new SchemaAndRecord(record, this.tableSchema));
}

Line under review: return parseFn.apply(new SchemaAndRecord(record, this.tableSchema));

Code after addressing the review:
public T read(T reuse, Decoder in) throws IOException {
GenericRecord record = (GenericRecord) this.reader.read(reuse, in);
return parseFn.apply(new SchemaAndRecord(record, this.tableSchema));
}
Code review comment: Thanks for pointing this out, after rethinking the semantics of `read()`, I think changing the [NoFetchingInput#readBytes()](https://github.com/apache/flink/blob/9d2ae5572897f3e2d9089414261a250cfc2a2ab8/flink-core/src/main/java/org/apache/flink/api/java/typeutils/runtime/NoFetchingInput.java#L115-L140) is a better way to go.  As https://docs.oracle.com/javase/8/docs/api/java/io/FileInputStream.html#read--  explained,  > Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.  We should keep the semantics of `read()` consistent. 

Code before review:
public int read(byte[] b, int off, int len) throws IOException {
final int bytesLeft = data.length - index;
if (bytesLeft > 0) {
final int bytesToCopy = Math.min(len, bytesLeft);
System.arraycopy(data, index, b, off, bytesToCopy);
index += bytesToCopy;
return bytesToCopy;
} else {
return len == 0 ? 0 : -1;
}
}

Line under review: return len == 0 ? 0 : -1;

Code after addressing the review:
public int read(byte[] b, int off, int len) throws IOException {
final int bytesLeft = data.length - index;
if (bytesLeft > 0) {
final int bytesToCopy = Math.min(len, bytesLeft);
System.arraycopy(data, index, b, off, bytesToCopy);
index += bytesToCopy;
return bytesToCopy;
} else {
return len == 0 ? 0 : -1;
}
}
Code review comment: These changes are not covered. Consider adding a test in `PrintConnectorITCase` so that the result shows this `printIdentifier`.

Code before review:
public SinkRuntimeProvider getSinkRuntimeProvider(DynamicTableSink.Context context) {
DataStructureConverter converter = context.createDataStructureConverter(type);
staticPartitions.forEach(
(key, value) -> {
printIdentifier = null != printIdentifier ? printIdentifier + ":" : "";
printIdentifier += key + "=" + value;
});
return SinkFunctionProvider.of(
new RowDataPrintFunction(converter, printIdentifier, stdErr), parallelism);
}

Line under review: });

Code after addressing the review:
public SinkRuntimeProvider getSinkRuntimeProvider(DynamicTableSink.Context context) {
DataStructureConverter converter = context.createDataStructureConverter(type);
staticPartitions.forEach(
(key, value) -> {
printIdentifier = null != printIdentifier ? printIdentifier + ":" : "";
printIdentifier += key + "=" + value;
});
return SinkFunctionProvider.of(
new RowDataPrintFunction(converter, printIdentifier, stdErr), parallelism);
}
Code review comment: Can we consider adding integration test to cover this line? Or we can add a test in the `remote.management` module. 

Code before review:
public Object getDetail(String detailKey) {
return details.getOrDefault(detailKey, null);
}

Line under review: return details.getOrDefault(detailKey, null);

Code after addressing the review:
public Object getDetail(String detailKey) {
return details.getOrDefault(detailKey, null);
}
Code review comment: @mosche, what about switching from `AtomicInteger` to `Integer` as @adude3141 suggested ? Indeed, this counter is always accessed in a synchronised block, there is no need to add extract sync mechanism. And by the way it will also allow to remove the `SuppressWarning`

Code before review:
private void setupSharedProducer() {
synchronized (producerRefCount) {
if (producer == null) {
producer =
spec.getAWSClientsProvider().createKinesisProducer(spec.producerConfiguration());
producerRefCount.set(0);
}
}
producerRefCount.incrementAndGet();
}

Line under review: }

Code after addressing the review:
private void setupSharedProducer() {
synchronized (KinesisWriterFn.class) {
if (producer == null) {
producer =
spec.getAWSClientsProvider()
.createKinesisProducer(spec.createProducerConfiguration());
producerRefCount = 0;
}
producerRefCount++;
}
}
Code review comment: This code appears to be substituting calls to `getQualifiedUser()` with calls to `getUser()`. The review of such a change depends upon the exact implementation of these two methods, which is not included in the snippet provided. Broadly, this might imply a significant shift from using "qualified" (potentially containing additional attributes or information) to just basic username.  However, given what we have here, here are some general points to consider:  1. **Consistency**: This change is consistently applied throughout the code. It's good to see that all instances of the old method are replaced with the new ones, indicating thoroughness.   2. **Exception Messages**: In your exception messages, you directly print out the username. Consider if this may lead to privacy and security issues - depending on who can access these logs, you might be unintentionally leaking user information.  3. **Testing**: After this significant change, it would be important to immediately verify that the application still behaves as expected for various scenarios: existing users, new users who need to be created, handling errors, duplicates, etc.   Remember, before making this kind of modification, it's crucial to understand fully how `getQualifiedUser()` and `getUser()` differ in their implementation and use. Validate that replacing one with the other won't unintentionally remove any required functionality or introduce unexpected behavior.    Finally, while there doesn't appear to be any direct syntax errors introduced by the changes, without context and broader understanding of the entire codebase, it's impossible to guarantee that these modifications won't introduce logic or functionality errors. Always make sure to conduct comprehensive testing after changes like this.

Code before review:
private boolean hasUserNameNoLock(String userName) {
for (UserIdentity userIdentity : userToAuthenticationInfo.keySet()) {
if (userIdentity.getUser().equals(userName)) {
return true;
}
}
return false;
}

Line under review: }

Code after addressing the review:
private boolean hasUserNameNoLock(String userName) {
for (UserIdentity userIdentity : userToAuthenticationInfo.keySet()) {
if (userIdentity.getUser().equals(userName)) {
return true;
}
}
return false;
}
Code review comment: also worth adding the low bound comparison , like` duration.getSeconds > timeout based on the httpTimeoutPolicy`.  By just comparing the high bound, it will not catch the issue 

Code before review:
private void validateDataPlaneRetryPolicyResponseTimeouts(CosmosDiagnostics cosmosDiagnostics) {
List<ClientSideRequestStatistics.GatewayStatistics> gatewayStatisticsList = diagnosticsAccessor.getClientSideRequestStatistics(cosmosDiagnostics)
.stream()
.map(ClientSideRequestStatistics::getGatewayStatisticsList)
.flatMap(Collection::stream)
.collect(Collectors.toList());
for (ClientSideRequestStatistics.GatewayStatistics gs : gatewayStatisticsList) {
for (RequestTimeline.Event event : gs.getRequestTimeline()) {
Duration durationInMillis = event.getDuration();
if (durationInMillis != null) {
assertThat(durationInMillis.getSeconds()).isLessThanOrEqualTo(62);
}
}
}
}

Line under review: assertThat(durationInMillis.getSeconds()).isLessThanOrEqualTo(62);

Code after addressing the review:
private void validateDataPlaneRetryPolicyResponseTimeouts(CosmosDiagnostics cosmosDiagnostics) {
List<ClientSideRequestStatistics.GatewayStatistics> gatewayStatisticsList = diagnosticsAccessor.getClientSideRequestStatistics(cosmosDiagnostics)
.stream()
.map(ClientSideRequestStatistics::getGatewayStatisticsList)
.flatMap(Collection::stream)
.collect(Collectors.toList());
for (ClientSideRequestStatistics.GatewayStatistics gs : gatewayStatisticsList) {
if (gs.getStatusCode() == HttpConstants.StatusCodes.REQUEST_TIMEOUT) {
for (RequestTimeline.Event event : gs.getRequestTimeline()) {
Duration durationInMillis = event.getDuration();
if (durationInMillis != null) {
assertThat(durationInMillis.getSeconds()).isLessThanOrEqualTo(62);
assertThat(durationInMillis.getSeconds()).isGreaterThanOrEqualTo(60);
}
}
}
}
}
Code review comment: Couldn't you inject the Agroal datasource directly? I see Flyway has a method for this: https://github.com/flyway/flyway/blob/master/flyway-core/src/main/java/org/flywaydb/core/api/configuration/FluentConfiguration.java#L735 .

Code before review:
public Flyway produceFlyway() {
FluentConfiguration configure = Flyway.configure();
String url = agroalRuntimeConfig.defaultDataSource.url
.orElseThrow(() -> new IllegalStateException(
"No default datasource configured. Please specify the quarkus.datasource.* properties"));
String username = agroalRuntimeConfig.defaultDataSource.username.orElse(null);
String password = agroalRuntimeConfig.defaultDataSource.password.orElse(null);
configure.dataSource(url, username, password);
flywayRuntimeConfig.connectRetries.ifPresent(configure::connectRetries);
flywayRuntimeConfig.schemas.ifPresent(configure::schemas);
flywayRuntimeConfig.table.ifPresent(configure::table);
flywayBuildConfig.locations.map(it -> it.split(",")).ifPresent(configure::locations);
flywayRuntimeConfig.sqlMigrationPrefix.ifPresent(configure::sqlMigrationPrefix);
flywayRuntimeConfig.repeatableSqlMigrationPrefix.ifPresent(configure::repeatableSqlMigrationPrefix);
return configure.load();
}

Line under review: flywayRuntimeConfig.repeatableSqlMigrationPrefix.ifPresent(configure::repeatableSqlMigrationPrefix);

Code after addressing the review:
public Flyway produceFlyway() {
FluentConfiguration configure = Flyway.configure();
configure.dataSource(dataSource);
flywayRuntimeConfig.connectRetries.ifPresent(configure::connectRetries);
List<String> notEmptySchemas = filterBlanks(flywayRuntimeConfig.schemas);
if (!notEmptySchemas.isEmpty()) {
configure.schemas(notEmptySchemas.toArray(new String[0]));
}
flywayRuntimeConfig.table.ifPresent(configure::table);
List<String> notEmptyLocations = filterBlanks(flywayBuildConfig.locations);
if (!notEmptyLocations.isEmpty()) {
configure.locations(notEmptyLocations.toArray(new String[0]));
}
flywayRuntimeConfig.sqlMigrationPrefix.ifPresent(configure::sqlMigrationPrefix);
flywayRuntimeConfig.repeatableSqlMigrationPrefix.ifPresent(configure::repeatableSqlMigrationPrefix);
return configure.load();
}
Code review comment: configRegistry will never be null, right?

Code before review:
public Tracer getTracer(String tracerName, String serviceName) {
if (Objects.isNull(configRegistry)) {
throw new IllegalStateException("Tracer not initialized with configurations");
}
return new Configuration(
serviceName,
new Configuration.SamplerConfiguration(samplerType, samplerParam),
new Configuration.ReporterConfiguration(
Boolean.FALSE, hostname, port, reporterFlushInterval, reporterBufferSize
)
).getTracerBuilder().withScopeManager(NoOpScopeManager.INSTANCE).build();
}

Line under review: if (Objects.isNull(configRegistry)) {

Code after addressing the review:
public Tracer getTracer(String tracerName, String serviceName) {
if (Objects.isNull(configRegistry)) {
throw new IllegalStateException("Tracer not initialized with configurations");
}
return new Configuration(
serviceName,
new Configuration.SamplerConfiguration(samplerType, samplerParam),
new Configuration.ReporterConfiguration(
Boolean.FALSE, hostname, port, reporterFlushInterval, reporterBufferSize
)
).getTracerBuilder().withScopeManager(NoOpScopeManager.INSTANCE).build();
}
Code review comment: Is this format consistent for all cases?

Code before review:
static String cleanupObjectTypeName(String callName, BType objectType) {
if (!objectType.tsymbol.name.value.isEmpty() && callName.startsWith(objectType.tsymbol.name.value)) {
callName = callName.replace(objectType.tsymbol.name.value + ".", "").trim();
}
if (callName.startsWith("(") && callName.contains(").")) {
callName = callName.substring(callName.indexOf(").") + 2);
}
return callName;
}


Code after addressing the review:
static String cleanupObjectTypeName(String callName, BType objectType) {
if (!objectType.tsymbol.name.value.isEmpty() && callName.startsWith(objectType.tsymbol.name.value)) {
callName = callName.replace(objectType.tsymbol.name.value + ".", "").trim();
}
if (callName.startsWith("(") && callName.contains(").")) {
callName = callName.substring(callName.indexOf(").") + 2);
}
return callName;
}
Code review comment: what is it for ?

Code before review:
public void replace(Map<Slot, Slot> replaceMap) {
slots = slots.stream()
.map(s -> replaceMap.getOrDefault(s, s))
.collect(Collectors.toSet());
slotSets = slotSets.stream()
.map(set -> set.stream().map(s -> replaceMap.getOrDefault(s, s))
.collect(ImmutableSet.toImmutableSet()))
.collect(Collectors.toSet());
}

Line under review: .map(set -> set.stream().map(s -> replaceMap.getOrDefault(s, s))

Code after addressing the review:
public void replace(Map<Slot, Slot> replaceMap) {
uniformSet.replace(replaceMap);
uniqueSet.replace(replaceMap);
}
Code review comment: ``` List<Library> deps = platform.libraries.stream().filter(library -> library.getModules() == null ||                                                     Arrays.asList(library.getModules()).contains(moduleName)).toList(); ```

Code before review:
public String getTargetPlatform(String moduleName) {
if (isTemplateModule(moduleName)) {
return ProgramFileConstants.ANY_PLATFORM;
}
if (null != platform.libraries) {
if (null == platform.target) {
throw new BLangCompilerException("Platform target is not specified in the Ballerina.toml");
}
if (!(Arrays.stream(ProgramFileConstants.SUPPORTED_PLATFORMS).anyMatch(platform.getTarget()::equals))) {
throw new BLangCompilerException("Platform target is not " +
"supported by installed Ballerina distribution." +
"\nSupported platforms : " + supportedPlatforms());
}
List<Library> deps = platform.libraries.stream().filter(library ->
library.getModules() == null ||
Arrays.stream(library.getModules()).anyMatch(moduleName::equals)
).collect(Collectors.toList());
if (!deps.isEmpty()) {
return platform.target;
}
}
return ProgramFileConstants.ANY_PLATFORM;
}

Line under review: ).collect(Collectors.toList());

Code after addressing the review:
public String getTargetPlatform(String moduleName) {
if (isTemplateModule(moduleName)) {
return ProgramFileConstants.ANY_PLATFORM;
}
if (null != platform.libraries) {
if (null == platform.target) {
throw new BLangCompilerException("Platform target is not specified in the Ballerina.toml");
}
if (!(Arrays.stream(ProgramFileConstants.SUPPORTED_PLATFORMS).anyMatch(platform.getTarget()::equals))) {
throw new BLangCompilerException("Platform target is not " +
"supported by installed Ballerina distribution." +
"\nSupported platforms : " + supportedPlatforms());
}
List<Library> deps = platform.libraries.stream().filter(library -> library.getModules() == null ||
Arrays.stream(library.getModules()).anyMatch(moduleName::equals)).toList();
if (!deps.isEmpty()) {
return platform.target;
}
}
return ProgramFileConstants.ANY_PLATFORM;
}
Code review comment: @cescoffier maybe we could merge and adjust later if needed? I'm a bit worried that we could have annoying conflicts, considering it touches a lot of places.

Code before review:
public void testHealth() {
try {
RestAssured.defaultParser = Parser.JSON;
RestAssured.when().get("/health").then()
.body("outcome", is("UP"),
"checks.state", contains("UP"),
"checks.name", contains("basic"));
} finally {
RestAssured.reset();
}
}

Line under review: RestAssured.defaultParser = Parser.JSON;

Code after addressing the review:
public void testHealth() {
try {
RestAssured.defaultParser = Parser.JSON;
RestAssured.when().get("/health").then()
.body("outcome", is("UP"),
"checks.state", contains("UP"),
"checks.name", contains("basic"));
} finally {
RestAssured.reset();
}
}
Code review comment: Does this need to include the try count as that is inferred by attempting more than the maximum limit

Code before review:
private boolean isValidRedirectCount(int tryCount) {
if (tryCount >= getMaxAttempts()) {
LOGGER.atError()
.addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount)
.addKeyValue("maxAttempts", getMaxAttempts())
.log("Redirect attempts have been exhausted.");
return false;
}
return true;
}

Line under review: .addKeyValue(LoggingKeys.TRY_COUNT_KEY, tryCount)

Code after addressing the review:
private boolean isValidRedirectCount(int tryCount) {
if (tryCount >= getMaxAttempts()) {
LOGGER.atError()
.addKeyValue("maxAttempts", getMaxAttempts())
.log("Redirect attempts have been exhausted.");
return false;
}
return true;
}
Code review comment: I think we need to call `setProperties` in `gsonPostProcess` as well to make sure all properties are set after metadata replay.

Code before review:
private void setProperties(Map<String, String> properties) {
try {
nodes = properties.get(PROP_HOSTS).trim().split(",");
if (properties.containsKey(PROP_SSL)) {
enableSsl = EsUtil.getBoolean(properties, PROP_SSL);
}
if (StringUtils.isNotBlank(properties.get(PROP_USERNAME))) {
username = properties.get(PROP_USERNAME).trim();
}
if (StringUtils.isNotBlank(properties.get(PROP_PASSWORD))) {
password = properties.get(PROP_PASSWORD).trim();
}
if (properties.containsKey(PROP_DOC_VALUE_SCAN)) {
enableDocValueScan = EsUtil.getBoolean(properties, PROP_DOC_VALUE_SCAN);
}
if (properties.containsKey(PROP_KEYWORD_SNIFF)) {
enableKeywordSniff = EsUtil.getBoolean(properties, PROP_KEYWORD_SNIFF);
}
if (properties.containsKey(PROP_NODES_DISCOVERY)) {
enableNodesDiscovery = EsUtil.getBoolean(properties, PROP_NODES_DISCOVERY);
}
} catch (DdlException e) {
throw new RuntimeException("should not happen", e);
}
}

Line under review: try {

Code after addressing the review:
private void setProperties(Map<String, String> properties) {
try {
nodes = properties.get(PROP_HOSTS).trim().split(",");
if (properties.containsKey(PROP_SSL)) {
enableSsl = EsUtil.getBoolean(properties, PROP_SSL);
}
if (StringUtils.isNotBlank(properties.get(PROP_USERNAME))) {
username = properties.get(PROP_USERNAME).trim();
}
if (StringUtils.isNotBlank(properties.get(PROP_PASSWORD))) {
password = properties.get(PROP_PASSWORD).trim();
}
if (properties.containsKey(PROP_DOC_VALUE_SCAN)) {
enableDocValueScan = EsUtil.getBoolean(properties, PROP_DOC_VALUE_SCAN);
}
if (properties.containsKey(PROP_KEYWORD_SNIFF)) {
enableKeywordSniff = EsUtil.getBoolean(properties, PROP_KEYWORD_SNIFF);
}
if (properties.containsKey(PROP_NODES_DISCOVERY)) {
enableNodesDiscovery = EsUtil.getBoolean(properties, PROP_NODES_DISCOVERY);
}
} catch (DdlException e) {
throw new RuntimeException("should not happen", e);
}
}
Code review comment: https://stackoverflow.com/questions/35792590/how-to-check-number-of-digits-from-bigdecimal There is a trick to this as well.. ```Java xInBigDecimal = xInBigDecimal.stripTrailingZeros(); int  y = xInBigDecimal.precision() - xInBigDecimal.scale() if (y > digitsTmp) {   return 0; } ```

Code before review:
public static double round(double x, long fractionDigits) {
if (isSpecialValue(x)) {
return x;
}
if (fractionDigits == 0) {
return Math.rint(x);
}
if (fractionDigits > Integer.MAX_VALUE) {
return x;
}
if (fractionDigits < Integer.MIN_VALUE) {
return 0;
}
int fractionDigitsAsInt = (int) fractionDigits;
BigDecimal xInBigDecimal = BigDecimal.valueOf(x);
BigDecimal xTmp = xInBigDecimal;
int digitsTmp = fractionDigitsAsInt;
if (digitsTmp > 0) {
while (digitsTmp-- > 0) {
if (xTmp.remainder(BigDecimal.ONE).compareTo(BigDecimal.ZERO) == 0) {
return x;
}
xTmp = xTmp.multiply(BigDecimal.TEN);
}
} else {
while (digitsTmp++ < 0) {
if (xTmp.compareTo(BigDecimal.ZERO) == 0) {
return 0;
}
xTmp = xTmp.divide(BigDecimal.TEN, 0, RoundingMode.DOWN);
}
}
return xInBigDecimal.setScale(fractionDigitsAsInt, RoundingMode.HALF_EVEN).doubleValue();
}

Line under review: while (digitsTmp++ < 0) {

Code after addressing the review:
public static double round(double x, long fractionDigits) {
if (Double.isInfinite(x) || Double.isNaN(x) || x == 0.0d) {
return x;
}
if (fractionDigits == 0) {
return Math.rint(x);
}
if (fractionDigits > Integer.MAX_VALUE) {
return x;
}
if (fractionDigits < Integer.MIN_VALUE) {
return 0;
}
int fractionDigitsAsInt = (int) fractionDigits;
BigDecimal xInBigDecimal = BigDecimal.valueOf(x);
int scale = xInBigDecimal.scale();
if (fractionDigitsAsInt > 0) {
if (fractionDigitsAsInt > scale) {
return x;
}
} else if (-fractionDigitsAsInt > (xInBigDecimal.precision() - scale)) {
return 0;
}
return xInBigDecimal.setScale(fractionDigitsAsInt, RoundingMode.HALF_EVEN).doubleValue();
}
Code review comment: Is this possible? Don't above checks preclude this condition?

Code before review:
String resolve() throws IOException {
String from =
String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());
if (!Strings.isNullOrEmpty(options.getPrismLocation())) {
checkArgument(
!options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),
"Provided --prismLocation URL is not an Apache Beam Github "
+ "Release page URL or download URL: ",
from);
from = options.getPrismLocation();
}
String fromFileName = getNameWithoutExtension(from);
Path to = Paths.get(userHome(), PRISM_BIN_PATH, fromFileName);
if (Files.exists(to)) {
return to.toString();
}
createDirectoryIfNeeded(to);
if (from.startsWith("http")) {
String result = resolve(new URL(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
String result = resolve(Paths.get(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}

Line under review: if (from.startsWith("http")) {

Code after addressing the review:
String resolve() throws IOException {
String from =
String.format("%s/v%s/%s.zip", GITHUB_DOWNLOAD_PREFIX, getSDKVersion(), buildFileName());
if (!Strings.isNullOrEmpty(options.getPrismLocation())) {
checkArgument(
!options.getPrismLocation().startsWith(GITHUB_TAG_PREFIX),
"Provided --prismLocation URL is not an Apache Beam Github "
+ "Release page URL or download URL: ",
from);
from = options.getPrismLocation();
}
String fromFileName = getNameWithoutExtension(from);
Path to = Paths.get(userHome(), PRISM_BIN_PATH, fromFileName);
if (Files.exists(to)) {
return to.toString();
}
createDirectoryIfNeeded(to);
if (from.startsWith("http")) {
String result = resolve(new URL(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
String result = resolve(Paths.get(from), to);
checkState(Files.exists(to), "Resolved location does not exist: %s", result);
return result;
}
Code review comment: Same as above. Async client should be built with autocomplete enabled for the processor. We may have to find a different way to disable it on the `receive()` method on the sync client.

Code before review:
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout());
}

Line under review: return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout());

Code after addressing the review:
public ServiceBusReceiverClient buildClient() {
return new ServiceBusReceiverClient(buildAsyncClient(false), retryOptions.getTryTimeout());
}
Code review comment: Shall we change this to report a diagnostic?

Code before review:
public void init(CompilerPluginContext pluginContext) {
pluginContext.addCodeAnalyzer(new CodeAnalyzer() {
@Override
public void init(CodeAnalysisContext codeAnalysisContext) {
System.out.println("Hello from the analyzer");
}
});
pluginContext.addCodeGenerator(new CodeGenerator() {
@Override
public void init(CodeGeneratorContext codeGeneratorContext) {
System.out.println("Hello from the generator");
}
});
pluginContext.addCodeModifier(new CodeModifier() {
@Override
public void init(CodeModifierContext codeModifierContext) {
System.out.println("Hello from the modifier");
}
});
}

Line under review: System.out.println("Hello from the generator");

Code after addressing the review:
public void init(CompilerPluginContext pluginContext) {
pluginContext.addCodeAnalyzer(new CodeAnalyzer() {
@Override
public void init(CodeAnalysisContext codeAnalysisContext) {
appendToOutputFile(CodeType.ANALYZER);
}
});
pluginContext.addCodeGenerator(new CodeGenerator() {
@Override
public void init(CodeGeneratorContext codeGeneratorContext) {
appendToOutputFile(CodeType.GENERATOR);
}
});
pluginContext.addCodeModifier(new CodeModifier() {
@Override
public void init(CodeModifierContext codeModifierContext) {
appendToOutputFile(CodeType.MODIFIER);
}
});
}
Code review comment: Can we wrap using ZstdOutputStream instead of first encoding the entire value to bytes?  Ditto for decoding.

Code before review:
public void encode(T value, OutputStream os) throws IOException {
ZstdCompressCtx ctx = new ZstdCompressCtx();
try {
ctx.setLevel(level);
ctx.setMagicless(true);
ctx.setDictID(false);
ctx.loadDict(dict);
byte[] encoded = CoderUtils.encodeToByteArray(innerCoder, value);
ctx.setPledgedSrcSize(encoded.length);
byte[] compressed = ctx.compress(encoded);
ByteArrayCoder.of().encode(compressed, os);
} finally {
ctx.close();
}
}

Line under review: byte[] encoded = CoderUtils.encodeToByteArray(innerCoder, value);

Code after addressing the review:
public void encode(T value, OutputStream os) throws IOException {
ZstdCompressCtx ctx = new ZstdCompressCtx();
try {
ctx.setLevel(level);
ctx.setMagicless(true);
ctx.setDictID(false);
ctx.loadDict(dict);
byte[] encoded = CoderUtils.encodeToByteArray(innerCoder, value);
byte[] compressed = ctx.compress(encoded);
ByteArrayCoder.of().encode(compressed, os);
} finally {
ctx.close();
}
}
Code review comment: The WARNING log may misunderstand the user. I think the behavior is normal when some tables are dropped before publishing.

Code before review:
public void updateReplicaVersions(List<TTabletVersionPair> tabletVersions) {
if (span != null) {
span.addEvent("update_replica_version_start");
span.setAttribute("num_replicas", tabletVersions.size());
}
TabletInvertedIndex tablets = GlobalStateMgr.getCurrentInvertedIndex();
List<Long> tabletIds = tabletVersions.stream().map(tv -> tv.tablet_id).collect(Collectors.toList());
List<Replica> replicas = tablets.getReplicasOnBackendByTabletIds(tabletIds, backendId);
if (replicas == null) {
LOG.warn("backend not found backendid={}", backendId);
return;
}
Database db = GlobalStateMgr.getCurrentState().getDb(dbId);
if (db == null) {
LOG.warn("db not found dbid={}", dbId);
return;
}
List<Long> droppedTablets = new ArrayList<>();
for (int i = 0; i < tabletVersions.size(); i++) {
if (replicas.get(i) == null) {
droppedTablets.add(tabletVersions.get(i).tablet_id);
}
}
if (!droppedTablets.isEmpty()) {
LOG.warn("during publish version some tablets were dropped(maybe by alter), tabletIds={}", droppedTablets);
}
db.writeLock();
try {
for (int i = 0; i < tabletVersions.size(); i++) {
TTabletVersionPair tabletVersion = tabletVersions.get(i);
Replica replica = replicas.get(i);
if (replica == null) {
continue;
}
replica.updateVersion(tabletVersion.version);
}
} finally {
db.writeUnlock();
if (span != null) {
span.addEvent("update_replica_version_finish");
}
}
}

Line under review: if (!droppedTablets.isEmpty()) {

Code after addressing the review:
public void updateReplicaVersions(List<TTabletVersionPair> tabletVersions) {
if (span != null) {
span.addEvent("update_replica_version_start");
span.setAttribute("num_replicas", tabletVersions.size());
}
TabletInvertedIndex tablets = GlobalStateMgr.getCurrentInvertedIndex();
List<Long> tabletIds = tabletVersions.stream().map(tv -> tv.tablet_id).collect(Collectors.toList());
List<Replica> replicas = tablets.getReplicasOnBackendByTabletIds(tabletIds, backendId);
if (replicas == null) {
LOG.warn("backend not found backendid={}", backendId);
return;
}
Database db = GlobalStateMgr.getCurrentState().getDb(dbId);
if (db == null) {
LOG.warn("db not found dbid={}", dbId);
return;
}
List<Long> droppedTablets = new ArrayList<>();
for (int i = 0; i < tabletVersions.size(); i++) {
if (replicas.get(i) == null) {
droppedTablets.add(tabletVersions.get(i).tablet_id);
}
}
if (!droppedTablets.isEmpty()) {
LOG.info("during publish version some tablets were dropped(maybe by alter), tabletIds={}", droppedTablets);
}
db.writeLock();
try {
for (int i = 0; i < tabletVersions.size(); i++) {
TTabletVersionPair tabletVersion = tabletVersions.get(i);
Replica replica = replicas.get(i);
if (replica == null) {
continue;
}
replica.updateVersion(tabletVersion.version);
}
} finally {
db.writeUnlock();
if (span != null) {
span.addEvent("update_replica_version_finish");
}
}
}
Code review comment: Yes you are correct, will update.

Code before review:
private void checkFixedLength(long length) {
if (arrayType != null && arrayType.getTag() == TypeTags.TUPLE_TAG) {
BTupleType tupleType = (BTupleType) this.arrayType;
if (tupleType.getRestType() == null
|| (tupleType.getRestType() != null && tupleType.getTupleTypes().size() > length)) {
throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
RuntimeErrors.ILLEGAL_TUPLE_SIZE, length);
}
} else if (((BArrayType) this.arrayType).getState() == ArrayState.CLOSED_SEALED) {
throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
RuntimeErrors.ILLEGAL_ARRAY_SIZE, length);
}
}

Line under review: if (tupleType.getRestType() == null

Code after addressing the review:
private void checkFixedLength(long length) {
if (arrayType == null) {
return;
}
if (arrayType.getTag() == TypeTags.TUPLE_TAG) {
BTupleType tupleType = (BTupleType) this.arrayType;
if (tupleType.getRestType() == null) {
throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
RuntimeErrors.ILLEGAL_TUPLE_SIZE, size, length);
} else if (tupleType.getTupleTypes().size() > length) {
throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
RuntimeErrors.ILLEGAL_TUPLE_WITH_REST_TYPE_SIZE, tupleType.getTupleTypes().size(), length);
}
} else if (((BArrayType) this.arrayType).getState() == ArrayState.CLOSED_SEALED) {
throw BLangExceptionHelper.getRuntimeException(BallerinaErrorReasons.INHERENT_TYPE_VIOLATION_ERROR,
RuntimeErrors.ILLEGAL_ARRAY_SIZE, size, length);
}
}
Code review comment: If this throws InterruptedException then locked will be true but the lock will not have been acquired, and the finally block will attempt to unlock a lock it does not hold.

Code before review:
private Object writeLock(Lock lock, InvocationContext ctx) throws Exception {
boolean locked = true;
long time = lock.time();
try {
if (time > 0) {
locked = readWriteLock.writeLock().tryLock(time, lock.unit());
if (!locked) {
throw new LockException("Write lock not acquired in " + lock.unit().toMillis(time) + " ms");
}
} else {
readWriteLock.writeLock().lock();
}
return ctx.proceed();
} finally {
if (locked) {
readWriteLock.writeLock().unlock();
}
}
}

Line under review: locked = readWriteLock.writeLock().tryLock(time, lock.unit());

Code after addressing the review:
private Object writeLock(Lock lock, InvocationContext ctx) throws Exception {
boolean locked = false;
long time = lock.time();
try {
if (time > 0) {
locked = readWriteLock.writeLock().tryLock(time, lock.unit());
if (!locked) {
throw new LockException("Write lock not acquired in " + lock.unit().toMillis(time) + " ms");
}
} else {
readWriteLock.writeLock().lock();
locked = true;
}
return ctx.proceed();
} finally {
if (locked) {
readWriteLock.writeLock().unlock();
}
}
}
Code review comment: Just a formatting thing: I think it would be more readable to have both lambda statements on new lines.

Code before review:
public PagedFlux<KeyBase> listKeys() {
return new PagedFlux<>(() -> listKeysFirstPage(),
continuationToken -> listKeysNextPage(continuationToken));
}

Line under review: continuationToken -> listKeysNextPage(continuationToken));

Code after addressing the review:
public PagedFlux<KeyBase> listKeys() {
return new PagedFlux<>(() ->
listKeysFirstPage(),
continuationToken -> listKeysNextPage(continuationToken));
}
Code review comment: for checkstyle: `preTransactionType != null` => `null != preTransactionType`

Code before review:
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
ShardingTransactionType shardingTransactionType = getAnnotation(methodInvocation);
Objects.requireNonNull(shardingTransactionType, "could not found sharding transaction type annotation");
TransactionType preTransactionType = TransactionTypeHolder.get();
TransactionTypeHolder.set(shardingTransactionType.value());
try {
return methodInvocation.proceed();
} finally {
TransactionTypeHolder.clear();
if (preTransactionType != null) {
TransactionTypeHolder.set(preTransactionType);
}
}
}

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

Code after addressing the review:
public Object invoke(final MethodInvocation methodInvocation) throws Throwable {
ShardingTransactionType shardingTransactionType = getAnnotation(methodInvocation);
Objects.requireNonNull(shardingTransactionType, "could not found sharding transaction type annotation");
TransactionType preTransactionType = TransactionTypeHolder.get();
TransactionTypeHolder.set(shardingTransactionType.value());
try {
return methodInvocation.proceed();
} finally {
TransactionTypeHolder.clear();
if (null != preTransactionType) {
TransactionTypeHolder.set(preTransactionType);
}
}
}
Code review comment: I think you could just use phase instead of getPhase() here

Code before review:
public void onNext(T value) {
synchronized (lock) {
if (++numMessages >= maxMessagesBeforeCheck) {
numMessages = 0;
int waitTime = 1;
int totalTimeWaited = 0;
int phase = phaser.getPhase();
int initialPhase = phase;
while (!outboundObserver.isReady()) {
try {
phase = phaser.awaitAdvanceInterruptibly(phase, waitTime, TimeUnit.SECONDS);
} catch (TimeoutException e) {
totalTimeWaited += waitTime;
waitTime = waitTime * 2;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
if (totalTimeWaited > 0) {
if (initialPhase == phaser.getPhase()) {
LOG.info(
"Output channel stalled for {}s, outbound thread {}. See: "
+ "https:
+ "this issue.",
totalTimeWaited,
Thread.currentThread().getName());
} else {
LOG.debug(
"Output channel stalled for {}s, outbound thread {}.",
totalTimeWaited,
Thread.currentThread().getName());
}
}
}
outboundObserver.onNext(value);
}
}

Line under review: if (initialPhase == phaser.getPhase()) {

Code after addressing the review:
public void onNext(T value) {
synchronized (lock) {
if (++numMessages >= maxMessagesBeforeCheck) {
numMessages = 0;
int waitTime = 1;
int totalTimeWaited = 0;
int phase = phaser.getPhase();
int initialPhase = phase;
while (!outboundObserver.isReady()) {
try {
phase = phaser.awaitAdvanceInterruptibly(phase, waitTime, TimeUnit.SECONDS);
} catch (TimeoutException e) {
totalTimeWaited += waitTime;
waitTime = waitTime * 2;
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}
if (totalTimeWaited > 0) {
if (initialPhase == phase) {
LOG.info(
"Output channel stalled for {}s, outbound thread {}. See: "
+ "https:
+ "this issue.",
totalTimeWaited,
Thread.currentThread().getName());
} else {
LOG.debug(
"Output channel stalled for {}s, outbound thread {}.",
totalTimeWaited,
Thread.currentThread().getName());
}
}
}
outboundObserver.onNext(value);
}
}
Code review comment: ops! yes ;) I've used [guava](https://guava.dev/releases/19.0/api/docs/com/google/common/io/Closer.html) nomenclature 

Code before review:
public void close() throws RocksDBException {
try {
if (batch.count() != 0) {
flush();
}
} finally {
IOUtils.closeQuietly(batch);
if (ownsWriteOptions) {
IOUtils.closeQuietly(options);
}
}
}

Line under review: }

Code after addressing the review:
public void close() throws RocksDBException {
try {
if (batch.count() != 0) {
flush();
}
} finally {
IOUtils.closeAllQuietly(toClose);
}
}
Code review comment: We should also check for `isNullLiteral`?

Code before review:
private void setArguments(CallContext callContext) {
DataType[] inputTypes = callContext.getArgumentDataTypes().toArray(new DataType[0]);
Object[] constantArgs = new Object[inputTypes.length];
for (int i = 0; i < constantArgs.length; i++) {
if (callContext.isArgumentLiteral(i)) {
constantArgs[i] = callContext.getArgumentValue(
i, ClassLogicalTypeConverter.getDefaultExternalClassForType(inputTypes[i].getLogicalType()))
.orElse(null);
}
}
this.constantArguments = constantArgs;
this.argTypes = inputTypes;
}

Line under review: if (callContext.isArgumentLiteral(i)) {

Code after addressing the review:
private void setArguments(CallContext callContext) {
DataType[] inputTypes = callContext.getArgumentDataTypes().toArray(new DataType[0]);
Object[] constantArgs = new Object[inputTypes.length];
for (int i = 0; i < constantArgs.length; i++) {
if (callContext.isArgumentLiteral(i)) {
constantArgs[i] = callContext.getArgumentValue(
i, ClassLogicalTypeConverter.getDefaultExternalClassForType(inputTypes[i].getLogicalType()))
.orElse(null);
}
}
this.constantArguments = constantArgs;
this.argTypes = inputTypes;
}
Code review comment: Let's stay with the option 2 (as you have currently implemented)

Code before review:
public BufferAndBacklog getNextBuffer() throws IOException {
if (isReleased) {
return null;
}
Buffer current = dataReader.nextBuffer();
if (current == null) {
return null;
}
updateStatistics(current);
Buffer.DataType nextDataType = Buffer.DataType.NONE;
if (numDataBuffers > 0) {
nextDataType = Buffer.DataType.DATA_BUFFER;
} else if (numDataAndEventBuffers > 0) {
nextDataType = Buffer.DataType.EVENT_BUFFER;
}
return BufferAndBacklog.fromBufferAndLookahead(
current, nextDataType, numDataBuffers, sequenceNumber++);
}

Line under review: }

Code after addressing the review:
public BufferAndBacklog getNextBuffer() throws IOException {
if (isReleased) {
return null;
}
Buffer current = dataReader.nextBuffer();
if (current == null) {
return null;
}
updateStatistics(current);
Buffer.DataType nextDataType = Buffer.DataType.NONE;
if (numDataBuffers > 0) {
nextDataType = Buffer.DataType.DATA_BUFFER;
} else if (numDataAndEventBuffers > 0) {
nextDataType = Buffer.DataType.EVENT_BUFFER;
}
return BufferAndBacklog.fromBufferAndLookahead(
current, nextDataType, numDataBuffers, sequenceNumber++);
}
Code review comment: same as above (if I understand your suggestion correctly)

Code before review:
private static String getTargetOrNullOldSemconv(Attributes attributes, int defaultPort) {
String peerService = attributes.get(SemanticAttributes.PEER_SERVICE);
if (peerService != null) {
return peerService;
}
String host = attributes.get(SemanticAttributes.NET_PEER_NAME);
if (host != null) {
Long port = attributes.get(SemanticAttributes.NET_PEER_PORT);
return getTarget(host, port, defaultPort);
}
host = attributes.get(SemanticAttributes.NET_SOCK_PEER_NAME);
if (host == null) {
host = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR);
}
if (host != null) {
Long port = attributes.get(SemanticAttributes.NET_SOCK_PEER_PORT);
return getTarget(host, port, defaultPort);
}
String httpUrl = attributes.get(SemanticAttributes.HTTP_URL);
if (httpUrl != null) {
return UrlParser.getTarget(httpUrl);
}
return null;
}

Line under review: Long port = attributes.get(SemanticAttributes.NET_SOCK_PEER_PORT);

Code after addressing the review:
private static String getTargetOrNullOldSemconv(Attributes attributes, int defaultPort) {
String peerService = attributes.get(SemanticAttributes.PEER_SERVICE);
if (peerService != null) {
return peerService;
}
String host = attributes.get(SemanticAttributes.NET_PEER_NAME);
if (host != null) {
Long port = attributes.get(SemanticAttributes.NET_PEER_PORT);
return getTarget(host, port, defaultPort);
}
host = attributes.get(SemanticAttributes.NET_SOCK_PEER_NAME);
if (host == null) {
host = attributes.get(SemanticAttributes.NET_SOCK_PEER_ADDR);
}
if (host != null) {
Long port = attributes.get(SemanticAttributes.NET_SOCK_PEER_PORT);
return getTarget(host, port, defaultPort);
}
String httpUrl = attributes.get(SemanticAttributes.HTTP_URL);
if (httpUrl != null) {
return UrlParser.getTarget(httpUrl);
}
return null;
}
Code review comment: Instead of the `StatelessIdentityDoFn` we could use `MapElements.into(...).via(e -> KV.of("", e.getValue())`, which would enforce shuffle semantically. That might improve readability a bit.

Code before review:
private JobGraph getStatefulParDoAfterCombineChainingJobGraph(boolean stablePartitioning) {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
final FlinkStreamingPipelineTranslator translator =
new FlinkStreamingPipelineTranslator(env, PipelineOptionsFactory.create());
final PipelineOptions pipelineOptions = PipelineOptionsFactory.create();
pipelineOptions.setRunner(FlinkRunner.class);
final Pipeline pipeline = Pipeline.create(pipelineOptions);
PCollection<KV<String, Long>> aggregate =
pipeline
.apply(Create.of("foo", "bar").withCoder(StringUtf8Coder.of()))
.apply(Count.perElement());
if (!stablePartitioning) {
aggregate = aggregate.apply(ParDo.of(new StatelessIdentityDoFn<>()));
}
aggregate.apply(ParDo.of(new StatefulNoopDoFn<>()));
translator.translate(pipeline);
return env.getStreamGraph().getJobGraph();
}

Line under review: aggregate = aggregate.apply(ParDo.of(new StatelessIdentityDoFn<>()));

Code after addressing the review:
private JobGraph getStatefulParDoAfterCombineChainingJobGraph(boolean stablePartitioning) {
final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
final FlinkStreamingPipelineTranslator translator =
new FlinkStreamingPipelineTranslator(env, PipelineOptionsFactory.create());
final PipelineOptions pipelineOptions = PipelineOptionsFactory.create();
pipelineOptions.setRunner(FlinkRunner.class);
final Pipeline pipeline = Pipeline.create(pipelineOptions);
PCollection<KV<String, Long>> aggregate =
pipeline
.apply(Create.of("foo", "bar").withCoder(StringUtf8Coder.of()))
.apply(Count.perElement());
if (!stablePartitioning) {
aggregate = aggregate.apply(ParDo.of(new StatelessIdentityDoFn<>()));
}
aggregate.apply(ParDo.of(new StatefulNoopDoFn<>()));
translator.translate(pipeline);
return env.getStreamGraph().getJobGraph();
}