muttakin2301/ccr2000 huggingface dataset:
Code review comment: Hm... Here we aren't storing the references, just using them to check and then obtain the bean. So we don't need to close them anywhere, no?

Code under review:
private Object getBeanInstance(Object testInstance, Field field) {
        Class<?> fieldClass = field.getType();
        InstanceHandle<?> instance = Arc.container().instance(fieldClass, getQualifiers(field));
        if (!instance.isAvailable()) {
            throw new IllegalStateException("Invalid use of @MockBean - could not determine bean of type: "
                    + fieldClass + ". Offending field is " + field.getName() + " of test class "
                    + testInstance.getClass());
        }
        return instance.get();
    }

Line commented on: InstanceHandle<?> instance = Arc.container().instance(fieldClass, getQualifiers(field));

Revised code:
private Object getBeanInstance(Object testInstance, Field field) {
        Class<?> fieldClass = field.getType();
        InstanceHandle<?> instance = Arc.container().instance(fieldClass, getQualifiers(field));
        if (!instance.isAvailable()) {
            throw new IllegalStateException("Invalid use of @InjectMock - could not determine bean of type: "
                    + fieldClass + ". Offending field is " + field.getName() + " of test class "
                    + testInstance.getClass());
        }
        return instance.get();
    }
Code review comment: I guess we could make this method empty and remove `canceled` variable for this concrete unit test.

Code under review:
public void cancel() {
			canceled = true;
		}

Line commented on: canceled = true;

Revised code:
public void cancel() {
			isRunning = false;
		}
Code review comment: Shouldn't this be done irrespective of whether a user-specified module init exists?  The following two scenarios would produce two different sets of errors atm?  Case I ```ballerina int i;  function __init() {  }  public function main() {    int j = i; } ```  Case II ```ballerina int i;  public function main() {    int j = i; } ```

Code under review:
public void visit(BLangPackage pkgNode) {
        if (pkgNode.completedPhases.contains(CompilerPhase.DATAFLOW_ANALYZE)) {
            return;
        }

        
        List<TopLevelNode> sortedListOfNodes = new ArrayList<>(pkgNode.globalVars);
        pkgNode.topLevelNodes.forEach(topLevelNode -> {
            if (!sortedListOfNodes.contains(topLevelNode)) {
                sortedListOfNodes.add(topLevelNode);
            }
        });

        sortedListOfNodes.forEach(topLevelNode -> {
            if (isModuleInitFunction((BLangNode) topLevelNode)) {
                analyzeModuleInitFunc((BLangFunction) topLevelNode);
                checkForUninitializedGlobalVar(pkgNode.globalVars);
            } else {
                analyzeNode((BLangNode) topLevelNode, env);
            }
        });
        pkgNode.getTestablePkgs().forEach(testablePackage -> visit((BLangPackage) testablePackage));
        this.globalVariableRefAnalyzer.analyzeAndReOrder(pkgNode, this.globalNodeDependsOn);
        this.globalVariableRefAnalyzer.populateFunctionDependencies(this.functionToDependency);
        checkUnusedImports(pkgNode.imports);
        pkgNode.completedPhases.add(CompilerPhase.DATAFLOW_ANALYZE);
    }

Line commented on: checkForUninitializedGlobalVar(pkgNode.globalVars);

Revised code:
public void visit(BLangPackage pkgNode) {
        if (pkgNode.completedPhases.contains(CompilerPhase.DATAFLOW_ANALYZE)) {
            return;
        }

        
        List<TopLevelNode> sortedListOfNodes = new ArrayList<>(pkgNode.globalVars);
        addModuleInitToSortedNodeList(pkgNode, sortedListOfNodes);
        addNodesToSortedNodeList(pkgNode, sortedListOfNodes);

        for (TopLevelNode topLevelNode : sortedListOfNodes) {
            if (isModuleInitFunction((BLangNode) topLevelNode)) {
                analyzeModuleInitFunc((BLangFunction) topLevelNode);
            } else {
                analyzeNode((BLangNode) topLevelNode, env);
            }
        }
        checkForUninitializedGlobalVars(pkgNode.globalVars);
        pkgNode.getTestablePkgs().forEach(testablePackage -> visit((BLangPackage) testablePackage));
        this.globalVariableRefAnalyzer.analyzeAndReOrder(pkgNode, this.globalNodeDependsOn);
        this.globalVariableRefAnalyzer.populateFunctionDependencies(this.functionToDependency);
        checkUnusedImports(pkgNode.imports);
        pkgNode.completedPhases.add(CompilerPhase.DATAFLOW_ANALYZE);
    }
Code review comment: Yes. Right now there is nothing to do.

Code under review:
public void applyToConfiguration(Configuration configuration) {
        hdfsCloudCredential.applyToConfiguration(configuration);
        addConfigResourcesToConfiguration(configResources, configuration);
    }

Line commented on: hdfsCloudCredential.applyToConfiguration(configuration);

Revised code:
public void applyToConfiguration(Configuration configuration) {
        hdfsCloudCredential.applyToConfiguration(configuration);
        addConfigResourcesToConfiguration(configResources, configuration);
    }
Code review comment: I am wondering should we use block() here?

Code under review:
public void createContainerWithComputedProperties() {
        CosmosContainerProperties containerProperties = getCollectionDefinition(containerName);
        
        List<ComputedProperty> computedProperties = new ArrayList<>(
                Arrays.asList(
                        new ComputedProperty("lowerName", "SELECT VALUE LOWER(c.name) FROM c")
                )
        );
        containerProperties.setComputedProperties(computedProperties);
        database.createContainer(containerProperties).subscribe();
        
    }

Line commented on: database.createContainer(containerProperties).subscribe();

Revised code:
public void createContainerWithComputedProperties() {
        CosmosContainerProperties containerProperties = getCollectionDefinition(containerName);
        
        List<ComputedProperty> computedProperties = new ArrayList<>(
                Arrays.asList(
                        new ComputedProperty("lowerName", "SELECT VALUE LOWER(c.name) FROM c")
                )
        );
        containerProperties.setComputedProperties(computedProperties);
        database.createContainer(containerProperties).subscribe();
        
    }
Code review comment: Agree, the API is not ideal.

Code under review:
private List<Node> performOn(NodeFilter filter, BiFunction<Node, Mutex, Node> action) {
        List<Node> unallocatedNodes = new ArrayList<>();
        ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>();

        
        for (Node node : db.readNodes()) {
            if ( ! filter.matches(node)) continue;
            if (node.allocation().isPresent())
                allocatedNodes.put(node.allocation().get().owner(), node);
            else
                unallocatedNodes.add(node);
        }

        
        List<Node> resultingNodes = new ArrayList<>();
        try (Mutex lock = lockUnallocated()) {
            for (Node node : unallocatedNodes) {
                Optional<Node> currentNode = db.readNode(node.hostname()); 
                if (currentNode.isEmpty()) continue;
                resultingNodes.add(action.apply(currentNode.get(), lock));
            }
        }
        for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) {
            try (Mutex lock = lock(applicationNodes.getKey())) {
                for (Node node : applicationNodes.getValue()) {
                    Optional<Node> currentNode = db.readNode(node.hostname());  
                    if (currentNode.isEmpty()) continue;
                    resultingNodes.add(action.apply(currentNode.get(), lock));
                }
            }
        }
        return resultingNodes;
    }

Line commented on: Optional<Node> currentNode = db.readNode(node.hostname());

Revised code:
private List<Node> performOn(NodeFilter filter, BiFunction<Node, Mutex, Node> action) {
        List<Node> unallocatedNodes = new ArrayList<>();
        ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>();

        
        for (Node node : db.readNodes()) {
            if ( ! filter.matches(node)) continue;
            if (node.allocation().isPresent())
                allocatedNodes.put(node.allocation().get().owner(), node);
            else
                unallocatedNodes.add(node);
        }

        
        List<Node> resultingNodes = new ArrayList<>();
        try (Mutex lock = lockUnallocated()) {
            for (Node node : unallocatedNodes) {
                Optional<Node> currentNode = db.readNode(node.hostname()); 
                if (currentNode.isEmpty()) continue;
                resultingNodes.add(action.apply(currentNode.get(), lock));
            }
        }
        for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) {
            try (Mutex lock = lock(applicationNodes.getKey())) {
                for (Node node : applicationNodes.getValue()) {
                    Optional<Node> currentNode = db.readNode(node.hostname());  
                    if (currentNode.isEmpty()) continue;
                    resultingNodes.add(action.apply(currentNode.get(), lock));
                }
            }
        }
        return resultingNodes;
    }
Code review comment: The most risky bug in this code is: Exposing sensitive information through accessors  You can modify the code like this: ```java // It's not recommended to provide public getters for sensitive information like access keys and secret keys. // If you need to provide read access to this data, rethink your design to ensure it's done securely, // and consider limiting the scope of the access. Perhaps use a more secure method to handle sensitive credentials. public class AliyunCloudCredential {     private String accessKey;     private String secretKey;     private String endpoint;      // Existing constructor and other methods...      // Remove or limit the getters for sensitive information.     // For demonstration purposes here, they're simply removed.      @Override     public void applyToConfiguration(Configuration configuration) {         configuration.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem");     }      // Additional methods and class implementation... } ```

Code under review:
public void applyToConfiguration(Configuration configuration) {
        configuration.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem");
        configuration.set("fs.AbstractFileSystem.oss.impl", "com.aliyun.jindodata.oss.OSS");
        configuration.set("fs.oss.accessKeyId", accessKey);
        configuration.set("fs.oss.accessKeySecret", secretKey);
        configuration.set("fs.oss.endpoint", endpoint);
    }

Line commented on: configuration.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem");

Revised code:
public void applyToConfiguration(Configuration configuration) {
        configuration.set("fs.oss.impl", "com.aliyun.jindodata.oss.JindoOssFileSystem");
        configuration.set("fs.AbstractFileSystem.oss.impl", "com.aliyun.jindodata.oss.OSS");
        configuration.set("fs.oss.accessKeyId", accessKey);
        configuration.set("fs.oss.accessKeySecret", secretKey);
        configuration.set("fs.oss.endpoint", endpoint);
    }
Code review comment: I think it's better to assign aliases: `SELECT 1 AS x, '1' AS y ...` so that in unlikely case Calcite changes the convention of calling these `EXPR$..` the test doesn't break

Code under review:
public void testValues_selectEmpty() throws Exception {
    String sql = "select 1, '1' FROM string_table WHERE false";
    PCollection<Row> rows = compilePipeline(sql, pipeline);
    PAssert.that(rows)
        .containsInAnyOrder(
            TestUtils.RowsBuilder.of(
                    Schema.FieldType.INT32, "EXPR$0",
                    Schema.FieldType.STRING, "EXPR$1")
                .getRows());
    pipeline.run();
  }

Line commented on: String sql = "select 1, '1' FROM string_table WHERE false";

Revised code:
public void testValues_selectEmpty() throws Exception {
    String sql = "select 1, '1' FROM string_table WHERE false";
    PCollection<Row> rows = compilePipeline(sql, pipeline);
    PAssert.that(rows)
        .containsInAnyOrder(
            TestUtils.RowsBuilder.of(
                    Schema.FieldType.INT32, "EXPR$0",
                    Schema.FieldType.STRING, "EXPR$1")
                .getRows());
    pipeline.run();
  }
Code review comment: I was thinking of when we have to renew multiple lock Token in one go and need to expose that API,  this would be helpful. But for now I have changed this like you said.

Code under review:
private Message createManagementMessage(String operation, String linkName) {
        final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout);
        final Map<String, Object> applicationProperties = new HashMap<>();
        applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation);
        applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis());

        if (linkName != null && !linkName.isEmpty()) {
            applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName);
        }

        final Message message = Proton.message();
        message.setApplicationProperties(new ApplicationProperties(applicationProperties));

        return message;
    }

Line commented on: return message;

Revised code:
private Message createManagementMessage(String operation, String linkName) {
        final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout);
        final Map<String, Object> applicationProperties = new HashMap<>();
        applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation);
        applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis());

        if (linkName != null && !linkName.isEmpty()) {
            applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName);
        }

        final Message message = Proton.message();
        message.setApplicationProperties(new ApplicationProperties(applicationProperties));

        return message;
    }
Code review comment: This line can be removed if you pass the default client as suggested above.

Code under review:
private HttpPipeline setupPipeline(HttpClient httpClient) {
        List<HttpPipelinePolicy> policies = new ArrayList<>();
        HttpLogOptions httpLogOptions = new HttpLogOptions();
        HttpPolicyProviders.addBeforeRetryPolicies(policies);
        policies.add(new RetryPolicy());
        HttpPolicyProviders.addAfterRetryPolicies(policies);
        policies.add(new HttpLoggingPolicy(httpLogOptions));
        HttpClient client = httpClient != null ? httpClient : HttpClient.createDefault();
        return new HttpPipelineBuilder().httpClient(client)
                   .policies(policies.toArray(new HttpPipelinePolicy[0])).build();
    }

Line commented on: HttpClient client = httpClient != null ? httpClient : HttpClient.createDefault();

Revised code:
private HttpPipeline setupPipeline(HttpClient httpClient) {
        List<HttpPipelinePolicy> policies = new ArrayList<>();
        HttpLogOptions httpLogOptions = new HttpLogOptions();
        HttpPolicyProviders.addBeforeRetryPolicies(policies);
        policies.add(new RetryPolicy());
        HttpPolicyProviders.addAfterRetryPolicies(policies);
        policies.add(new HttpLoggingPolicy(httpLogOptions));
        return new HttpPipelineBuilder().httpClient(httpClient)
                   .policies(policies.toArray(new HttpPipelinePolicy[0])).build();
    }
Code review comment: I see 2 paths above for assigning to `from`:  ```     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();     } ```  In either of these assignments are followed, won't `from` start with either `GITHUB_DOWNLOAD_PREFIX` or `GITHUB_TAG_PREFIX` which both start with `https://`?

Code under 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 commented on: if (from.startsWith("http")) {

Revised code:
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: Yeah, agree, will fix in a forthcoming PR

Code under review:
private String inProgressOutput(JsonNode hosts) {
        ArrayList<String> statusPerHost = new ArrayList<>();
        for (JsonNode host : hosts) {
            StringBuilder sb = new StringBuilder();
            String status = host.get("status").asText();
            sb.append(host.get("hostname").asText()).append(": ").append(status);
            if (status.equals(statusUnknown))
                sb.append(" (").append(host.get("message").asText()).append(")");
            else if (status.equals(statusInProgress)) {
                JsonNode fileReferencesArray = host.get("fileReferences");
                int size = fileReferencesArray.size();
                int finished = 0;
                for (JsonNode element : fileReferencesArray) {
                    for (Iterator<Map.Entry<String, JsonNode>> it = element.fields(); it.hasNext(); ) {
                        Map.Entry<String, JsonNode> fileReferenceStatus = it.next();
                        if (fileReferenceStatus.getValue().asDouble() == 1.0)
                            finished++;
                    }
                }
                sb.append(" (" + finished + " of " + size + " finished)");
            }
            statusPerHost.add(sb.toString());
        }
        return String.join("\n", statusPerHost);
    }

Line commented on: else if (status.equals(statusInProgress)) {

Revised code:
private String inProgressOutput(JsonNode hosts) {
        ArrayList<String> statusPerHost = new ArrayList<>();
        for (JsonNode host : hosts) {
            StringBuilder sb = new StringBuilder();
            String status = host.get("status").asText();
            sb.append(host.get("hostname").asText()).append(": ").append(status);
            if (status.equals(statusUnknown))
                sb.append(" (").append(host.get("message").asText()).append(")");
            else if (status.equals(statusInProgress)) {
                JsonNode fileReferencesArray = host.get("fileReferences");
                int size = fileReferencesArray.size();
                int finished = 0;
                for (JsonNode element : fileReferencesArray) {
                    for (Iterator<Map.Entry<String, JsonNode>> it = element.fields(); it.hasNext(); ) {
                        Map.Entry<String, JsonNode> fileReferenceStatus = it.next();
                        if (fileReferenceStatus.getValue().asDouble() == 1.0)
                            finished++;
                    }
                }
                sb.append(" (" + finished + " of " + size + " finished)");
            }
            statusPerHost.add(sb.toString());
        }
        return String.join("\n", statusPerHost);
    }
Code review comment: Same with this one. I'm not sure if Yijun fixed this too.

Code under review:
public ServiceBusReceiverAsyncClient buildAsyncClient() {
            final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
                queueName);
            final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
                SubQueue.NONE);

            validateAndThrow(prefetchCount);
            validateAndThrow(maxAutoLockRenewDuration);

            final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);
            final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
                sessionId, isRollingSessionReceiver(), maxConcurrentSessions, maxAutoLockRenewDuration);

            final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
                connectionProcessor, tracerProvider, messageSerializer, receiverOptions);

            return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
                entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
                tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose,
                maxAutoLockRenewDuration, sessionManager);
        }

Line commented on: validateAndThrow(prefetchCount);

Revised code:
public ServiceBusReceiverAsyncClient buildAsyncClient() {
            final MessagingEntityType entityType = validateEntityPaths(logger, connectionStringEntityName, topicName,
                queueName);
            final String entityPath = getEntityPath(logger, entityType, queueName, topicName, subscriptionName,
                SubQueue.NONE);

            final ServiceBusConnectionProcessor connectionProcessor = getOrCreateConnectionProcessor(messageSerializer);

            if (receiveMode == ReceiveMode.RECEIVE_AND_DELETE) {
                maxAutoLockRenewDuration = Duration.ZERO;
            }

            final ReceiverOptions receiverOptions = new ReceiverOptions(receiveMode, prefetchCount,
                sessionId, isRollingSessionReceiver(), maxConcurrentSessions, maxAutoLockRenewDuration);

            final ServiceBusSessionManager sessionManager = new ServiceBusSessionManager(entityPath, entityType,
                connectionProcessor, tracerProvider, messageSerializer, receiverOptions);

            return new ServiceBusReceiverAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), entityPath,
                entityType, receiverOptions, connectionProcessor, ServiceBusConstants.OPERATION_TIMEOUT,
                tracerProvider, messageSerializer, ServiceBusClientBuilder.this::onClientClose, sessionManager);
        }
Code review comment: Can we verify that the group doesn't include range deletes, and throw an exception if it does?

Code under review:
public static long countOf(SpannerSchema spannerSchema, MutationGroup mutationGroup) {
    long mutatedCells = 0L;
    for (Mutation mutation : mutationGroup) {
      if (mutation.getOperation() != Op.DELETE) {
        
        for (String column : mutation.getColumns()) {
          mutatedCells += spannerSchema.getCellsMutatedPerColumn(mutation.getTable(), column);
        }
      } else {
        
        
        
        final KeySet keySet = mutation.getKeySet();

        final long rows = Iterables.size(keySet.getKeys());
        if (rows > 0) {
          mutatedCells += rows * spannerSchema.getCellsMutatedPerRow(mutation.getTable());
        }
      }
    }

    return mutatedCells;
  }


Revised code:
public static long countOf(SpannerSchema spannerSchema, MutationGroup mutationGroup) {
    long mutatedCells = 0L;
    for (Mutation mutation : mutationGroup) {
      if (mutation.getOperation() == Op.DELETE) {
        
        
        if (isPointDelete(mutation)) {
          final KeySet keySet = mutation.getKeySet();

          final long rows = Iterables.size(keySet.getKeys());
          mutatedCells += rows * spannerSchema.getCellsMutatedPerRow(mutation.getTable());
        }
      } else {
        
        for (String column : mutation.getColumns()) {
          mutatedCells += spannerSchema.getCellsMutatedPerColumn(mutation.getTable(), column);
        }
      }
    }

    return mutatedCells;
  }
Code review comment: But, if we keep it in a constant, the error will be initialised even if there's no error. Wouldn't that be unnecessary?

Code under review:
public static long abs(long n) {
        if (n <= Long.MIN_VALUE) {
            throw ErrorCreator.createError(getModulePrefixedReason(INT_LANG_LIB,
                            BallerinaErrorReasons.NUMBER_OVERFLOW_ERROR_IDENTIFIER),
                    BLangExceptionHelper.getErrorDetails(RuntimeErrors.INT_RANGE_OVERFLOW_ERROR));
        }
        return Math.abs(n);
    }

Line commented on: throw ErrorCreator.createError(getModulePrefixedReason(INT_LANG_LIB,

Revised code:
public static long abs(long n) {
        if (n <= Long.MIN_VALUE) {
            throw ErrorCreator.createError(getModulePrefixedReason(INT_LANG_LIB,
                            BallerinaErrorReasons.NUMBER_OVERFLOW_ERROR_IDENTIFIER),
                    BLangExceptionHelper.getErrorDetails(RuntimeErrors.INT_RANGE_OVERFLOW_ERROR));
        }
        return Math.abs(n);
    }
Code review comment: @menghaoranss Why not init workerId in `init` method?

Code under review:
private long getWorkerId() {
        if (null == instanceContext) {
            return DEFAULT_WORKER_ID;
        }
        long result = instanceContext.getWorkerId();
        Preconditions.checkArgument(result >= 0L && result < WORKER_ID_MAX_VALUE, "Illegal worker id.");
        return result;
    }

Line commented on: long result = instanceContext.getWorkerId();

Revised code:
private long getWorkerId() {
        if (null == instanceContext) {
            return DEFAULT_WORKER_ID;
        }
        long result = instanceContext.getWorkerId();
        Preconditions.checkArgument(result >= 0L && result < WORKER_ID_MAX_VALUE, "Illegal worker id.");
        return result;
    }
Code review comment: We can merge records and objects into one by casting the typeNode to `BStructureTypeNode`

Code under review:
private void createDummyTypeDefSymbol(BLangTypeDefinition typeDef, SymbolEnv env) {
        
        typeDef.symbol = Symbols.createTypeSymbol(SymTag.TYPE_DEF, Flags.asMask(typeDef.flagSet),
                names.fromIdNode(typeDef.name), env.enclPkg.symbol.pkgID, typeDef.typeNode.type, env.scope.owner);
        typeDef.symbol.scope = env.scope;

        
        switch (typeDef.typeNode.type.tag) {
            case TypeTags.RECORD:
                typeDef.symbol.kind = ((BLangRecordTypeNode) typeDef.typeNode).symbol.kind;
                ((BLangRecordTypeNode) typeDef.typeNode).symbol.scope = env.scope;
                break;
            case TypeTags.OBJECT:
                typeDef.symbol.kind = ((BLangObjectTypeNode) typeDef.typeNode).symbol.kind;
                ((BLangObjectTypeNode) typeDef.typeNode).symbol.scope = env.scope;
                break;
        }

        defineSymbol(typeDef.pos, typeDef.symbol, env);
    }

Line commented on: case TypeTags.OBJECT:

Revised code:
private void createDummyTypeDefSymbol(BLangTypeDefinition typeDef, SymbolEnv env) {
        
        typeDef.symbol = Symbols.createTypeSymbol(SymTag.TYPE_DEF, Flags.asMask(typeDef.flagSet),
                names.fromIdNode(typeDef.name), env.enclPkg.symbol.pkgID, typeDef.typeNode.type, env.scope.owner);
        typeDef.symbol.scope = env.scope;

        
        switch (typeDef.typeNode.type.tag) {
            case TypeTags.RECORD:
            case TypeTags.OBJECT:
                typeDef.symbol.kind = ((BLangStructureTypeNode) typeDef.typeNode).symbol.kind;
                ((BLangStructureTypeNode) typeDef.typeNode).symbol.scope = env.scope;
                break;
        }

        defineSymbol(typeDef.pos, typeDef.symbol, env);
    }
Code review comment: @geoand is it the expected behavior? I'm surprised that RestEasy Reactive does not decode the path parameter.

Code under review:
void shouldDetermineUrlViaStorkWhenUsingTarget() throws URISyntaxException {
        String greeting = ClientBuilder.newClient().target("stork:
                .get(String.class);
        assertThat(greeting).isEqualTo("Hello, World!");

        greeting = ClientBuilder.newClient().target(new URI("stork:
        assertThat(greeting).isEqualTo("Hello, World!");

        greeting = ClientBuilder.newClient().target(UriBuilder.fromUri("stork:
                .get(String.class);
        assertThat(greeting).isEqualTo("Hello, World!");

        greeting = ClientBuilder.newClient().target("stork:
                .get(String.class);
        assertThat(greeting).isEqualTo("Hello, big%20bird");
    }

Line commented on: assertThat(greeting).isEqualTo("Hello, big%20bird");

Revised code:
void shouldDetermineUrlViaStorkWhenUsingTarget() throws URISyntaxException {
        String greeting = ClientBuilder.newClient().target("stork:
                .get(String.class);
        assertThat(greeting).isEqualTo("Hello, World!");

        greeting = ClientBuilder.newClient().target(new URI("stork:
        assertThat(greeting).isEqualTo("Hello, World!");

        greeting = ClientBuilder.newClient().target(UriBuilder.fromUri("stork:
                .get(String.class);
        assertThat(greeting).isEqualTo("Hello, World!");

        greeting = ClientBuilder.newClient().target("stork:
                .get(String.class);
        assertThat(greeting).isEqualTo("Hello, big bird");
    }
Code review comment: The only thing I ask you @mkouba  to think about is that in logging, when receiving null in the handler, to send to the log and `Thread.currentThread().getStackTrace()` so that you can roughly understand which extension had an error. Please think about it and let me know

Code under review:
public StartupContext() {
        ShutdownContext shutdownContext = new ShutdownContext() {
            @Override
            public void addShutdownTask(Runnable runnable) {
                if (Objects.nonNull(runnable)) {
                    shutdownTasks.addFirst(runnable);
                } else  {
                    LOG.warn("Shutdown task turned out to be null!");
                }
            }

            @Override
            public void addLastShutdownTask(Runnable runnable) {
                if (Objects.nonNull(runnable)) {
                    lastShutdownTasks.addFirst(runnable);
                } else {
                    LOG.warn("Last shutdown task turned out to be null!");
                }
            }
        };
        values.put(ShutdownContext.class.getName(), shutdownContext);
        values.put(RAW_COMMAND_LINE_ARGS, new Supplier<String[]>() {
            @Override
            public String[] get() {
                if (commandLineArgs == null) {
                    throw new RuntimeException("Command line arguments not available during static init");
                }
                return commandLineArgs;
            }
        });
    }

Line commented on: if (Objects.nonNull(runnable)) {

Revised code:
public StartupContext() {
        ShutdownContext shutdownContext = new ShutdownContext() {
            @Override
            public void addShutdownTask(Runnable runnable) {
                if (runnable != null) {
                    shutdownTasks.addFirst(runnable);
                } else {
                    throw new IllegalArgumentException("Extension passed an invalid shutdown handler");
                }
            }

            @Override
            public void addLastShutdownTask(Runnable runnable) {
                if (runnable != null) {
                    lastShutdownTasks.addFirst(runnable);
                } else {
                    throw new IllegalArgumentException("Extension passed an invalid last shutdown handler");
                }
            }
        };
        values.put(ShutdownContext.class.getName(), shutdownContext);
        values.put(RAW_COMMAND_LINE_ARGS, new Supplier<String[]>() {
            @Override
            public String[] get() {
                if (commandLineArgs == null) {
                    throw new RuntimeException("Command line arguments not available during static init");
                }
                return commandLineArgs;
            }
        });
    }
Code review comment: The builder methods can be chained instead. ```java ServiceBusProcessorClient processor = new ServiceBusClientBuilder()             .connectionString(connectionString)             .processor()             .queueName(queueName)             .processMessage(System.out::println)             .processError(context -> System.err.println(context.getErrorSource()))             .buildProcessorClient();  ```

Code under review:
public void instantiateProcessor() {
        
        
        ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
            .connectionString(connectionString);
        ServiceBusProcessorClient processor = builder
            .processor()
            .queueName(queueName)
            .processMessage(System.out::println)
            .processError(context -> System.err.println(context.getErrorSource()))
            .buildProcessorClient();
        
        processor.start();
        processor.stop();
    }

Line commented on: ServiceBusProcessorClient processor = builder

Revised code:
public void instantiateProcessor() {
        
        
        ServiceBusClientBuilder builder = new ServiceBusClientBuilder()
            .connectionString(connectionString);
        ServiceBusProcessorClient processor = builder
            .processor()
            .queueName(queueName)
            .processMessage(System.out::println)
            .processError(context -> System.err.println(context.getErrorSource()))
            .buildProcessorClient();
        
        processor.start();
        processor.stop();
    }
Code review comment: Why cannot change the parallelism of a job running in reactive mode

Code under review:
public static RestHandlerConfiguration fromConfiguration(Configuration configuration) {
        final long refreshInterval = configuration.getLong(WebOptions.REFRESH_INTERVAL);

        final int maxCheckpointStatisticCacheEntries =
                configuration.getInteger(WebOptions.CHECKPOINTS_HISTORY_SIZE);

        final Time timeout = Time.milliseconds(configuration.getLong(WebOptions.TIMEOUT));

        final String rootDir = "flink-web-ui";
        final File webUiDir = new File(configuration.getString(WebOptions.TMP_DIR), rootDir);

        final boolean webSubmitEnabled = configuration.getBoolean(WebOptions.SUBMIT_ENABLE);
        final boolean webCancelEnabled = configuration.getBoolean(WebOptions.CANCEL_ENABLE);
        final boolean webRescaleSupported =
                ClusterOptions.isAdaptiveSchedulerEnabled(configuration)
                        && !ClusterOptions.isReactiveModeEnabled(configuration);
        final boolean webRescaleEnabled =
                webRescaleSupported && configuration.getBoolean(WebOptions.RESCALE_ENABLE);

        return new RestHandlerConfiguration(
                refreshInterval,
                maxCheckpointStatisticCacheEntries,
                timeout,
                webUiDir,
                webSubmitEnabled,
                webCancelEnabled,
                webRescaleEnabled);
    }

Line commented on: && !ClusterOptions.isReactiveModeEnabled(configuration);

Revised code:
public static RestHandlerConfiguration fromConfiguration(Configuration configuration) {
        final long refreshInterval = configuration.getLong(WebOptions.REFRESH_INTERVAL);

        final int maxCheckpointStatisticCacheEntries =
                configuration.getInteger(WebOptions.CHECKPOINTS_HISTORY_SIZE);

        final Time timeout = Time.milliseconds(configuration.getLong(WebOptions.TIMEOUT));

        final String rootDir = "flink-web-ui";
        final File webUiDir = new File(configuration.getString(WebOptions.TMP_DIR), rootDir);

        final boolean webSubmitEnabled = configuration.getBoolean(WebOptions.SUBMIT_ENABLE);
        final boolean webCancelEnabled = configuration.getBoolean(WebOptions.CANCEL_ENABLE);
        final boolean webRescaleSupported =
                ClusterOptions.isAdaptiveSchedulerEnabled(configuration)
                        && !ClusterOptions.isReactiveModeEnabled(configuration);
        final boolean webRescaleEnabled =
                webRescaleSupported && configuration.getBoolean(WebOptions.RESCALE_ENABLE);

        return new RestHandlerConfiguration(
                refreshInterval,
                maxCheckpointStatisticCacheEntries,
                timeout,
                webUiDir,
                webSubmitEnabled,
                webCancelEnabled,
                webRescaleEnabled);
    }
Code review comment: Okay, thanks for the hint. Changed

Code under review:
void assertFind() {
        ShardingRuleConfiguration ruleConfig = new ShardingRuleConfiguration();
        
        ShardingTableRuleConfiguration shardingTableRuleConfiguration = getShardingTableRuleConfiguration();
        Map<String, AlgorithmConfiguration> allAlgorithms = getAlgorithms();
        
        ruleConfig.getTables().add(shardingTableRuleConfiguration);
        ruleConfig.getShardingAlgorithms().putAll(allAlgorithms);
        ruleConfig.setDefaultDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("order_id", USED_DATABASE_SHARDING_DEFAULT_ALGORITHM));
        ruleConfig.setDefaultTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", USED_TABLE_SHARDING_DEFAULT_ALGORITHM));
        
        Collection<String> unusedAlgorithmsCollection = UnusedAlgorithmFinder.find(ruleConfig);
        
        assertNotNull(unusedAlgorithmsCollection);
        assertThat(unusedAlgorithmsCollection.size(), is(1));
        assertTrue(unusedAlgorithmsCollection.contains(UNUSED_ALGORITHM));
    }

Line commented on: Map<String, AlgorithmConfiguration> allAlgorithms = getAlgorithms();

Revised code:
void assertFind() {
        ShardingRuleConfiguration ruleConfig = new ShardingRuleConfiguration();
        ShardingTableRuleConfiguration shardingTableRuleConfig = getShardingTableRuleConfiguration();
        ruleConfig.getTables().add(shardingTableRuleConfig);
        ruleConfig.getShardingAlgorithms().putAll(getAlgorithms());
        ruleConfig.setDefaultDatabaseShardingStrategy(new StandardShardingStrategyConfiguration("order_id", USED_DATABASE_SHARDING_DEFAULT_ALGORITHM));
        ruleConfig.setDefaultTableShardingStrategy(new StandardShardingStrategyConfiguration("order_id", USED_TABLE_SHARDING_DEFAULT_ALGORITHM));
        Collection<String> actual = UnusedAlgorithmFinder.find(ruleConfig);
        assertNotNull(actual);
        assertThat(actual.size(), is(1));
        assertTrue(actual.contains(UNUSED_ALGORITHM));
    }
Code review comment: Can we combine queries with `;`? E.g.:  ```java BeamSqlLine.testMain(   new String[] {     "-e",     "CREATE TABLE table_test (col_a VARCHAR, col_b VARCHAR) TYPE 'test'; \n"     + "INSERT INTO table_test SELECT '3', 'foo'; \n"     + "INSERT INTO table_test SELECT '3', 'bar'; \n"     + "SELECT col_a, count(*) FROM table_test GROUP BY col_a;" }); ```

Code under review:
public void testSqlLine_GroupBy() throws Exception {
    BeamSqlLine.testMain(
        new String[] {
          "-e",
          "CREATE TABLE table_test (col_a VARCHAR, col_b VARCHAR) TYPE 'test';",
          "-e",
          "INSERT INTO table_test SELECT '3', 'foo';",
          "-e",
          "INSERT INTO table_test SELECT '3', 'bar';",
          "-e",
          "INSERT INTO table_test SELECT '4', 'foo';",
          "-e",
          "SELECT col_a, count(*) FROM table_test GROUP BY col_a;"
        },
        new PrintStream(byteArrayOutputStream));

    
    verifyStringOutputTrue(byteArrayOutputStream.toString(), "3", "2");
    
    verifyStringOutputTrue(byteArrayOutputStream.toString(), "4", "1");
  }

Line commented on: "INSERT INTO table_test SELECT '4', 'foo';",

Revised code:
public void testSqlLine_GroupBy() throws Exception {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    String[] args =
        buildArgs(
            "CREATE TABLE table_test (col_a VARCHAR, col_b VARCHAR) TYPE 'test';",
            "INSERT INTO table_test SELECT '3', 'foo';",
            "INSERT INTO table_test SELECT '3', 'bar';",
            "INSERT INTO table_test SELECT '4', 'foo';",
            "SELECT col_a, count(*) FROM table_test GROUP BY col_a;");

    BeamSqlLine.runSqlLine(args, null, byteArrayOutputStream, null);

    List<List<String>> lines = toLines(byteArrayOutputStream);
    assertThat(
        Arrays.asList(Arrays.asList("3", "2"), Arrays.asList("4", "1")),
        everyItem(IsIn.isOneOf(lines.toArray())));
  }
Code review comment: I don't think so. If the key is available locally and is valid the client will always try to perform the operation locally. Might want to change that behavior to what you suggested in a future PR.

Code under review:
private void unpackAndValidateId(String keyId) {
        if (CoreUtils.isNullOrEmpty(keyId)) {
            throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
        }

        try {
            URL url = new URL(keyId);
            String[] tokens = url.getPath().split("/");
            String endpoint = url.getProtocol() + ":
            String keyName = (tokens.length >= 3 ? tokens[2] : null);
            String version = (tokens.length >= 4 ? tokens[3] : null);
            this.keyCollection = (tokens.length >= 2 ? tokens[1] : null);

            if (Strings.isNullOrEmpty(endpoint)) {
                throw logger.logExceptionAsError(
                    new IllegalArgumentException("Key endpoint in key identifier is invalid."));
            } else if (Strings.isNullOrEmpty(keyName)) {
                throw logger.logExceptionAsError(
                    new IllegalArgumentException("Key name in key identifier is invalid."));
            } else if (Strings.isNullOrEmpty(version)) {
                throw logger.logExceptionAsError(
                    new IllegalArgumentException("Key version in key identifier is invalid."));
            }
        } catch (MalformedURLException e) {
            throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e));
        }
    }

Line commented on: throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e));

Revised code:
private void unpackAndValidateId(String keyId) {
        if (CoreUtils.isNullOrEmpty(keyId)) {
            throw logger.logExceptionAsError(new IllegalArgumentException("Key Id is invalid"));
        }

        try {
            URL url = new URL(keyId);
            String[] tokens = url.getPath().split("/");
            String endpoint = url.getProtocol() + ":
            String keyName = (tokens.length >= 3 ? tokens[2] : null);
            String version = (tokens.length >= 4 ? tokens[3] : null);
            this.keyCollection = (tokens.length >= 2 ? tokens[1] : null);

            if (Strings.isNullOrEmpty(endpoint)) {
                throw logger.logExceptionAsError(
                    new IllegalArgumentException("Key endpoint in key identifier is invalid."));
            } else if (Strings.isNullOrEmpty(keyName)) {
                throw logger.logExceptionAsError(
                    new IllegalArgumentException("Key name in key identifier is invalid."));
            } else if (Strings.isNullOrEmpty(version)) {
                throw logger.logExceptionAsError(
                    new IllegalArgumentException("Key version in key identifier is invalid."));
            }
        } catch (MalformedURLException e) {
            throw logger.logExceptionAsError(new IllegalArgumentException("The key identifier is malformed.", e));
        }
    }
Code review comment: Updated.  I kept the first %s for now.

Code under review:
public ExpressionChecker addExpr(String expression, Object expectedValue) {
      TypeName resultTypeName = JAVA_CLASS_TO_TYPENAME.get(expectedValue.getClass());
      checkArgument(
          resultTypeName != null,
          String.format(
              "The type of the expected object '%s' is unknown in 'addExpr(String %s, Object %s)'"
                  + " . Please use 'addExpr(String expr, Object expected, "
                  + "FieldType type)' instead and provide the type of the expected object",
              expectedValue, expression, expectedValue));
      addExpr(expression, expectedValue, FieldType.of(resultTypeName));
      return this;
    }

Line commented on: "The type of the expected object '%s' is unknown in 'addExpr(String %s, Object %s)'"

Revised code:
public ExpressionChecker addExpr(String expression, Object expectedValue) {
      TypeName resultTypeName = JAVA_CLASS_TO_TYPENAME.get(expectedValue.getClass());
      checkArgument(
          resultTypeName != null,
          String.format(
              "The type of the expected value '%s' is unknown in 'addExpr(String expression, "
                  + "Object expectedValue)'. Please use 'addExpr(String expr, Object expected, "
                  + "FieldType type)' instead and provide the type of the expected object",
              expectedValue));
      addExpr(expression, expectedValue, FieldType.of(resultTypeName));
      return this;
    }
Code review comment: This still needs to be addressed.

Code under review:
private static Long getExpiresJwtClaim(String accessToken) {
        String[] parts = accessToken.split("\\.");
        if (parts.length == 3) {
            try {
                JsonObject claims = new JsonObject(new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8));
                return claims.getLong(Claims.exp.name());
            } catch (IllegalArgumentException ex) {
                return null;
            }
        }
        return null;
    }

Line commented on: try {

Revised code:
private static Long getExpiresJwtClaim(String accessToken) {
        JsonObject claims = decodeJwtToken(accessToken);
        if (claims != null) {
            try {
                return claims.getLong(Claims.exp.name());
            } catch (IllegalArgumentException ex) {
                LOG.debug("JWT expiry claim can not be converted to Long");
            }
        }
        return null;
    }
Code review comment: Add a comment here to explain that this is the special case where we split after removing the root of a path that is just the root.

Code under review:
private String[] splitToElements(String str) {
        String[] arr = str.split(this.parentFileSystem.getSeparator());
        if (arr.length == 1 && arr[0].isEmpty()) {
            return new String[0];
        }
        return arr;
    }

Line commented on: if (arr.length == 1 && arr[0].isEmpty()) {

Revised code:
private String[] splitToElements(String str) {
        String[] arr = str.split(this.parentFileSystem.getSeparator());
        /*
        This is a special case where we split after removing the root from a path that is just the root. Or otherwise
        have an empty path.
         */
        if (arr.length == 1 && arr[0].isEmpty()) {
            return new String[0];
        }
        return arr;
    }