muttakin2301/ccr2000 huggingface dataset:
Code review comment: Cool - that makes sense, thanks. Just wanted to make sure we weren't changing for a failing test.

Code under review:
public void shouldNotDetectClassPathResourceThatIsNotAFile() throws Exception {
    String url = "http:
    ClassLoader classLoader = new URLClassLoader(new URL[] {new URL(url)});
    ClasspathScanningResourcesDetector detector =
        new ClasspathScanningResourcesDetector(new ClassGraph());

    List<String> result = detector.detect(classLoader);

    assertThat(result, not(hasItem(containsString(url))));
  }

Line commented on: String url = "http:

Revised code:
public void shouldNotDetectClassPathResourceThatIsNotAFile() throws Exception {
    String url = "http:
    ClassLoader classLoader = new URLClassLoader(new URL[] {new URL(url)});
    ClasspathScanningResourcesDetector detector =
        new ClasspathScanningResourcesDetector(new ClassGraph());

    List<String> result = detector.detect(classLoader);

    assertThat(result, not(hasItem(containsString(url))));
  }
Code review comment: @kushagraThapar https://github.com/Azure/azure-sdk-for-java/issues/9053 is for the PartitionKey.None is that right link?

Code under review:
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) {
        String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN);
        if (!Strings.isNullOrEmpty(sessionToken)) {
            String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();
            getLocalSessionToken(request, sessionToken, partitionKeyRangeId);
            request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN);
        }
    }

Line commented on: String partitionKeyRangeId = request.requestContext.resolvedPartitionKeyRange.getId();

Revised code:
public static void validateAndRemoveSessionToken(RxDocumentServiceRequest request) {
        String sessionToken = request.getHeaders().get(HttpConstants.HttpHeaders.SESSION_TOKEN);
        if (!Strings.isNullOrEmpty(sessionToken)) {
            getLocalSessionToken(request, sessionToken, StringUtils.EMPTY);
            request.getHeaders().remove(HttpConstants.HttpHeaders.SESSION_TOKEN);
        }
    }
Code review comment: @soulasuna Can you add some sql parse test case for this logic?

Code under review:
public ASTNode visitSet(final SetContext ctx) {
        PostgreSQLSetStatement result = new PostgreSQLSetStatement();
        Collection<VariableAssignSegment> variableAssigns = new LinkedList<>();
        if (null != ctx.configurationParameterClause()) {
            VariableAssignSegment variableAssignSegment = (VariableAssignSegment) visit(ctx.configurationParameterClause());
            if (null != ctx.runtimeScope()) {
                variableAssignSegment.getVariable().setScope(ctx.runtimeScope().getText());
            }
            variableAssigns.add(variableAssignSegment);
        }
        if (null != ctx.encoding()) {
            VariableAssignSegment variableAssignSegment = new VariableAssignSegment();
            VariableSegment variableSegment = new VariableSegment();
            variableSegment.setVariable("charset");
            variableAssignSegment.setVariable(variableSegment);
            String value = ctx.encoding().getText();
            variableAssignSegment.setAssignValue(value);
            variableAssigns.add(variableAssignSegment);
        }
        result.getVariableAssigns().addAll(variableAssigns);
        return result;
    }

Line commented on: result.getVariableAssigns().addAll(variableAssigns);

Revised code:
public ASTNode visitSet(final SetContext ctx) {
        PostgreSQLSetStatement result = new PostgreSQLSetStatement();
        Collection<VariableAssignSegment> variableAssigns = new LinkedList<>();
        if (null != ctx.configurationParameterClause()) {
            VariableAssignSegment variableAssignSegment = (VariableAssignSegment) visit(ctx.configurationParameterClause());
            if (null != ctx.runtimeScope()) {
                variableAssignSegment.getVariable().setScope(ctx.runtimeScope().getText());
            }
            variableAssigns.add(variableAssignSegment);
        }
        if (null != ctx.encoding()) {
            VariableAssignSegment variableAssignSegment = new VariableAssignSegment();
            VariableSegment variableSegment = new VariableSegment();
            variableSegment.setVariable("charset");
            variableAssignSegment.setVariable(variableSegment);
            String value = ctx.encoding().getText();
            variableAssignSegment.setAssignValue(value);
            variableAssigns.add(variableAssignSegment);
        }
        result.getVariableAssigns().addAll(variableAssigns);
        return result;
    }
Code review comment: @Ladicek we wanted to know if ClassInfo.annotations(annotation) orders the result the same as when you loop over ClassInfo.fields(). If so I can improve the code without introducing a breaking change. If not I will have to keep it like this.   @FroMage Is there a way we can have users migrate to the new RestLinkId annotation which is more safe to use?

Code under review:
private FieldInfo resolveField(IndexView index, String parameterName, DotName className) {
        FieldInfoSupplier byParamName = new FieldInfoSupplier(c -> c.field(parameterName), className, index);

        
        FieldInfo fieldInfo = byParamName.get();
        if (parameterName.equals("id")) {
            
            
            
            
            
            FieldInfoSupplier byIdAnnotation = new FieldInfoSupplier(
                    c -> {
                        FieldInfo persistenceId = null;
                        for (FieldInfo field : c.fields()) {
                            
                            if (fieldAnnotatedWith(field, RestLinkId.class.getName())) {
                                return field;
                            }
                            
                            if (fieldAnnotatedWith(field, "persistence.Id") && persistenceId == null) {
                                persistenceId = field;
                            }
                        }
                        return persistenceId;
                    },
                    className,
                    index);
            if (byIdAnnotation.get() != null) {
                fieldInfo = byIdAnnotation.get();
            }
        }
        return fieldInfo;
    }

Line commented on: for (FieldInfo field : c.fields()) {

Revised code:
private FieldInfo resolveField(IndexView index, String parameterName, DotName className) {
        FieldInfoSupplier byParamName = new FieldInfoSupplier(c -> c.field(parameterName), className, index);

        
        FieldInfo fieldInfo = byParamName.get();
        if (parameterName.equals("id")) {
            
            
            
            
            
            FieldInfoSupplier byAnnotation = new FieldInfoSupplier(
                    c -> {
                        FieldInfo persistenceId = null;
                        for (FieldInfo field : c.fields()) {
                            
                            if (field.hasAnnotation(RestLinkId.class)) {
                                return field;
                            }
                            
                            if (fieldAnnotatedWith(field, "persistence.Id") && persistenceId == null) {
                                persistenceId = field;
                            }
                        }
                        return persistenceId;
                    },
                    className,
                    index);
            FieldInfo annotatedField = byAnnotation.get();
            if (annotatedField != null) {
                fieldInfo = annotatedField;
            }
        }
        return fieldInfo;
    }
Code review comment: Is the Toml location correct ? Shall we validate the location is the test as well ?

Code under review:
public void testPkgInvalidExportedModule() {
        Package currentPackage = loadPackage("package_invalid_exported_modules");
        DiagnosticResult diagnosticResult = currentPackage.getCompilation().diagnosticResult();
        Assert.assertEquals(diagnosticResult.diagnosticCount(), 3, "Unexpected number of compilation diagnostics");
        Iterator<Diagnostic> diagnosticIterator = diagnosticResult.diagnostics().iterator();
        Assert.assertEquals(diagnosticIterator.next().toString(), "ERROR [Ballerina.toml:(7:0,7:64)] "
                + "could not locate dependency path '../libs/ballerina-runtime-api-2.0.0-beta.2-SNAPSHOT.jar'");
        Assert.assertEquals(diagnosticIterator.next().toString(), "ERROR [Ballerina.toml:(4:10,4:15)] "
                + "exported module 'abc' is not a module of the package");
        Assert.assertEquals(diagnosticIterator.next().toString(), "ERROR [Ballerina.toml:(4:17,4:22)] "
                + "exported module 'xyz' is not a module of the package");
    }

Line commented on: Assert.assertEquals(diagnosticIterator.next().toString(), "ERROR [Ballerina.toml:(4:10,4:15)] "

Revised code:
public void testPkgInvalidExportedModule() {
        Package currentPackage = loadPackage("package_invalid_exported_modules");
        DiagnosticResult diagnosticResult = currentPackage.getCompilation().diagnosticResult();
        Assert.assertEquals(diagnosticResult.diagnosticCount(), 3, "Unexpected number of compilation diagnostics");
        Iterator<Diagnostic> diagnosticIterator = diagnosticResult.diagnostics().iterator();
        Assert.assertEquals(diagnosticIterator.next().toString(), "ERROR [Ballerina.toml:(7:0,7:64)] "
                + "could not locate dependency path '../libs/ballerina-runtime-api-2.0.0-beta.2-SNAPSHOT.jar'");
        Assert.assertEquals(diagnosticIterator.next().toString(), "ERROR [Ballerina.toml:(4:10,4:15)] "
                + "exported module 'abc' is not a module of the package");
        Assert.assertEquals(diagnosticIterator.next().toString(), "ERROR [Ballerina.toml:(4:17,4:22)] "
                + "exported module 'xyz' is not a module of the package");
    }
Code review comment: Added it to constructor and left a comment to explain why we do that check.

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

Line commented on: if (this.index == 0) {

Revised code:
public void setIndex(int index) {
        
        if (this.index == 0) {
            this.index = index;
        }
    }
Code review comment: Doesn't `QuerySpecification` have fluent setters?

Code under review:
Mono<PagedResponse<String>> queryFirstPage(String query, Context context) {
        QuerySpecification querySpecification = new QuerySpecification();

        querySpecification
            .setQuery(query);

        return protocolLayer
            .getQueries()
            .queryTwinsWithResponseAsync(querySpecification, context)
            .map(objectPagedResponse -> new PagedResponseBase<>(
                objectPagedResponse.getRequest(),
                objectPagedResponse.getStatusCode(),
                objectPagedResponse.getHeaders(),
                objectPagedResponse.getValue().getItems().stream()
                    .map(object -> {
                        try {
                            return mapper.writeValueAsString(object);
                        } catch (JsonProcessingException e) {
                            logger.error("JsonProcessingException occurred while retrieving query result items: ", e);
                            throw new RuntimeException("JsonProcessingException occurred while retrieving query result items", e);
                        }
                    })
                    .filter(Objects::nonNull)
                    .collect(Collectors.toList()),
                objectPagedResponse.getValue().getContinuationToken(),
                objectPagedResponse.getDeserializedHeaders()));
    }

Line commented on: querySpecification

Revised code:
new QuerySpecification().setQuery(query);

        return protocolLayer
            .getQueries()
            .queryTwinsWithResponseAsync(querySpecification, context)
            .map(objectPagedResponse -> new PagedResponseBase<>(
                objectPagedResponse.getRequest(),
                objectPagedResponse.getStatusCode(),
                objectPagedResponse.getHeaders(),
                objectPagedResponse.getValue().getItems().stream()
                    .map(object -> {
                        try {
                            return mapper.writeValueAsString(object);
                        } catch (JsonProcessingException e) {
                            logger.error("JsonProcessingException occurred while retrieving query result items: ", e);
                            throw new RuntimeException("JsonProcessingException occurred while retrieving query result items", e);
                        }
                    }
Code review comment: throw new NumberFormatException("invalid id: " + id);

Code under review:
public static TUniqueId parseTUniqueIdFromString(String id) {
        if (Strings.isNullOrEmpty(id)) {
            throw new NumberFormatException("invalid query id");
        }

        String[] parts = id.split("-");
        if (parts.length != 2) {
            throw new NumberFormatException("invalid query id");
        }

        TUniqueId uniqueId = new TUniqueId();
        try {
            uniqueId.setHi(Long.parseUnsignedLong(parts[0], 16));
            uniqueId.setLo(Long.parseUnsignedLong(parts[1], 16));
        } catch (NumberFormatException e) {
            throw new NumberFormatException("invalid query id:" + e.getMessage());
        }

        return uniqueId;
    }

Line commented on: throw new NumberFormatException("invalid query id");

Revised code:
public static TUniqueId parseTUniqueIdFromString(String id) {
        if (Strings.isNullOrEmpty(id)) {
            throw new NumberFormatException("invalid query id");
        }

        String[] parts = id.split("-");
        if (parts.length != 2) {
            throw new NumberFormatException("invalid query id");
        }

        TUniqueId uniqueId = new TUniqueId();
        try {
            uniqueId.setHi(Long.parseUnsignedLong(parts[0], 16));
            uniqueId.setLo(Long.parseUnsignedLong(parts[1], 16));
        } catch (NumberFormatException e) {
            throw new NumberFormatException("invalid query id:" + e.getMessage());
        }

        return uniqueId;
    }
Code review comment: I got a PR on https://github.com/geoand/quarkus/pull/1 but for right padding but for some reason that gives me a NPE in the java compiler ;)

Code under review:
private String readBannerFile(BannerConfig config) {
        URL resource = Thread.currentThread().getContextClassLoader().getResource(config.path);
        if (resource != null) {
            try (InputStream is = resource.openStream()) {
                byte[] content = FileUtil.readFileContents(is);
                StringBuilder bannerTitle = new StringBuilder(new String(content, StandardCharsets.UTF_8));
                bannerTitle.append('\n');
                if (!config.isDefaultPath()) {
                    bannerTitle.append("Powered by Quarkus v").append(Version.getVersion()).append('\n');
                }
                return bannerTitle.toString();
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        } else {
            logger.warn("Could not read banner file");
            return "";
        }
    }

Line commented on: bannerTitle.append("Powered by Quarkus v").append(Version.getVersion()).append('\n');

Revised code:
private String readBannerFile(BannerConfig config) {
        try {
            Map.Entry<URL, Boolean> entry = getBanner(config);
            URL bannerResourceURL = entry.getKey();
            if (bannerResourceURL == null) {
                logger.warn("Could not locate banner file");
                return "";
            }
            try (InputStream is = bannerResourceURL.openStream()) {
                byte[] content = FileUtil.readFileContents(is);
                String bannerTitle = new String(content, StandardCharsets.UTF_8);

                int width = 0;
                Scanner scanner = new Scanner(bannerTitle);
                while (scanner.hasNextLine()) {
                    width = Math.max(width, scanner.nextLine().length());
                }

                String tagline = "\n";
                Boolean isDefaultBanner = entry.getValue();
                if (!isDefaultBanner) {
                    tagline = String.format("\n%" + width + "s\n", "Powered by Quarkus v" + Version.getVersion());
                }

                return bannerTitle + tagline;
            }
        } catch (IOException e) {
            logger.warn("Unable to read banner file");
            return "";
        }
    }
Code review comment: ```suggestion             return cosmosItem; ``` on this if branch the item is InternalObjectNode you don't need to serialze and deserialize again.

Code under review:
public static InternalObjectNode fromObjectToInternalObjectNode(Object cosmosItem) {
        if (cosmosItem instanceof InternalObjectNode) {
            return new InternalObjectNode(((InternalObjectNode) cosmosItem).toJson());
        } else if (cosmosItem instanceof byte[]) {
            return new InternalObjectNode((byte[]) cosmosItem);
        } else {
            try {
                return new InternalObjectNode(InternalObjectNode.MAPPER.writeValueAsString(cosmosItem));
            } catch (IOException e) {
                throw new IllegalArgumentException("Can't serialize the object into the json string", e);
            }
        }
    }

Line commented on: return new InternalObjectNode(((InternalObjectNode) cosmosItem).toJson());

Revised code:
public static InternalObjectNode fromObjectToInternalObjectNode(Object cosmosItem) {
        if (cosmosItem instanceof InternalObjectNode) {
            return (InternalObjectNode) cosmosItem;
        } else if (cosmosItem instanceof byte[]) {
            return new InternalObjectNode((byte[]) cosmosItem);
        } else {
            try {
                return new InternalObjectNode(InternalObjectNode.MAPPER.writeValueAsString(cosmosItem));
            } catch (IOException e) {
                throw new IllegalArgumentException("Can't serialize the object into the json string", e);
            }
        }
    }
Code review comment: Comma should be at the end of the previous line.

Code under review:
public void testPullCount() throws IOException {
        URI remoteUri = URI.create(RepoUtils.getRemoteRepoURL() + "/modules/info/" + orgName + "/" + moduleName);
        HttpURLConnection conn;
        conn = (HttpURLConnection) remoteUri.toURL().openConnection();
        int statusCode = conn.getResponseCode();
        if (statusCode == 200) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()
                    , Charset.defaultCharset()))) {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                Object payload = JSONParser.parse(result.toString());
                if (payload instanceof MapValue) {
                    long pullCount = ((MapValue) payload).getIntValue("totalPullCount");
                    Assert.assertEquals(pullCount, 1);
                }
            }
        }
    }

Line commented on: , Charset.defaultCharset()))) {

Revised code:
public void testPullCount() throws IOException {
        URI remoteUri = URI.create(RepoUtils.getStagingURL() + "/modules/info/" + orgName + "/" + moduleName + "/*/");
        HttpURLConnection conn;
        conn = (HttpURLConnection) remoteUri.toURL().openConnection();
        int statusCode = conn.getResponseCode();
        if (statusCode == 200) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),
                    Charset.defaultCharset()))) {
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }
                Object payload = JSONParser.parse(result.toString());
                if (payload instanceof MapValue) {
                    long pullCount = ((MapValue) payload).getIntValue("totalPullCount");
                    Assert.assertEquals(pullCount, totalPullCount);
                } else {
                    Assert.fail("error: invalid response received");
                }
            }
        } else {
            Assert.fail("error: could not connect to remote repository to find the latest version of module");
        }
    }
Code review comment: Yes. My next pr will fix it.

Code under review:
public void testInClauseCombineOr_2() throws Exception {
        String plan = getFragmentPlan("select * from ptest where (d2 > '1000-01-01') or (d2 in (null, null));");
        assertTrue(plan.contains("  0:OlapScanNode\n" +
                "     TABLE: ptest\n" +
                "     PREAGGREGATION: ON\n" +
                "     PREDICATES: (2: d2 > '1000-01-01') OR (2: d2 IN (NULL, NULL)), 2: d2 > '1000-01-01'\n" +
                "     partitions=4/4\n" +
                "     rollup: ptest"));
    }

Line commented on: "     PREDICATES: (2: d2 > '1000-01-01') OR (2: d2 IN (NULL, NULL)), 2: d2 > '1000-01-01'\n" +

Revised code:
public void testInClauseCombineOr_2() throws Exception {
        String plan = getFragmentPlan("select * from ptest where (d2 > '1000-01-01') or (d2 in (null, null));");
        assertTrue(plan.contains("  0:OlapScanNode\n" +
                "     TABLE: ptest\n" +
                "     PREAGGREGATION: ON\n" +
                "     PREDICATES: (2: d2 > '1000-01-01') OR (2: d2 IN (NULL, NULL)), 2: d2 > '1000-01-01'\n" +
                "     partitions=4/4\n" +
                "     rollup: ptest"));
    }
Code review comment: > Is the documentation of the sql client outdated? It doesn't list --update   Not outdated, the --update is used to execute one SQL statement in the client, such as:  ``` ./bin/sql-client.sh embedded --jar test.jar -u "select 1" ```  > and embedded does not appear to be an optional argument.  That's true, now it's a necessary argument, let me change this.

Code under review:
public void submitSQLJob(SQLJobSubmission job) throws IOException {
		final List<String> commands = new ArrayList<>();
		commands.add(bin.resolve("sql-client.sh").toAbsolutePath().toString());
		if (job.isEmbedded()) {
			commands.add("embedded");
		}
		if (job.getDefaultEnvFile() != null) {
			commands.add("--defaults");
			commands.add(job.getDefaultEnvFile());
		}
		if (job.getSessionEnvFile() != null) {
			commands.add("--environment");
			commands.add(job.getSessionEnvFile());
		}
		for (String jar : job.getJars()) {
			commands.add("--jar");
			commands.add(jar);
		}
		commands.add("--update");
		commands.add("\"" + job.getSQL() + "\"");

		AutoClosableProcess.create(commands.toArray(new String[0])).runBlocking();
	}

Line commented on: commands.add(jar);

Revised code:
public void submitSQLJob(SQLJobSubmission job) throws IOException {
		final List<String> commands = new ArrayList<>();
		commands.add(bin.resolve("sql-client.sh").toAbsolutePath().toString());
		commands.add("embedded");
		job.getDefaultEnvFile().ifPresent(defaultEnvFile -> {
			commands.add("--defaults");
			commands.add(defaultEnvFile);
		});
		job.getSessionEnvFile().ifPresent(sessionEnvFile -> {
			commands.add("--environment");
			commands.add(sessionEnvFile);
		});
		for (String jar : job.getJars()) {
			commands.add("--jar");
			commands.add(jar);
		}
		commands.add("--update");
		commands.add("\"" + job.getSQL() + "\"");

		AutoClosableProcess.runBlocking(commands.toArray(new String[0]));
	}
Code review comment: That's what I had there originally, but since some pieces of code just choose to "silently" proceed now, WARN felt a bit too strong. But  I wouldn't mind...

Code under review:
private static ClassInfo lookupClassInIndex(IndexView index, DotName dotName, boolean withLogging) {
        if (dotName == null) {
            throw new IllegalArgumentException("Cannot lookup class, provided DotName was null.");
        }
        if (index == null) {
            throw new IllegalArgumentException("Cannot lookup class, provided Jandex Index was null.");
        }
        ClassInfo info = index.getClassByName(dotName);
        if (info == null && withLogging) {
            
            LOGGER.info("Class for name: " + dotName + " was not found in Jandex index. Please ensure the class " +
                    "is part of the index.");
        }
        return info;
    }

Line commented on: LOGGER.info("Class for name: " + dotName + " was not found in Jandex index. Please ensure the class " +

Revised code:
private static ClassInfo lookupClassInIndex(IndexView index, DotName dotName, boolean withLogging) {
        if (dotName == null) {
            throw new IllegalArgumentException("Cannot lookup class, provided DotName was null.");
        }
        if (index == null) {
            throw new IllegalArgumentException("Cannot lookup class, provided Jandex Index was null.");
        }
        ClassInfo info = index.getClassByName(dotName);
        if (info == null && withLogging) {
            
            LOGGER.info("Class for name: " + dotName + " was not found in Jandex index. Please ensure the class " +
                    "is part of the index.");
        }
        return info;
    }
Code review comment: We should probably pass the original exception as the `cause`

Code under review:
public ReactiveMongoCollection mongoCollection(Class<?> entityClass) {
        MongoEntity mongoEntity = entityClass.getAnnotation(MongoEntity.class);
        ReactiveMongoDatabase database = mongoDatabase(mongoEntity);
        if (mongoEntity != null) {
            ReactiveMongoCollection collection = mongoEntity.collection().isEmpty()
                    ? database.getCollection(entityClass.getSimpleName(), entityClass)
                    : database.getCollection(mongoEntity.collection(), entityClass);
            if (!mongoEntity.readPreference().isEmpty()) {
                try {
                    collection = collection.withReadPreference(ReadPreference.valueOf(mongoEntity.readPreference()));
                } catch (IllegalArgumentException iae) {
                    throw new IllegalArgumentException("Illegal read preference " + mongoEntity.readPreference()
                            + " configured in the @MongoEntity annotation of " + entityClass.getName() + "."
                            + " Supported values are primary|primaryPreferred|secondary|secondaryPreferred|nearest");
                }
            }
            return collection;
        }
        return database.getCollection(entityClass.getSimpleName(), entityClass);
    }

Line commented on: throw new IllegalArgumentException("Illegal read preference " + mongoEntity.readPreference()

Revised code:
public ReactiveMongoCollection mongoCollection(Class<?> entityClass) {
        MongoEntity mongoEntity = entityClass.getAnnotation(MongoEntity.class);
        ReactiveMongoDatabase database = mongoDatabase(mongoEntity);
        if (mongoEntity != null) {
            ReactiveMongoCollection collection = mongoEntity.collection().isEmpty()
                    ? database.getCollection(entityClass.getSimpleName(), entityClass)
                    : database.getCollection(mongoEntity.collection(), entityClass);
            if (!mongoEntity.readPreference().isEmpty()) {
                try {
                    collection = collection.withReadPreference(ReadPreference.valueOf(mongoEntity.readPreference()));
                } catch (IllegalArgumentException iae) {
                    throw new IllegalArgumentException("Illegal read preference " + mongoEntity.readPreference()
                            + " configured in the @MongoEntity annotation of " + entityClass.getName() + "."
                            + " Supported values are primary|primaryPreferred|secondary|secondaryPreferred|nearest");
                }
            }
            return collection;
        }
        return database.getCollection(entityClass.getSimpleName(), entityClass);
    }
Code review comment: Ugh.  No, I had added that briefly when testing and completely missed it when I cleaned up.  Removing now.

Code under review:
public Manager(DataflowWorkerHarnessOptions options, Collection<Capturable> capturables) {
      try {
        client = options.getDataflowClient();
      } catch (Exception e) {
        LOG.info("Failed to get dataflow client. Does not send debug capture data. ", e);
        return;
      }

      JsonFactory datOtherFactory = new JacksonFactory();

      project = options.getProject();
      job = options.getJobId();
      host = options.getWorkerId();
      region = options.getRegion();
      this.capturables = capturables;
      enabled = !capturables.isEmpty();

      LOG.info("Created Debug Capture Manager");
    }

Line commented on: JsonFactory datOtherFactory = new JacksonFactory();

Revised code:
public Manager(DataflowWorkerHarnessOptions options, Collection<Capturable> capturables) {
      try {
        client = options.getDataflowClient();
      } catch (Exception e) {
        LOG.info("Failed to get dataflow client. Does not send debug capture data. ", e);
        return;
      }

      project = options.getProject();
      job = options.getJobId();
      host = options.getWorkerId();
      region = options.getRegion();
      this.capturables = capturables;
      enabled = !capturables.isEmpty();

      LOG.info("Created Debug Capture Manager");
    }
Code review comment: I'll think of a better solution for 1.2. Unfortunately without this change, Kubernetes manifest generation for 1.1 was sort of broken

Code under review:
public KubernetesPortBuildItem kubernetes() {
        int port = ConfigProvider.getConfig().getOptionalValue("quarkus.http.port", Integer.class).orElse(8080);
        return new KubernetesPortBuildItem(port, "http");
    }

Line commented on: int port = ConfigProvider.getConfig().getOptionalValue("quarkus.http.port", Integer.class).orElse(8080);

Revised code:
public KubernetesPortBuildItem kubernetes() {
        int port = ConfigProvider.getConfig().getOptionalValue("quarkus.http.port", Integer.class).orElse(8080);
        return new KubernetesPortBuildItem(port, "http");
    }
Code review comment: Maybe, but it's hard to check each type, so only support Number/String/Boolean type

Code under review:
public boolean checkCastTypeReduceAble(Type parent, Type child, Type grandChild) {
        int parentSlotSize = parent.getTypeSize();
        int childSlotSize = child.getTypeSize();
        int grandChildSlotSize = grandChild.getTypeSize();

        if (parent.isDecimalOfAnyVersion() || child.isDecimalOfAnyVersion() || grandChild.isDecimalOfAnyVersion()) {
            return false;
        }

        if (!(parent.isNumericType() || parent.isStringType()) ||
                !(child.isNumericType() || child.isBoolean()) ||
                !(grandChild.isNumericType() || grandChild.isBoolean())) {
            return false;
        }

        
        
        if (parentSlotSize > childSlotSize && childSlotSize < grandChildSlotSize) {
            return false;
        }

        Type childCompatibleType = Type.getAssignmentCompatibleType(grandChild, child, true);
        Type parentCompatibleType = Type.getAssignmentCompatibleType(child, parent, true);
        return childCompatibleType != Type.INVALID && parentCompatibleType != Type.INVALID;
    }

Line commented on: if (!(parent.isNumericType() || parent.isStringType()) ||

Revised code:
public boolean checkCastTypeReduceAble(Type parent, Type child, Type grandChild) {
        int parentSlotSize = parent.getTypeSize();
        int childSlotSize = child.getTypeSize();
        int grandChildSlotSize = grandChild.getTypeSize();

        if (parent.isDecimalOfAnyVersion() || child.isDecimalOfAnyVersion() || grandChild.isDecimalOfAnyVersion()) {
            return false;
        }

        if (!(parent.isNumericType() || parent.isStringType()) ||
                !(child.isNumericType() || child.isBoolean()) ||
                !(grandChild.isNumericType() || grandChild.isBoolean())) {
            return false;
        }

        
        
        if (parentSlotSize > childSlotSize && childSlotSize < grandChildSlotSize) {
            return false;
        }

        Type childCompatibleType = Type.getAssignmentCompatibleType(grandChild, child, true);
        Type parentCompatibleType = Type.getAssignmentCompatibleType(child, parent, true);
        return childCompatibleType != Type.INVALID && parentCompatibleType != Type.INVALID;
    }
Code review comment: Could this be removed for a test in `azure-core`?

Code under review:
public void timeoutPolicy() {
        final String key = "newKey";
        final String value = "newValue";

        connectionString = interceptorManager.isPlaybackMode()
            ? "Endpoint=http:
            : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);

        
        final ConfigurationClient client = new ConfigurationClientBuilder()
            .connectionString(connectionString)
            .addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient();

        assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value));
    }


Revised code:
public void timeoutPolicy() {
        final String key = "newKey";
        final String value = "newValue";

        connectionString = interceptorManager.isPlaybackMode()
            ? "Endpoint=http:
            : Configuration.getGlobalConfiguration().get(AZURE_APPCONFIG_CONNECTION_STRING);

        
        final ConfigurationClient client = new ConfigurationClientBuilder()
            .connectionString(connectionString)
            .addPolicy(new TimeoutPolicy(Duration.ofMillis(1))).buildClient();

        assertThrows(RuntimeException.class, () -> client.setConfigurationSetting(key, null, value));
    }
Code review comment: I've addressed your point regarding the early returns vs nesting.  As for the `newState == desiredState`, this fails tests so I'd rather not use it.

Code under review:
boolean updateTaskExecutionState(TaskExecutionStateTransition taskExecutionStateTransition) {
        if (taskExecutionStateTransition.getExecutionState() != ExecutionState.FAILED) {
            return getExecutionGraph().updateState(taskExecutionStateTransition);
        }

        
        
        
        
        Optional<ExecutionVertexID> idOpt =
                executionGraph.findExecutionVertexId(taskExecutionStateTransition.getID());
        final boolean successfulUpdate =
                getExecutionGraph().updateState(taskExecutionStateTransition);
        if (!successfulUpdate) {
            return false;
        }

        Throwable cause = extractErrorOrUseDefault(taskExecutionStateTransition);

        checkState(idOpt.isPresent());
        ExecutionVertexID id = idOpt.get();

        if (getNonEmptyExecution(id).getFailureInfo().isPresent()) {
            failureCollection.add(new LocalFailure(cause, id));
        }
        onFailure(cause);
        return true;
    }

Line commented on: return true;

Revised code:
boolean updateTaskExecutionState(TaskExecutionStateTransition taskExecutionStateTransition) {
        
        final Optional<AccessExecution> maybeExecution =
                executionGraph.findExecution(taskExecutionStateTransition.getID());
        final Optional<String> maybeTaskName =
                executionGraph.findVertexWithAttempt(taskExecutionStateTransition.getID());

        final ExecutionState desiredState = taskExecutionStateTransition.getExecutionState();
        boolean successfulUpdate = getExecutionGraph().updateState(taskExecutionStateTransition);
        if (successfulUpdate && desiredState == ExecutionState.FAILED) {
            final AccessExecution execution =
                    maybeExecution.orElseThrow(NoSuchElementException::new);
            final String taskName = maybeTaskName.orElseThrow(NoSuchElementException::new);
            final ExecutionState currentState = execution.getState();
            if (currentState == desiredState) {
                failureCollection.add(ExceptionHistoryEntry.create(execution, taskName));
                onFailure(
                        ErrorInfo.handleMissingThrowable(
                                taskExecutionStateTransition.getError(userCodeClassLoader)));
            }
        }
        return successfulUpdate;
    }
Code review comment: The old timeout was too long.

Code under review:
private void stopProcess(String id, Process process) {
    if (process.isAlive()) {
      LOG.debug("Attempting to stop process with id {}", id);
      
      process.destroy();
      long maxTimeToWait = 500;
      try {
        if (waitForProcessToDie(process, maxTimeToWait)) {
          LOG.debug("Process for worker {} shut down gracefully.", id);
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      } finally {
        if (process.isAlive()) {
          LOG.info("Process for worker {} still running. Killing.", id);
          process.destroyForcibly();
        }
      }
    }
  }

Line commented on: long maxTimeToWait = 500;

Revised code:
private void stopProcess(String id, Process process) {
    if (process.isAlive()) {
      LOG.debug("Attempting to stop process with id {}", id);
      
      process.destroy();
      long maxTimeToWait = 500;
      try {
        if (waitForProcessToDie(process, maxTimeToWait)) {
          LOG.debug("Process for worker {} shut down gracefully.", id);
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      } finally {
        if (process.isAlive()) {
          LOG.info("Process for worker {} still running. Killing.", id);
          process.destroyForcibly();
        }
      }
    }
  }
Code review comment: ImmutableSet.copyOf(...) is likely faster, especially for sets of {0,1} elements. (Might be worth using elsewhere too.)

Code under review:
private StringSetResult getStringSetValue(MetricUpdate metricUpdate) {
      if (metricUpdate.getSet() == null) {
        return StringSetResult.empty();
      }
      return StringSetResult.create(new HashSet<>(((ArrayList) metricUpdate.getSet())));
    }

Line commented on: return StringSetResult.create(new HashSet<>(((ArrayList) metricUpdate.getSet())));

Revised code:
private StringSetResult getStringSetValue(MetricUpdate metricUpdate) {
      if (metricUpdate.getSet() == null) {
        return StringSetResult.empty();
      }
      return StringSetResult.create(ImmutableSet.copyOf(((Set) metricUpdate.getSet())));
    }
Code review comment: remove unnecessary `String.format` here and at other locations

Code under review:
public void testUnsetCatalogWithSelectCurrentTimestamp() throws Exception {
        TableEnvironment tEnv = TableEnvironment.create(ENVIRONMENT_SETTINGS);

        tEnv.useCatalog(null);
        Table table = tEnv.sqlQuery(String.format("SELECT CURRENT_TIMESTAMP;"));

        assertThat(table.getResolvedSchema()).isEqualTo(CURRENT_TIMESTAMP_EXPECTED_SCHEMA);
    }

Line commented on: Table table = tEnv.sqlQuery(String.format("SELECT CURRENT_TIMESTAMP;"));

Revised code:
public void testUnsetCatalogWithSelectCurrentTimestamp() throws Exception {
        TableEnvironment tEnv = TableEnvironment.create(ENVIRONMENT_SETTINGS);

        tEnv.useCatalog(null);
        Table table = tEnv.sqlQuery("SELECT CURRENT_TIMESTAMP");

        assertThat(table.getResolvedSchema()).isEqualTo(CURRENT_TIMESTAMP_EXPECTED_SCHEMA);
    }
Code review comment: ```suggestion         while ((next = lookahead.get()).token == JsonToken.START_ARRAY) { } ```

Code under review:
private static boolean isArrayOfObjects(TokenBuffer buffer) {
        if (buffer.current() != JsonToken.START_ARRAY) return false;
        Supplier<Token> lookahead = buffer.lookahead();
        Token next;
        while ((next = lookahead.get()).token == JsonToken.START_ARRAY);
        return next.token == JsonToken.START_OBJECT;
    }

Line commented on: while ((next = lookahead.get()).token == JsonToken.START_ARRAY);

Revised code:
private static boolean isArrayOfObjects(TokenBuffer buffer) {
        if (buffer.current() != JsonToken.START_ARRAY) return false;
        Supplier<Token> lookahead = buffer.lookahead();
        Token next;
        while ((next = lookahead.get()).token == JsonToken.START_ARRAY) { }
        return next.token == JsonToken.START_OBJECT;
    }
Code review comment: ```suggestion         try {             return valueState.value();         } catch (Exception e) {             throw new RuntimeException("Error while getting value from raw ValueState", e);         } ```

Code under review:
public V value() {
        V value;
        try {
            value = valueState.value();
        } catch (Exception e) {
            throw new RuntimeException("Error while getting value from raw ValueState", e);
        }
        return value;
    }

Line commented on: return value;

Revised code:
public V value() {
        try {
            return valueState.value();
        } catch (Exception e) {
            throw new RuntimeException("Error while getting value from raw ValueState", e);
        }
    }
Code review comment: `checkArgument`?  Your error message can also be simpler - `"%s is not a %s", application.getTransform(), ProcessElements.class.getSimpleName()`

Code under review:
public DoFnLifecycleManager load(final AppliedPTransform<?, ?, ?> application) {
              if (!ProcessElements.class.isInstance(application.getTransform())) {
                throw new IllegalArgumentException(
                  "No know extraction of the fn from " + application);
              }
              final ProcessElements<InputT, OutputT, RestrictionT, TrackerT> transform =
                (ProcessElements<InputT, OutputT, RestrictionT, TrackerT>)
                  application.getTransform();
              final DoFn fn = ProcessElements.class.cast(application.getTransform()).getFn();
              return DoFnLifecycleManager.of(transform.newProcessFn(fn));
            }

Line commented on: "No know extraction of the fn from " + application);

Revised code:
public DoFnLifecycleManager load(final AppliedPTransform<?, ?, ?> application) {
              checkArgument(
                ProcessElements.class.isInstance(application.getTransform()),
                "No know extraction of the fn from " + application);
              final ProcessElements<InputT, OutputT, RestrictionT, TrackerT> transform =
                (ProcessElements<InputT, OutputT, RestrictionT, TrackerT>)
                  application.getTransform();
              return DoFnLifecycleManager.of(transform.newProcessFn(transform.getFn()));
            }
Code review comment: that's a good question, when we originally implemented connection strings, the Portal U/X only included IngestionEndpoint for gov clouds, so the default was important, but now the Portal U/X always includes IngestionEndpoint, so the default is likely not needed anymore. I'll start an internal thread and add you to see if we can find out.

Code under review:
public AzureMonitorExporterBuilder connectionString(String connectionString) {
        this.instrumentationKey = extractValueFromConnectionString(connectionString, "InstrumentationKey");
        this.endpoint(extractValueFromConnectionString(connectionString, "IngestionEndpoint"));
        return this;
    }

Line commented on: return this;

Revised code:
public AzureMonitorExporterBuilder connectionString(String connectionString) {
        Map<String, String> keyValues = extractKeyValuesFromConnectionString(connectionString);
        if (!keyValues.containsKey("InstrumentationKey")) {
            throw logger.logExceptionAsError(
                new IllegalArgumentException("InstrumentationKey not found in connectionString"));
        }
        this.instrumentationKey = keyValues.get("InstrumentationKey");
        String endpoint = keyValues.get("IngestionEndpoint");
        if (endpoint != null) {
            this.endpoint(endpoint);
        }
        return this;
    }
Code review comment: The error log will be printed outside

Code under review:
private void getNewImage(Pair<String, Integer> helperNode) throws IOException {
        long localImageVersion = 0;
        Storage storage = new Storage(this.imageDir);
        localImageVersion = storage.getImageSeq();

        try {
            URL infoUrl = new URL("http:
            StorageInfo info = getStorageInfo(infoUrl);
            long version = info.getImageSeq();
            if (version > localImageVersion) {
                String url = "http:
                        + "/image?version=" + version;
                String filename = Storage.IMAGE + "." + version;
                File dir = new File(this.imageDir);
                MetaHelper.getRemoteFile(url, HTTP_TIMEOUT_SECOND * 1000, MetaHelper.getOutputStream(filename, dir));
                MetaHelper.complete(filename, dir);
            }
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

Line commented on: throw new IOException(e);

Revised code:
private void getNewImage(Pair<String, Integer> helperNode) throws IOException {
        long localImageVersion = 0;
        Storage storage = new Storage(this.imageDir);
        localImageVersion = storage.getImageSeq();

        try {
            URL infoUrl = new URL("http:
            StorageInfo info = getStorageInfo(infoUrl);
            long version = info.getImageSeq();
            if (version > localImageVersion) {
                String url = "http:
                        + "/image?version=" + version;
                String filename = Storage.IMAGE + "." + version;
                File dir = new File(this.imageDir);
                MetaHelper.getRemoteFile(url, HTTP_TIMEOUT_SECOND * 1000, MetaHelper.getOutputStream(filename, dir));
                MetaHelper.complete(filename, dir);
            }
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
Code review comment: no, it just helped me with understanding the paths when debugging test failures. But I can remove it

Code under review:
public void testExistingEmptyDirectoryRecursiveDeletion() throws IOException {
        final Path path = new Path(basePath, "dir-" + randomName());
        fs.mkdirs(path);
        testSuccessfulDeletion(path, true);
    }

Line commented on: final Path path = new Path(basePath, "dir-" + randomName());

Revised code:
public void testExistingEmptyDirectoryRecursiveDeletion() throws IOException {
        final Path path = new Path(basePath, randomName());
        fs.mkdirs(path);
        testSuccessfulDeletion(path, true);
    }