muttakin2301/ccr2000 huggingface dataset:
Code review comment: unnecessary. a local static field is better.

Code under review:
public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
        final String path = key + "/";
        if (!caches.containsKey(path)) {
            addCacheData(key);
        }
        TreeCache cache = caches.get(path);
        cache.getListenable().addListener((client, event) -> {
            ChildData data = event.getData();
            if (null == data || null == data.getPath()) {
                return;
            }
            DataChangedEvent.ChangedType changedType = getChangedType(event);
            if (DataChangedEvent.ChangedType.IGNORED != changedType) {
                dataChangedEventListener.onChange(new DataChangedEvent(data.getPath(), null == data.getData() ? null : new String(data.getData(), StandardCharsets.UTF_8), changedType));
            }
        });
    }

Line commented on: dataChangedEventListener.onChange(new DataChangedEvent(data.getPath(), null == data.getData() ? null : new String(data.getData(), StandardCharsets.UTF_8), changedType));

Revised code:
public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
        final String path = key + "/";
        if (!caches.containsKey(path)) {
            addCacheData(key);
        }
        TreeCache cache = caches.get(path);
        cache.getListenable().addListener((client, event) -> {
            ChildData data = event.getData();
            if (null == data || null == data.getPath()) {
                return;
            }
            DataChangedEvent.ChangedType changedType = getChangedType(event);
            if (DataChangedEvent.ChangedType.IGNORED != changedType) {
                dataChangedEventListener.onChange(new DataChangedEvent(data.getPath(), null == data.getData() ? null : new String(data.getData(), Charsets.UTF_8), changedType));
            }
        });
    }
Code review comment: We can use `module.moduleName()` which will work for both default and non-default module.

Code under review:
private String normalizeFileName(String fileName) {
        String orgName = IdentifierUtils.encodeNonFunctionIdentifier(
                this.module.packageInstance().packageOrg().toString());
        
        for (Module module : this.module.packageInstance().modules()) {
            String sourceRoot;
            String packageName;
            if (module.isDefaultModule()) {
                packageName = IdentifierUtils.encodeNonFunctionIdentifier(
                        module.packageInstance().packageName().toString());
                sourceRoot = module.project().sourceRoot().getFileName().toString();
            } else {
                packageName = IdentifierUtils.encodeNonFunctionIdentifier(module.descriptor().name().toString());
                sourceRoot = module.project().sourceRoot().getFileName().toString() + "/modules/" +
                        module.moduleName().moduleNamePart();
            }
            if (fileName.contains(orgName + "/" + packageName + "/")) {
                
                orgName = Pattern.quote(orgName);
                packageName = Pattern.quote(packageName);
                
                
                String normalizedFileName = fileName.replaceAll("^" + orgName + "/" +
                        packageName + "/.*/", sourceRoot + "/");
                
                
                normalizedFileName = normalizedFileName.replaceAll("^" + orgName + "/" +
                        packageName + "/.*", sourceRoot);
                return normalizedFileName;
            }
        }
        return fileName;
    }

Line commented on: module.packageInstance().packageName().toString());

Revised code:
private String normalizeFileName(String fileName) {
        String orgName = IdentifierUtils.encodeNonFunctionIdentifier(
                this.module.packageInstance().packageOrg().toString());
        
        for (Module module : this.module.packageInstance().modules()) {
            String packageName = IdentifierUtils.encodeNonFunctionIdentifier(
                    module.moduleName().toString());
            String sourceRoot = module.project().sourceRoot().getFileName().toString();
            if (!module.isDefaultModule()) {
                sourceRoot = sourceRoot + "/" + ProjectConstants.MODULES_ROOT + "/" +
                        module.moduleName().moduleNamePart();
            }
            if (fileName.contains(orgName + "/" + packageName + "/")) {
                
                orgName = Pattern.quote(orgName);
                packageName = Pattern.quote(packageName);
                
                
                String normalizedFileName = fileName.replaceAll("^" + orgName + "/" +
                        packageName + "/.*/", sourceRoot + "/");
                
                
                normalizedFileName = normalizedFileName.replaceAll("^" + orgName + "/" +
                        packageName + "/.*", sourceRoot);
                return normalizedFileName;
            }
        }
        return fileName;
    }
Code review comment: Complicated how? It's just iterating over the headers and building up a String. How is that more complicated than was was being done with lambdas?

Code under review:
private String asString(MultiMap headers) {
        if (headers.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder((headers.size() * (6 + 1 + 6)) + (headers.size() - 1)); 
        boolean isFirst = true;
        for (Map.Entry<String, String> entry : headers) {
            if (isFirst) {
                isFirst = false;
            } else {
                sb.append(' ');
            }
            sb.append(entry.getKey()).append('=').append(entry.getValue());
        }
        return sb.toString();
    }

Line commented on: StringBuilder sb = new StringBuilder((headers.size() * (6 + 1 + 6)) + (headers.size() - 1));

Revised code:
private String asString(MultiMap headers) {
        if (headers.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder((headers.size() * (6 + 1 + 6)) + (headers.size() - 1)); 
        boolean isFirst = true;
        for (Map.Entry<String, String> entry : headers) {
            if (isFirst) {
                isFirst = false;
            } else {
                sb.append(' ');
            }
            sb.append(entry.getKey()).append('=').append(entry.getValue());
        }
        return sb.toString();
    }
Code review comment: There was a change to make resource methods public and because of that, this warning appeared for service-decl. But from the client side, we only need to consider the shape of the parameters of resource methods, not the actual type. Therefore it is decided to disallow this warning only for service-decl. We need this warning to client-decl.

Code under review:
private boolean isMethodInServiceDeclaration(BLangFunction func) {
        BLangNode parent = func.parent;
        return parent.getKind() == NodeKind.CLASS_DEFN && ((BLangClassDefinition) parent).isServiceDecl;
    }

Line commented on: return parent.getKind() == NodeKind.CLASS_DEFN && ((BLangClassDefinition) parent).isServiceDecl;

Revised code:
private boolean isMethodInServiceDeclaration(BLangFunction func) {
        BLangNode parent = func.parent;
        return parent.getKind() == NodeKind.CLASS_DEFN &&
                Symbols.isFlagOn(((BLangClassDefinition) parent).symbol.flags, Flags.SERVICE);
    }
Code review comment: ```suggestion         try (ResultSet tableSet = connection.getMetaData().getTables(catalogSchema, null, partitionInfoTable, null)) { ```

Code under review:
public boolean checkAndSetSupportPartitionInformation(Connection connection) {
        String catalogSchema = "information_schema";
        String partitionInfoTable = "partitions";
        try (ResultSet tableSet = connection.getMetaData().getTables(catalogSchema, null, null, null)) {
            while (tableSet.next()) {
                String tableName = tableSet.getString("TABLE_NAME");
                if (tableName.equalsIgnoreCase(partitionInfoTable)) {
                    return this.supportPartitionInformation = true;
                }
            }
        } catch (SQLException e) {
            throw new StarRocksConnectorException(e.getMessage());
        }
        return this.supportPartitionInformation = false;
    }

Line commented on: try (ResultSet tableSet = connection.getMetaData().getTables(catalogSchema, null, null, null)) {

Revised code:
public boolean checkAndSetSupportPartitionInformation(Connection connection) {
        String catalogSchema = "information_schema";
        String partitionInfoTable = "partitions";
        
        
        try (ResultSet catalogSet = connection.getMetaData().getCatalogs()) {
            while (catalogSet.next()) {
                String schemaName = catalogSet.getString("TABLE_CAT");
                if (schemaName.equalsIgnoreCase(catalogSchema)) {
                    try (ResultSet tableSet = connection.getMetaData().getTables(catalogSchema, null, null, null)) {
                        while (tableSet.next()) {
                            String tableName = tableSet.getString("TABLE_NAME");
                            if (tableName.equalsIgnoreCase(partitionInfoTable)) {
                                return this.supportPartitionInformation = true;
                            }
                        }
                    }
                }
            }
        } catch (SQLException e) {
            throw new StarRocksConnectorException(e.getMessage());
        }
        return this.supportPartitionInformation = false;
    }
Code review comment: ```suggestion             throw new AnalysisException("Multi partition time interval mush be larger than zero."); ```

Code under review:
private void timeIntervalTrans() throws AnalysisException {
        this.timeInterval = partitionKeyDesc.getTimeInterval();
        String timeType = partitionKeyDesc.getTimeType();
        if (timeType == null) {
            throw new AnalysisException("Unknown time interval type for Multi build partition.");
        }
        if (this.timeInterval <= 0) {
            throw new AnalysisException("Multi partition every clause mush be larger than zero.");
        }
        try {
            this.timeUnitType = TimestampArithmeticExpr.TimeUnit.valueOf(timeType);
        } catch (Exception e) {
            throw new AnalysisException("Multi build partition got an unknow time interval type: "
                    + timeType);
        }
        if (!timeUnitTypeMultiPartition.contains(this.timeUnitType)) {
            throw new AnalysisException("Multi build partition does not support time interval type: "
                    + this.timeUnitType);
        }
    }

Line commented on: throw new AnalysisException("Multi partition every clause mush be larger than zero.");

Revised code:
private void timeIntervalTrans() throws AnalysisException {
        this.timeInterval = partitionKeyDesc.getTimeInterval();
        String timeType = partitionKeyDesc.getTimeType();
        if (timeType == null) {
            throw new AnalysisException("Unknown time interval type for Multi build partition.");
        }
        if (this.timeInterval <= 0) {
            throw new AnalysisException("Multi partition time interval mush be larger than zero.");
        }
        try {
            this.timeUnitType = TimestampArithmeticExpr.TimeUnit.valueOf(timeType);
        } catch (Exception e) {
            throw new AnalysisException("Multi build partition got an unknow time interval type: "
                    + timeType);
        }
        if (!timeUnitTypeMultiPartition.contains(this.timeUnitType)) {
            throw new AnalysisException("Multi build partition does not support time interval type: "
                    + this.timeUnitType);
        }
    }
Code review comment: my reasoning on why this was a no-op: - the scoped metric containers stuffs in thread-local and delegating counter pulls it out - the scoping is not transitive, only the last scope matters - we are now caching the unboundedMetricContainer.getCounter() result instead of recalculating it every accept.  However the contaner appears to reset counters but not remove them.  I was hoping existing tests would cover correctness since I'm not familiar with this code.  @kileys can you take a look? Thanks

Code under review:
public void accept(WindowedValue<T> input) throws Exception {
      
      this.unboundedElementCountCounter.inc(input.getWindows().size());
      
      this.unboundSampledByteSizeDistribution.tryUpdate(input.getValue(), this.coder);
      
      
      
      
      MetricsContainerImpl container = metricsContainerRegistry.getContainer(pTransformId);
      try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(container)) {
        try (Closeable trackerCloseable = stateTracker.enterState(state)) {
          this.delegate.accept(input);
        }
      }
    }

Line commented on: this.unboundedElementCountCounter.inc(input.getWindows().size());

Revised code:
public void accept(WindowedValue<T> input) throws Exception {
      
      this.unboundedElementCountCounter.inc(input.getWindows().size());
      
      this.unboundSampledByteSizeDistribution.tryUpdate(input.getValue(), this.coder);
      
      
      
      
      MetricsContainerImpl container = metricsContainerRegistry.getContainer(pTransformId);
      try (Closeable closeable = MetricsEnvironment.scopedMetricsContainer(container)) {
        try (Closeable trackerCloseable = stateTracker.enterState(state)) {
          this.delegate.accept(input);
        }
      }
    }
Code review comment: Will we meet any multi-thread issue here?

Code under review:
public void unregisterFunctionResources(List<ResourceUri> resourceUris) {
        if (!resourceUris.isEmpty()) {
            resourceUris.forEach(
                    uri -> {
                        ResourceCounter counter = functionResourceInfos.get(uri);
                        if (counter != null && counter.decreaseCounter()) {
                            functionResourceInfos.remove(uri);
                        }
                    });
        }
    }

Line commented on: functionResourceInfos.remove(uri);

Revised code:
public void unregisterFunctionResources(List<ResourceUri> resourceUris) {
        if (!resourceUris.isEmpty()) {
            resourceUris.forEach(
                    uri -> {
                        ResourceCounter counter = functionResourceInfos.get(uri);
                        if (counter != null && counter.decreaseCounter()) {
                            functionResourceInfos.remove(uri);
                        }
                    });
        }
    }
Code review comment: Do we want this option to be purely for the UI or also for the REST API as a whole? If the latter, then we could also disable the requirement handlers directly in the endpoint.

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 =
                JobManagerOptions.SchedulerType.Adaptive.equals(
                                configuration.get(JobManagerOptions.SCHEDULER))
                        && configuration.get(JobManagerOptions.SCHEDULER_MODE) == null;
        final boolean webRescaleEnabled =
                webRescaleSupported && configuration.getBoolean(WebOptions.RESCALE_ENABLE);

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

Line commented on: && configuration.get(JobManagerOptions.SCHEDULER_MODE) == null;

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: Can't we merge the two if conditions?  Also I think the exception should be thrown in the else block of that if condition. This error should be more specific such that it indicates that the problem is passing an array of a type other than byte.  Also, can we add a negative test to verify this exception is thrown appropriately?

Code under review:
public static String getSQLType(BType value) {
        int tag = value.getTag();
        switch (tag) {
        case TypeTags.INT_TAG:
            return Constants.SQLDataTypes.BIGINT;
        case TypeTags.STRING_TAG:
            return Constants.SQLDataTypes.VARCHAR;
        case TypeTags.FLOAT_TAG:
            return Constants.SQLDataTypes.DOUBLE;
        case TypeTags.BOOLEAN_TAG:
            return Constants.SQLDataTypes.BOOLEAN;
        case TypeTags.DECIMAL_TAG:
            return Constants.SQLDataTypes.DECIMAL;
        case TypeTags.ARRAY_TAG:
            if (value instanceof BArrayType) {
                if (((BArrayType) value).getElementType().getTag() == TypeTags.BYTE_TAG) {
                    return Constants.SQLDataTypes.BINARY;
                }
            }
            throw new BallerinaException("unsupported data type as direct value for sql operation, " +
                    "use sql:Parameter: " + value.getName());
        default:
            throw new BallerinaException(
                    "unsupported data type as direct value for sql operation, use sql:Parameter: " + value.getName());
        }
    }

Line commented on: if (((BArrayType) value).getElementType().getTag() == TypeTags.BYTE_TAG) {

Revised code:
public static String getSQLType(BType value) {
        int tag = value.getTag();
        switch (tag) {
        case TypeTags.INT_TAG:
            return Constants.SQLDataTypes.BIGINT;
        case TypeTags.STRING_TAG:
            return Constants.SQLDataTypes.VARCHAR;
        case TypeTags.FLOAT_TAG:
            return Constants.SQLDataTypes.DOUBLE;
        case TypeTags.BOOLEAN_TAG:
            return Constants.SQLDataTypes.BOOLEAN;
        case TypeTags.DECIMAL_TAG:
            return Constants.SQLDataTypes.DECIMAL;
        case TypeTags.ARRAY_TAG:
            if (((BArrayType) value).getElementType().getTag() == TypeTags.BYTE_TAG) {
                return Constants.SQLDataTypes.BINARY;
            } else {
                throw new BallerinaException("Array data type as direct value is supported only " +
                        "with byte type elements, use sql:Parameter " + value.getName());
            }
        default:
            throw new BallerinaException(
                    "unsupported data type as direct value for sql operation, use sql:Parameter: " + value.getName());
        }
    }
Code review comment: Where is the the RuntimeException being thrown from? I'm surprised that the `withContext(…)` or underlying RestProxy isn't bubbling this to downstream.

Code under review:
public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
        try {
            return withContext(context -> addSetting(setting, context))
                .flatMap(response -> Mono.justOrEmpty(response.getValue()));
        } catch (RuntimeException ex) {
            return Mono.error(logger.logExceptionAsError(Exceptions.propagate(ex)));
        }
    }

Line commented on: try {

Revised code:
public Mono<ConfigurationSetting> addSetting(ConfigurationSetting setting) {
        try {
            return withContext(context -> addSetting(setting, context))
                .flatMap(response -> Mono.justOrEmpty(response.getValue()));
        } catch (RuntimeException ex) {
            return monoError(logger, ex);
        }
    }
Code review comment: If we change default value we would also need to change meaning/name of the variables - I can do it but really do not see where the problem is?

Code under review:
public static boolean isIdValueValidationEnabled() {
        String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS);
        if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) {
            return !Boolean.valueOf(valueFromSystemProperty);
        }

        String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE);
        if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) {
            return!Boolean.valueOf(valueFromEnvVariable);
        }

        return !DEFAULT_PREVENT_INVALID_ID_CHARS;
    }

Line commented on: return !DEFAULT_PREVENT_INVALID_ID_CHARS;

Revised code:
public static boolean isIdValueValidationEnabled() {
        String valueFromSystemProperty = System.getProperty(PREVENT_INVALID_ID_CHARS);
        if (valueFromSystemProperty != null && !valueFromSystemProperty.isEmpty()) {
            return !Boolean.valueOf(valueFromSystemProperty);
        }

        String valueFromEnvVariable = System.getenv(PREVENT_INVALID_ID_CHARS_VARIABLE);
        if (valueFromEnvVariable != null && !valueFromEnvVariable.isEmpty()) {
            return!Boolean.valueOf(valueFromEnvVariable);
        }

        return DEFAULT_PREVENT_INVALID_ID_CHARS;
    }
Code review comment: I guess we can skip this call to `getLength()` and keep a running sum of the length in the for loop below and if the sum exceeds the max array size, throw an exception. We don't have to go through the list of all byte buffers twice.

Code under review:
private byte[] getBytes() {
        long length = getLength();
        if (length > MAX_ARRAY_SIZE) {
            throw LOGGER.logExceptionAsError(new IllegalStateException(TOO_LARGE_FOR_BYTE_ARRAY + length));
        }

        byte[] bytes = new byte[(int) length];
        int offset = 0;

        for (ByteBuffer bb : content) {
            bb = bb.duplicate();
            int count = bb.remaining();
            bb.get(bytes, offset, count);
            offset += count;
        }

        return bytes;
    }

Line commented on: long length = getLength();

Revised code:
private byte[] getBytes() {
        long length = getLength();
        if (length > MAX_ARRAY_SIZE) {
            throw LOGGER.logExceptionAsError(new IllegalStateException(TOO_LARGE_FOR_BYTE_ARRAY + length));
        }

        byte[] bytes = new byte[(int) length];
        int offset = 0;

        for (ByteBuffer bb : content) {
            bb = bb.duplicate();
            int count = bb.remaining();
            bb.get(bytes, offset, count);
            offset += count;
        }

        return bytes;
    }
Code review comment: I wouldn't add a constructor like this, this can cause problems with serialization as Autorest won't know about this and could/will generate assuming this class uses an empty constructor.

Code under review:
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
        classCustomization.getMethod("setLabel")
            .getJavadoc()
            .setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.")
            .setReturn("the {@link KeyValueFilter} object itself.");
        classCustomization.getMethod("getKey")
            .getJavadoc()
            .setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
        classCustomization.getMethod("getLabel")
            .getJavadoc()
            .setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");

        classCustomization = classCustomization.customizeAst(
            ast -> ast.getClassByName("KeyValueFilter")
                       .get()
                       .getDefaultConstructor().get()
                       .remove())
                                 .removeMethod("setKey")
                                 .rename("SnapshotSettingFilter");

        classCustomization.addConstructor(joinWithNewline(
            "public SnapshotSettingFilter(String key) {",
            "   this.key = key;",
            "}"))
            .getJavadoc()
            .setDescription("Constructor of {@link SnapshotSettingFilter}.")
            .setParam("key", "The key value to set.");
    }

Line commented on: "public SnapshotSettingFilter(String key) {",

Revised code:
private void customizeKeyValueFilter(ClassCustomization classCustomization) {
        
        classCustomization.getMethod("setLabel")
            .getJavadoc()
            .setDescription("Set the label property: Filters {@link ConfigurationSetting} by their label field.");
        
        classCustomization.getMethod("getKey")
            .getJavadoc()
            .setDescription("Get the key property: Filters {@link ConfigurationSetting} by their key field.");
        
        classCustomization.getMethod("getLabel")
            .getJavadoc()
            .setDescription("Get the label property: Filters {@link ConfigurationSetting} by their label field.");
        classCustomization.getConstructor("SnapshotSettingFilter")
            .removeAnnotation("JsonCreator");
    }
Code review comment: You need to implement logic like: ShowUserPropertyStmt.analyze()

Code under review:
public Void visitShowUserPropertyStmt(ShowUserPropertyStmt statement, ConnectContext session) {
            return null;
        }

Line commented on: return null;

Revised code:
public Void visitShowUserPropertyStmt(ShowUserPropertyStmt statement, ConnectContext session) {
            ShowUserPropertyAnalyzer.analyze(statement, session);
            return null;
        }
Code review comment: Ok, I'll change it accordingly ...

Code under review:
private static void setAddressResolverOptions(VertxConfiguration conf, VertxOptions options) {
        AddressResolverConfiguration ar = conf.resolver;
        AddressResolverOptions opts = new AddressResolverOptions();
        ar.cacheMaxTimeToLive.ifPresent(opts::setCacheMaxTimeToLive);
        ar.cacheMinTimeToLive.ifPresent(opts::setCacheMinTimeToLive);
        ar.cacheNegativeTimeToLive.ifPresent(opts::setCacheNegativeTimeToLive);

        options.setAddressResolverOptions(opts);
    }

Line commented on: ar.cacheNegativeTimeToLive.ifPresent(opts::setCacheNegativeTimeToLive);

Revised code:
private static void setAddressResolverOptions(VertxConfiguration conf, VertxOptions options) {
        AddressResolverConfiguration ar = conf.resolver;
        AddressResolverOptions opts = new AddressResolverOptions();
        opts.setCacheMaxTimeToLive(ar.cacheMaxTimeToLive);
        opts.setCacheMinTimeToLive(ar.cacheMinTimeToLive);
        opts.setCacheNegativeTimeToLive(ar.cacheNegativeTimeToLive);

        options.setAddressResolverOptions(opts);
    }
Code review comment: There are typos in this error message.  It should be "Error occurred while retrieving query params from connection: ".

Code under review:
public BValue[] execute(Context context) {
        try {
            return WebSocketUtil.getQueryParam(context, this);
        } catch (Throwable e) {
            throw new BallerinaException("Error while retrieving query param from Connection: " + e.getMessage());
        }
    }

Line commented on: throw new BallerinaException("Error while retrieving query param from Connection: " + e.getMessage());

Revised code:
public BValue[] execute(Context context) {
        try {
            return WebSocketUtil.getQueryParams(context, this);
        } catch (Throwable e) {
            throw new BallerinaException(
                    "Error occurred while retrieving query parameters from Connection: " + e.getMessage());
        }
    }
Code review comment: You should rather create and cache an `Event` object for perf reasons, i.e. `Event<SecurityEvent> event = Arc.container().beanManager().getEvent().select(SecurityEvent.class)` and then `event.fire(...)`.

Code under review:
private void fireEvent(SecurityEvent.Type eventType, SecurityIdentity securityIdentity) {
        if (resolver.isSecurityEventObserved()) {
            Arc.container().beanManager().fireEvent(new SecurityEvent(eventType, securityIdentity));
        }
    }

Line commented on: Arc.container().beanManager().fireEvent(new SecurityEvent(eventType, securityIdentity));

Revised code:
private void fireEvent(SecurityEvent.Type eventType, SecurityIdentity securityIdentity) {
        if (resolver.isSecurityEventObserved()) {
            resolver.getSecurityEvent().fire(new SecurityEvent(eventType, securityIdentity));
        }
    }
Code review comment: Sorry, we can't due to internal requirements.

Code under review:
private byte[] buildMetricOutput() {
        try {
            String output = getStatusPacket() + getAllMetricsPackets();
            return output.getBytes(StandardCharsets.UTF_8);
        } catch (JSONException e) {
            throw new RuntimeException("Bad JSON construction.", e);
        }
    }

Line commented on: String output = getStatusPacket() + getAllMetricsPackets();

Revised code:
private byte[] buildMetricOutput() {
        try {
            String output = getStatusPacket() + getAllMetricsPackets();
            return output.getBytes(StandardCharsets.UTF_8);
        } catch (JSONException e) {
            throw new RuntimeException("Bad JSON construction.", e);
        }
    }
Code review comment: This can be condensed into `return typeName != null && typeName.equals(CLIENT_LOGGER);`

Code under review:
private boolean isTypeClientLogger(DetailAST varDefAST) {
        DetailAST typeAST = varDefAST.findFirstToken(TokenTypes.TYPE);
        DetailAST varNameAST = varDefAST.findFirstToken(TokenTypes.IDENT);
        if (typeAST == null || varNameAST == null) {
            return false;
        }
        DetailAST typeNameAST = typeAST.findFirstToken(TokenTypes.IDENT);
        if (typeNameAST == null) {
            return false;
        }
        String typeName = typeNameAST.getText();
        if (typeName != null && typeName.equals(CLIENT_LOGGER)) {
            return true;
        }
        return false;
    }

Line commented on: return false;

Revised code:
private boolean isTypeClientLogger(DetailAST varDefAST) {
        final DetailAST typeAST = varDefAST.findFirstToken(TokenTypes.TYPE);
        if (typeAST == null) {
            return false;
        }
        return TokenUtil.findFirstTokenByPredicate(typeAST, node ->
           node.getType() == TokenTypes.IDENT && node.getText().equals(CLIENT_LOGGER)
        ).isPresent();
    }
Code review comment: The number "-1" doesn't look very good in a function called "unsigned..." - are you sure this is correct? Is there a way to make it more obviously correct?

Code under review:
private static byte[] unsignedCopyAndIncrement(byte[] input) {
    byte[] copy = Arrays.copyOf(input, input.length);
    if (copy == null) {
      throw new IllegalArgumentException("cannot increment null array");
    } else {
      for (int i = copy.length - 1; i >= 0; --i) {
        if (copy[i] != -1) {
          ++copy[i];
          return copy;
        }
        copy[i] = 0;
      }
      byte[] out = new byte[copy.length + 1];
      out[0] = 1;
      System.arraycopy(copy, 0, out, 1, copy.length);
      return out;
    }
  }

Line commented on: if (copy[i] != -1) {

Revised code:
private static byte[] unsignedCopyAndIncrement(byte[] input) {
    if (input.length == 0) {
      return new byte[] {0};
    }
    byte[] copy = Arrays.copyOf(input, input.length);
    for (int i = copy.length - 1; i >= 0; --i) {
      if (copy[i] != (byte) 0xff) {
        ++copy[i];
        return copy;
      }
      copy[i] = 0;
    }
    byte[] out = new byte[copy.length + 1];
    out[0] = 1;
    System.arraycopy(copy, 0, out, 1, copy.length);
    return out;
  }
Code review comment: Using `-s expectedSavepointPath -n --legacy` is not necessarily descriptive. It is not straightforward to tell what the `legacy` refers to.  This has been also pointed out by @rkhachatryan. Do you have any comments on that?

Code under review:
public void testClaimRestoreModeParsing() throws Exception {
        
        String[] parameters = {
            "-s", "expectedSavepointPath", "-n", "-r", "claim", getTestJarPath()
        };

        CommandLine commandLine =
                CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, parameters, true);
        ProgramOptions programOptions = ProgramOptions.create(commandLine);
        ExecutionConfigAccessor executionOptions =
                ExecutionConfigAccessor.fromProgramOptions(programOptions, Collections.emptyList());

        SavepointRestoreSettings savepointSettings = executionOptions.getSavepointRestoreSettings();
        assertTrue(savepointSettings.restoreSavepoint());
        assertEquals(RestoreMode.CLAIM, savepointSettings.getRestoreMode());
        assertEquals("expectedSavepointPath", savepointSettings.getRestorePath());
        assertTrue(savepointSettings.allowNonRestoredState());
    }

Line commented on: "-s", "expectedSavepointPath", "-n", "-r", "claim", getTestJarPath()

Revised code:
public void testClaimRestoreModeParsing() throws Exception {
        
        String[] parameters = {
            "-s", "expectedSavepointPath", "-n", "-restoreMode", "claim", getTestJarPath()
        };

        CommandLine commandLine =
                CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, parameters, true);
        ProgramOptions programOptions = ProgramOptions.create(commandLine);
        ExecutionConfigAccessor executionOptions =
                ExecutionConfigAccessor.fromProgramOptions(programOptions, Collections.emptyList());

        SavepointRestoreSettings savepointSettings = executionOptions.getSavepointRestoreSettings();
        assertTrue(savepointSettings.restoreSavepoint());
        assertEquals(RestoreMode.CLAIM, savepointSettings.getRestoreMode());
        assertEquals("expectedSavepointPath", savepointSettings.getRestorePath());
        assertTrue(savepointSettings.allowNonRestoredState());
    }
Code review comment: -> Error happens when closing the output stream for {}. Do not record events any more.  A few other logs need to be refined as well.

Code under review:
void closeOutputStream() {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException exception) {
                LOG.warn(
                        "Close the output stream for {} meet error, will not record event any more.",
                        writeFile,
                        exception);
                corrupted = true;
            } finally {
                outputStream = null;
            }
        }
    }

Line commented on: "Close the output stream for {} meet error, will not record event any more.",

Revised code:
void closeOutputStream() {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException exception) {
                LOG.warn(
                        "Error happens when closing the output stream for {}. Do not record events any more.",
                        writeFile,
                        exception);
                corrupted = true;
            } finally {
                outputStream = null;
            }
        }
    }
Code review comment: The most risky bug in this code is: Incorrect usage of `getDate` method to extract a `Timestamp` value.  You can modify the code like this: ```java @@ -220,7 +220,7 @@ public List<Partition> getPartitions(Connection connection, Table table) {                  while (rs.next()) {                      String[] partitionNames = rs.getString("NAME").                              replace("'", "").split(","); -                    long createTime = rs.getDate("MODIFIED_TIME").getTime(); +                    long createTime = rs.getTimestamp("MODIFIED_TIME").getTime(); // Correctly use getTimestamp for datetime columns                      for (String partitionName : partitionNames) {                          list.add(new Partition(partitionName, createTime));                      } ``` This change ensures that the correct method `getTimestamp` is called on the `ResultSet` object to handle the time information correctly when it's stored as a `TIMESTAMP` or `DATETIME` data type in the database. Using `getDate` can lead to loss of precision since it only captures the date portion and not the time.

Code under review:
private static String getPartitionQuery(Table table) {
        final String partitionsQuery = "SELECT PARTITION_DESCRIPTION AS NAME, " +
                "IF(UPDATE_TIME IS NULL, CREATE_TIME, UPDATE_TIME) AS MODIFIED_TIME " +
                "FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? " +
                "AND PARTITION_NAME IS NOT NULL " +
                "AND ( PARTITION_METHOD = 'RANGE' or PARTITION_METHOD = 'RANGE COLUMNS') ORDER BY PARTITION_DESCRIPTION";
        final String nonPartitionQuery = "SELECT TABLE_NAME AS NAME, " +
                "IF(UPDATE_TIME IS NULL, CREATE_TIME, UPDATE_TIME) AS MODIFIED_TIME " +
                "FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ";
        return table.isUnPartitioned() ? nonPartitionQuery : partitionsQuery;
    }

Line commented on: final String partitionsQuery = "SELECT PARTITION_DESCRIPTION AS NAME, " +

Revised code:
private static String getPartitionQuery(Table table) {
        final String partitionsQuery = "SELECT PARTITION_DESCRIPTION AS NAME, " +
                "IF(UPDATE_TIME IS NULL, CREATE_TIME, UPDATE_TIME) AS MODIFIED_TIME " +
                "FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? " +
                "AND PARTITION_NAME IS NOT NULL " +
                "AND ( PARTITION_METHOD = 'RANGE' or PARTITION_METHOD = 'RANGE COLUMNS') ORDER BY PARTITION_DESCRIPTION";
        final String nonPartitionQuery = "SELECT TABLE_NAME AS NAME, " +
                "IF(UPDATE_TIME IS NULL, CREATE_TIME, UPDATE_TIME) AS MODIFIED_TIME " +
                "FROM INFORMATION_SCHEMA.PARTITIONS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ? ";
        return table.isUnPartitioned() ? nonPartitionQuery : partitionsQuery;
    }
Code review comment: I agree, keeping only `-restoreMode` without abbrevitions and with several values should suffice and be less confusing IMO.

Code under review:
public void testClaimRestoreModeParsing() throws Exception {
        
        String[] parameters = {
            "-s", "expectedSavepointPath", "-n", "-r", "claim", getTestJarPath()
        };

        CommandLine commandLine =
                CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, parameters, true);
        ProgramOptions programOptions = ProgramOptions.create(commandLine);
        ExecutionConfigAccessor executionOptions =
                ExecutionConfigAccessor.fromProgramOptions(programOptions, Collections.emptyList());

        SavepointRestoreSettings savepointSettings = executionOptions.getSavepointRestoreSettings();
        assertTrue(savepointSettings.restoreSavepoint());
        assertEquals(RestoreMode.CLAIM, savepointSettings.getRestoreMode());
        assertEquals("expectedSavepointPath", savepointSettings.getRestorePath());
        assertTrue(savepointSettings.allowNonRestoredState());
    }

Line commented on: "-s", "expectedSavepointPath", "-n", "-r", "claim", getTestJarPath()

Revised code:
public void testClaimRestoreModeParsing() throws Exception {
        
        String[] parameters = {
            "-s", "expectedSavepointPath", "-n", "-restoreMode", "claim", getTestJarPath()
        };

        CommandLine commandLine =
                CliFrontendParser.parse(CliFrontendParser.RUN_OPTIONS, parameters, true);
        ProgramOptions programOptions = ProgramOptions.create(commandLine);
        ExecutionConfigAccessor executionOptions =
                ExecutionConfigAccessor.fromProgramOptions(programOptions, Collections.emptyList());

        SavepointRestoreSettings savepointSettings = executionOptions.getSavepointRestoreSettings();
        assertTrue(savepointSettings.restoreSavepoint());
        assertEquals(RestoreMode.CLAIM, savepointSettings.getRestoreMode());
        assertEquals("expectedSavepointPath", savepointSettings.getRestorePath());
        assertTrue(savepointSettings.allowNonRestoredState());
    }
Code review comment: if meter is null, `AmqpMetricsProvider` uses default meter (i.e. creates one using default options).  The next step would be creating meter in EH/SB and plumbing it through to AMQP core so the default meter will never be used and users will be able to configure metrics if they want.  I'm just phasing this work across several releases to reduce dependency mismatch pain with the new EB/EH + old amqp core.

Code under review:
AmqpMetricsProvider getMetricProvider(String namespace, String entityPath) {
        if (meter != null && !meter.isEnabled()) {
            return AmqpMetricsProvider.noop();
        }

        return metricsCache.computeIfAbsent(
            namespace + (entityPath == null ? "" : "/" + entityPath),
            ignored -> new AmqpMetricsProvider(meter, namespace, entityPath));
    }

Line commented on: ignored -> new AmqpMetricsProvider(meter, namespace, entityPath));

Revised code:
AmqpMetricsProvider getMetricProvider(String namespace, String entityPath) {
        if (meter != null && !meter.isEnabled()) {
            return AmqpMetricsProvider.noop();
        }

        return metricsCache.computeIfAbsent(
            namespace + (entityPath == null ? "" : "/" + entityPath),
            ignored -> new AmqpMetricsProvider(meter, namespace, entityPath));
    }
Code review comment: I find it nice to add a descriptive message, e.g. ``` new RuntimeException("Failed to read PipelineOptions from Protocol", e); ```

Code under review:
public static PipelineOptions fromProto(Struct protoOptions) {
    try {
      Map<String, TreeNode> mapWithoutUrns = new HashMap<>();
      TreeNode rootOptions = MAPPER.readTree(JsonFormat.printer().print(protoOptions));
      Iterator<String> optionsKeys = rootOptions.fieldNames();
      while (optionsKeys.hasNext()) {
        String optionKey = optionsKeys.next();
        TreeNode optionValue = rootOptions.get(optionKey);
        mapWithoutUrns.put(
            CaseFormat.LOWER_UNDERSCORE.to(
                CaseFormat.LOWER_CAMEL,
                optionKey.substring("beam:option:".length(), optionKey.length() - ":v1".length())),
            optionValue);
      }
      return MAPPER.readValue(
          MAPPER.writeValueAsString(ImmutableMap.of("options", mapWithoutUrns)),
          PipelineOptions.class);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

Line commented on: throw new RuntimeException(e);

Revised code:
public static PipelineOptions fromProto(Struct protoOptions) {
    try {
      Map<String, TreeNode> mapWithoutUrns = new HashMap<>();
      TreeNode rootOptions = MAPPER.readTree(JsonFormat.printer().print(protoOptions));
      Iterator<String> optionsKeys = rootOptions.fieldNames();
      while (optionsKeys.hasNext()) {
        String optionKey = optionsKeys.next();
        TreeNode optionValue = rootOptions.get(optionKey);
        mapWithoutUrns.put(
            CaseFormat.LOWER_UNDERSCORE.to(
                CaseFormat.LOWER_CAMEL,
                optionKey.substring("beam:option:".length(), optionKey.length() - ":v1".length())),
            optionValue);
      }
      return MAPPER.readValue(
          MAPPER.writeValueAsString(ImmutableMap.of("options", mapWithoutUrns)),
          PipelineOptions.class);
    } catch (IOException e) {
      throw new RuntimeException("Failed to read PipelineOptions from Protocol", e);
    }
  }
Code review comment: No - 862 being info is helpful - because it helps debugging in scenarios where some ingestion tasks take a long time (hang vs. long running task)

Code under review:
private void completeAllSinks() {
        logger.info("Closing all sinks, Context: {}", this.operationContextText);

        logger.debug("Executor service shut down, Context: {}", this.operationContextText);
        Sinks.EmitResult completeEmitResult = mainSink.tryEmitComplete();
        if (completeEmitResult == Sinks.EmitResult.OK) {
            logger.debug("Main sink completed, Context: {}", this.operationContextText);
        } else {
            if (completeEmitResult == Sinks.EmitResult.FAIL_CANCELLED ||
                completeEmitResult == Sinks.EmitResult.FAIL_TERMINATED) {

                logger.debug("Main sink already completed, EmitResult: {}, Context: {}",
                    completeEmitResult,
                    this.operationContextText);
            } else {
                logger.info(
                    "Main sink completion failed. EmitResult: {}, Context: {}",
                    completeEmitResult,
                    this.operationContextText);
            }
        }

        this.shutdown();
    }

Line commented on: if (completeEmitResult == Sinks.EmitResult.FAIL_CANCELLED ||

Revised code:
private void completeAllSinks() {
        logger.info("Closing all sinks, Context: {}", this.operationContextText);

        logger.debug("Executor service shut down, Context: {}", this.operationContextText);
        Sinks.EmitResult completeEmitResult = mainSink.tryEmitComplete();
        if (completeEmitResult == Sinks.EmitResult.OK) {
            logger.debug("Main sink completed, Context: {}", this.operationContextText);
        } else {
            if (completeEmitResult == Sinks.EmitResult.FAIL_CANCELLED ||
                completeEmitResult == Sinks.EmitResult.FAIL_TERMINATED) {

                logger.debug("Main sink already completed, EmitResult: {}, Context: {}",
                    completeEmitResult,
                    this.operationContextText);
            } else {
                logger.warn(
                    "Main sink completion failed. EmitResult: {}, Context: {}",
                    completeEmitResult,
                    this.operationContextText);
            }
        }

        this.shutdown();
    }