muttakin2301/ccr2000 huggingface dataset:
Code review comment: Made this change to fix CCE for `redeclared variable ANS7` ``` const NUM1 = -1; const int NUM2 = -9223372036854775807 - 1; const int ANS7 = NUM2 - 1;  const int ANS7 = NUM2 + NUM1;  ``` Is that acceptable?

Code under review:
private void checkUniqueness(BLangConstant constant) {
        if (constant.symbol.kind == SymbolKind.CONSTANT) {
            String nameString = constant.name.value;
            BLangConstantValue value = constant.symbol.value;

            if (constantMap.containsKey(nameString)) {
                if (value == null) {
                    dlog.error(constant.name.pos, DiagnosticErrorCode.ALREADY_INITIALIZED_SYMBOL, nameString);
                } else {
                    BLangConstantValue lastValue = constantMap.get(nameString);
                    if (!value.toString().equals(lastValue.toString())) {
                        if (lastValue == null) {
                            dlog.error(constant.name.pos, DiagnosticErrorCode.ALREADY_INITIALIZED_SYMBOL, nameString);
                        } else {
                            dlog.error(constant.name.pos, DiagnosticErrorCode.ALREADY_INITIALIZED_SYMBOL_WITH_ANOTHER,
                                    nameString, lastValue);
                        }
                    }
                }
            } else {
                constantMap.put(nameString, value);
            }
        }
    }

Line commented on: if (!value.toString().equals(lastValue.toString())) {

Revised code:
private void checkUniqueness(BLangConstant constant) {
        if (constant.symbol.kind == SymbolKind.CONSTANT) {
            String nameString = constant.name.value;
            BLangConstantValue value = constant.symbol.value;

            if (constantMap.containsKey(nameString)) {
                if (value == null) {
                    dlog.error(constant.name.pos, DiagnosticErrorCode.ALREADY_INITIALIZED_SYMBOL, nameString);
                } else {
                    BLangConstantValue lastValue = constantMap.get(nameString);
                    if (!value.equals(lastValue)) {
                        if (lastValue == null) {
                            dlog.error(constant.name.pos, DiagnosticErrorCode.ALREADY_INITIALIZED_SYMBOL, nameString);
                        } else {
                            dlog.error(constant.name.pos, DiagnosticErrorCode.ALREADY_INITIALIZED_SYMBOL_WITH_ANOTHER,
                                    nameString, lastValue);
                        }
                    }
                }
            } else {
                constantMap.put(nameString, value);
            }
        }
    }
Code review comment: Add some code comments here ? ```java /* sum = */ ifThenElse(isNull(operands()[0]), sum, minus(sum, operands()[0])), ```

Code under review:
public Expression[] retractExpressions() {
		return new Expression[] {
				ifThenElse(isNull(operands()[0]), sum, minus(sum, operands()[0])),
				ifThenElse(isNull(operands()[0]), count, minus(count, literal(1L))),
		};
	}

Line commented on: ifThenElse(isNull(operands()[0]), sum, minus(sum, operands()[0])),

Revised code:
public Expression[] retractExpressions() {
		return new Expression[] {
				/* sum = */ ifThenElse(isNull(operand(0)), sum, minus(sum, operand(0))),
				/* count = */ ifThenElse(isNull(operand(0)), count, minus(count, literal(1L))),
		};
	}
Code review comment: Hm, nice catch. Shouldn't always trust the IDE's suggested changes it seems. Will fix.

Code under review:
private Optional<String> childAsString(Optional<ModelElement> element, String childTagName) {
            return element.map(modelElement -> modelElement.childAsString(childTagName));
        }

Line commented on: return element.map(modelElement -> modelElement.childAsString(childTagName));

Revised code:
private Optional<String> childAsString(Optional<ModelElement> element, String childTagName) {
            if (element.isEmpty()) return Optional.empty();
            return Optional.ofNullable(element.get().childAsString(childTagName));
        }
Code review comment: Do we need to get the current catalog at this point? You handle that during the execution already, don't you?

Code under review:
public Operation convertSqlNode(SqlShowDatabases sqlShowDatabases, ConvertContext context) {
        if (sqlShowDatabases.getPreposition() == null) {
            return new ShowDatabasesOperation(
                    sqlShowDatabases.getLikeType(),
                    sqlShowDatabases.getLikeSqlPattern(),
                    sqlShowDatabases.isNotLike());
        } else {
            CatalogManager catalogManager = context.getCatalogManager();
            String[] fullCatalogName = sqlShowDatabases.getCatalog();
            String catalogName =
                    fullCatalogName.length == 0
                            ? catalogManager.getCurrentCatalog()
                            : fullCatalogName[0];
            return new ShowDatabasesOperation(
                    sqlShowDatabases.getPreposition(),
                    catalogName,
                    sqlShowDatabases.getLikeType(),
                    sqlShowDatabases.getLikeSqlPattern(),
                    sqlShowDatabases.isNotLike());
        }
    }

Line commented on: : fullCatalogName[0];

Revised code:
public Operation convertSqlNode(SqlShowDatabases sqlShowDatabases, ConvertContext context) {
        if (sqlShowDatabases.getPreposition() == null) {
            return new ShowDatabasesOperation(
                    sqlShowDatabases.getLikeType(),
                    sqlShowDatabases.getLikeSqlPattern(),
                    sqlShowDatabases.isNotLike());
        } else {
            return new ShowDatabasesOperation(
                    sqlShowDatabases.getCatalog()[0],
                    sqlShowDatabases.getLikeType(),
                    sqlShowDatabases.getLikeSqlPattern(),
                    sqlShowDatabases.isNotLike());
        }
    }
Code review comment: ```suggestion             final int cnt = 2 + userToAuthenticationInfo.size() * 2; ```

Code under review:
public void save(DataOutputStream dos) throws IOException {
        try {
            
            final int cnt = 1 + 1 + userToAuthenticationInfo.size() * 2;
            SRMetaBlockWriter writer = new SRMetaBlockWriter(dos, AuthenticationManager.class.getName(), cnt);
            
            writer.writeJson(this);
            
            writer.writeJson(userToAuthenticationInfo.size());
            Iterator<Map.Entry<UserIdentity, UserAuthenticationInfo>> iterator =
                    userToAuthenticationInfo.entrySet().iterator();
            while (iterator.hasNext()) {
                
                Map.Entry<UserIdentity, UserAuthenticationInfo> entry = iterator.next();
                writer.writeJson(entry.getKey());
                writer.writeJson(entry.getValue());
            }
            writer.close();
        } catch (SRMetaBlockException e) {
            IOException exception = new IOException("failed to save AuthenticationManager!");
            exception.initCause(e);
            throw exception;
        }
    }

Line commented on: final int cnt = 1 + 1 + userToAuthenticationInfo.size() * 2;

Revised code:
public void save(DataOutputStream dos) throws IOException {
        try {
            
            final int cnt = 1 + 1 + userToAuthenticationInfo.size() * 2;
            SRMetaBlockWriter writer = new SRMetaBlockWriter(dos, AuthenticationManager.class.getName(), cnt);
            
            writer.writeJson(this);
            
            writer.writeJson(userToAuthenticationInfo.size());
            Iterator<Map.Entry<UserIdentity, UserAuthenticationInfo>> iterator =
                    userToAuthenticationInfo.entrySet().iterator();
            while (iterator.hasNext()) {
                
                Map.Entry<UserIdentity, UserAuthenticationInfo> entry = iterator.next();
                writer.writeJson(entry.getKey());
                writer.writeJson(entry.getValue());
            }
            writer.close();
        } catch (SRMetaBlockException e) {
            IOException exception = new IOException("failed to save AuthenticationManager!");
            exception.initCause(e);
            throw exception;
        }
    }
Code review comment: I think we should gradually refactor existing generated operators. Take `AggregateWindowOperator` as an exmple, every generated class has two objects, e.g. `aggWindowAggregator` and `generatedAggWindowAggregator`, etc.. And they are all nullable, and we have to add a lot of `if else` to compile them in `open` method.   I think if we have a `WindowOperatorFactory`, the logic and member fields will be simpler.

Code under review:
public StreamOperator createStreamOperator(StreamTask containingTask, StreamConfig config, Output output) {
		WatermarkGenerator watermarkGenerator = generatedWatermarkGenerator.newInstance(containingTask.getUserCodeClassLoader());
		WatermarkAssignerOperator operator = new WatermarkAssignerOperator(rowtimeFieldIndex, watermarkGenerator, idleTimeout);
		operator.setup(containingTask, config, output);
		return operator;
	}

Line commented on: WatermarkAssignerOperator operator = new WatermarkAssignerOperator(rowtimeFieldIndex, watermarkGenerator, idleTimeout);

Revised code:
public StreamOperator createStreamOperator(StreamTask containingTask, StreamConfig config, Output output) {
		WatermarkGenerator watermarkGenerator = generatedWatermarkGenerator.newInstance(containingTask.getUserCodeClassLoader());
		WatermarkAssignerOperator operator = new WatermarkAssignerOperator(rowtimeFieldIndex, watermarkGenerator, idleTimeout);
		operator.setup(containingTask, config, output);
		return operator;
	}
Code review comment: Same comment here, need to get rid of this .block() too

Code under review:
public void canDeleteExistingMessage() {
        
        SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions();
        SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block();

        
        StepVerifier.create(chatThreadClient.deleteMessage(response.getId()))
            .verifyComplete();
    }

Line commented on: SendChatMessageResult response = chatThreadClient.sendMessage(messageRequest).block();

Revised code:
public void canDeleteExistingMessage() {
        
        SendChatMessageOptions messageRequest = ChatOptionsProvider.sendMessageOptions();

        
        StepVerifier.create(
            chatThreadClient.sendMessage(messageRequest)
                .flatMap(response -> {
                    return chatThreadClient.deleteMessage(response.getId());
                })
            )
            .verifyComplete();
    }
Code review comment: It may be better to call `TransactionTestConstants.ACCOUNT, 6)` before calling rollback.

Code under review:
private void assertRollback() throws SQLException {
        Connection conn = getDataSource().getConnection();
        conn.setAutoCommit(false);
        assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 0);
        executeWithLog(conn, "insert into account(id, BALANCE, TRANSACTION_ID) values(1, 1, 1),(2, 2, 2),(3, 3, 3),(4, 4, 4),(5, 5, 5),(6, 6, 6);");
        conn.rollback();
        assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 0);
    }

Line commented on: assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 0);

Revised code:
private void assertRollback() throws SQLException {
        Connection conn = getDataSource().getConnection();
        conn.setAutoCommit(false);
        assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 0);
        executeWithLog(conn, "insert into account(id, BALANCE, TRANSACTION_ID) values(1, 1, 1),(2, 2, 2),(3, 3, 3),(4, 4, 4),(5, 5, 5),(6, 6, 6);");
        assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 6);
        conn.rollback();
        assertTableRowCount(conn, TransactionTestConstants.ACCOUNT, 0);
    }
Code review comment: The most risky bug in this code is: The `KuduTable` constructor does not initialize the `properties`, `masterAddresses`, `catalogName`, `databaseName`, `tableName`, and `partColNames` fields which could lead to NullPointerException when accessing these fields.  You can modify the code like this: ```java public KuduTable() {     super(TableType.KUDU);     this.properties = new HashMap<>();     this.masterAddresses = "";     this.catalogName = "";     this.databaseName = "";     this.tableName = "";     this.partColNames = new ArrayList<>(); } ```

Code under review:
public List<String> getPartitionColumnNames() {
        return partColNames;
    }

Line commented on: return partColNames;

Revised code:
public List<String> getPartitionColumnNames() {
        return partColNames;
    }
Code review comment: I think by two steps Kenn meant that we could merge a PR that did not support processing-time timers and then a second PR that added that support.

Code under review:
private void setAndVerifyOutputTimestamp() {
      
      if (outputTimestamp != null && !TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) {
        throw new IllegalStateException("Cannot set outputTimestamp in processing time domain.");
      }
      
      if (outputTimestamp == null) {
        outputTimestamp = target;
      }

      if (TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) {
        Instant windowExpiry = window.maxTimestamp().plus(allowedLateness);
        checkArgument(
            !outputTimestamp.isAfter(windowExpiry),
            "Attempted to set event time timer that outputs for %s but that is"
                + " after the expiration of window %s",
            outputTimestamp,
            windowExpiry);
      }
    }

Line commented on: throw new IllegalStateException("Cannot set outputTimestamp in processing time domain.");

Revised code:
private void setAndVerifyOutputTimestamp() {
      
      if (outputTimestamp != null && !TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) {
        throw new IllegalStateException("Cannot set outputTimestamp in processing time domain.");
      }
      
      if (outputTimestamp == null) {
        outputTimestamp = target;
      }

      if (TimeDomain.EVENT_TIME.equals(spec.getTimeDomain())) {
        Instant windowExpiry = window.maxTimestamp().plus(allowedLateness);
        checkArgument(
            !target.isAfter(windowExpiry),
            "Attempted to set event time timer that outputs for %s but that is"
                + " after the expiration of window %s",
            target,
            windowExpiry);
      }
    }
Code review comment: Are we sure length of payload is not 0 here ?

Code under review:
private static String lowerCaseTheFirstLetter(String payload) {
        char[] characters = payload.toCharArray();
        characters[0] = Character.toLowerCase(characters[0]);
        payload = new String(characters);
        return payload;
    }

Line commented on: characters[0] = Character.toLowerCase(characters[0]);

Revised code:
private static String lowerCaseTheFirstLetter(String payload) {
        if (!payload.isEmpty()) {
            char[] characters = payload.toCharArray();
            characters[0] = Character.toLowerCase(characters[0]);
            payload = new String(characters);
        }
        return payload;
    }
Code review comment: I still don't think this is a real issue. If there is a RESTEasy request is progress then CP will have captured the context, so it should be propagated everywhere and there is no change of behaviour. The only way this will be missing is if a request is started with no request is progress, and then ends up in a RESTEasy request, such as with lazy authentication. This could mean that RESTEasy requests effectively loose their context once they start dealing with the SecurityIdentity, which does not seem ideal IMHO.

Code under review:
public ThreadContextSnapshot currentContext(Map<String, String> props) {
        Map<Class<?>, Object> context = ResteasyContext.getContextDataMap(false);
        if (context == null) {
            return null;
        }
        return () -> {
            ResteasyContext.pushContextDataMap(context);
            return () -> {
                ResteasyContext.removeContextDataLevel();
            };
        };
    }

Line commented on: return null;

Revised code:
public ThreadContextSnapshot currentContext(Map<String, String> props) {
        Map<Class<?>, Object> context = ResteasyContext.getContextDataMap(false);
        if (context == null) {
            return null;
        }
        return () -> {
            ResteasyContext.pushContextDataMap(context);
            return () -> {
                ResteasyContext.removeContextDataLevel();
            };
        };
    }
Code review comment: we can make two sources have same length to achieve the same goal, then to void too many vars.

Code under review:
public void testAccumulateWithCopy() {
		final int firstSourceLength = 128;
		final int firstSourceStartPosition = 32;
		final int secondSourceLength = 64;
		final int secondSourceStartPosition = 0;
		final int expectedAccumulationSize = 128;

		final int firstCopyLength = firstSourceLength - firstSourceStartPosition;
		final int secondCopyLength = expectedAccumulationSize - firstCopyLength;

		ByteBuf firstSource = createSourceBuffer(firstSourceLength, firstSourceStartPosition);
		ByteBuf secondSource = createSourceBuffer(secondSourceLength, secondSourceStartPosition);

		ByteBuf target = Unpooled.buffer(expectedAccumulationSize);

		
		ByteBuf accumulated = ByteBufUtils.accumulate(
			target,
			firstSource,
			expectedAccumulationSize,
			target.readableBytes());
		assertNull(accumulated);
		assertEquals(firstSourceLength, firstSource.readerIndex());
		assertEquals(firstCopyLength, target.readableBytes());

		
		
		accumulated = ByteBufUtils.accumulate(
			target,
			secondSource,
			expectedAccumulationSize,
			target.readableBytes());
		assertSame(target, accumulated);
		assertEquals(secondSourceStartPosition + secondCopyLength, secondSource.readerIndex());
		assertEquals(expectedAccumulationSize, target.readableBytes());

		verifyBufferContent(accumulated, 0, firstCopyLength, firstSourceStartPosition);
		verifyBufferContent(accumulated, firstCopyLength, secondCopyLength, secondSourceStartPosition);
	}

Line commented on: final int secondSourceLength = 64;

Revised code:
public void testAccumulateWithCopy() {
		int sourceLength = 128;
		int firstSourceReaderIndex = 32;
		int secondSourceReaderIndex = 0;
		int expectedAccumulationSize = 128;

		int firstAccumulationSize = sourceLength - firstSourceReaderIndex;
		int secondAccumulationSize = expectedAccumulationSize - firstAccumulationSize;

		ByteBuf firstSource = createSourceBuffer(sourceLength, firstSourceReaderIndex, firstAccumulationSize);
		ByteBuf secondSource = createSourceBuffer(sourceLength, secondSourceReaderIndex, secondAccumulationSize);

		ByteBuf target = Unpooled.buffer(expectedAccumulationSize);

		
		ByteBuf accumulated = ByteBufUtils.accumulate(
			target,
			firstSource,
			expectedAccumulationSize,
			target.readableBytes());
		assertNull(accumulated);
		assertEquals(sourceLength, firstSource.readerIndex());
		assertEquals(firstAccumulationSize, target.readableBytes());

		
		
		accumulated = ByteBufUtils.accumulate(
			target,
			secondSource,
			expectedAccumulationSize,
			target.readableBytes());
		assertSame(target, accumulated);
		assertEquals(secondSourceReaderIndex + secondAccumulationSize, secondSource.readerIndex());
		assertEquals(expectedAccumulationSize, target.readableBytes());

		verifyBufferContent(accumulated, 0, expectedAccumulationSize);
	}
Code review comment: ``` if (dataType.hasPriority() || dataType.requiresAnnouncement()) {   firstPriorityEvent = addPriorityBuffer(announce(sequenceBuffer)); } if (!dataType.hasPriority()) {   receivedBuffers.add(sequenceBuffer);   channelStatePersister.maybePersist(buffer); } ```

Code under review:
public void onBuffer(Buffer buffer, int sequenceNumber, int backlog) throws IOException {
		boolean recycleBuffer = true;

		try {
			if (expectedSequenceNumber != sequenceNumber) {
				onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber));
				return;
			}

			final boolean wasEmpty;
			boolean firstPriorityEvent = false;
			synchronized (receivedBuffers) {
				
				
				
				if (isReleased.get()) {
					return;
				}

				wasEmpty = receivedBuffers.isEmpty();

				SequenceBuffer sequenceBuffer = new SequenceBuffer(buffer, sequenceNumber);
				DataType dataType = buffer.getDataType();
				if (dataType.hasPriority()) {
					checkPriorityXorAnnouncement(buffer);
					firstPriorityEvent = addPriorityBuffer(sequenceBuffer);
				} else {
					receivedBuffers.add(sequenceBuffer);
					channelStatePersister.maybePersist(buffer);

					if (dataType.requiresAnnouncement()) {
						checkPriorityXorAnnouncement(buffer);
						firstPriorityEvent = addPriorityBuffer(announce(sequenceBuffer));
					}
				}
				++expectedSequenceNumber;
			}
			recycleBuffer = false;

			if (firstPriorityEvent) {
				notifyPriorityEvent(sequenceNumber);
			}
			if (wasEmpty) {
				notifyChannelNonEmpty();
			}

			if (backlog >= 0) {
				onSenderBacklog(backlog);
			}
		} finally {
			if (recycleBuffer) {
				buffer.recycleBuffer();
			}
		}
	}

Line commented on: checkPriorityXorAnnouncement(buffer);

Revised code:
public void onBuffer(Buffer buffer, int sequenceNumber, int backlog) throws IOException {
		boolean recycleBuffer = true;

		try {
			if (expectedSequenceNumber != sequenceNumber) {
				onError(new BufferReorderingException(expectedSequenceNumber, sequenceNumber));
				return;
			}

			final boolean wasEmpty;
			boolean firstPriorityEvent = false;
			synchronized (receivedBuffers) {
				
				
				
				if (isReleased.get()) {
					return;
				}

				wasEmpty = receivedBuffers.isEmpty();

				SequenceBuffer sequenceBuffer = new SequenceBuffer(buffer, sequenceNumber);
				DataType dataType = buffer.getDataType();
				if (dataType.hasPriority()) {
					firstPriorityEvent = addPriorityBuffer(sequenceBuffer);
				}
				else {
					receivedBuffers.add(sequenceBuffer);
					channelStatePersister.maybePersist(buffer);
					if (dataType.requiresAnnouncement()) {
						firstPriorityEvent = addPriorityBuffer(announce(sequenceBuffer));
					}
				}
				++expectedSequenceNumber;
			}
			recycleBuffer = false;

			if (firstPriorityEvent) {
				notifyPriorityEvent(sequenceNumber);
			}
			if (wasEmpty) {
				notifyChannelNonEmpty();
			}

			if (backlog >= 0) {
				onSenderBacklog(backlog);
			}
		} finally {
			if (recycleBuffer) {
				buffer.recycleBuffer();
			}
		}
	}
Code review comment: I didn't pay attention, tbh. I'll add the brackets.

Code under review:
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.equals(root) || dir.toString().equals("/") || dir.startsWith(devTemplatesPath))
                    return FileVisitResult.CONTINUE;
                return FileVisitResult.SKIP_SUBTREE;
            }

Line commented on: if (dir.equals(root) || dir.toString().equals("/") || dir.startsWith(devTemplatesPath))

Revised code:
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                if (dir.equals(root) || dir.toString().equals("/") || dir.startsWith(devTemplatesPath)) {
                    return FileVisitResult.CONTINUE;
                }
                return FileVisitResult.SKIP_SUBTREE;
            }
Code review comment: AvroUtils.toAvroSchema() method provides an avroSchema from the BeamSchema.  But the avroSchema geenrated does not have the name of the  avroSchema.  Now when I use this avroSchema (without the name) to write/read records it fails with error        SchemaParseException: No name in schema: {"type":"record","fields": ... } 	   So I had to provide the name for the schema, I have provided the same using the tableName.

Code under review:
public PDone buildIOWriter(PCollection<Row> input) {
    PTransform<PCollection<Row>, PCollection<GenericRecord>> writeConverter =
        GenericRecordWriteConverter.builder().beamSchema(schema).build();

    return input
        .apply("GenericRecordToRow", writeConverter)
        .apply(
            "AvroIOWrite",
            AvroIO.writeGenericRecords(AvroUtils.toAvroSchema(schema, tableName, null))
                .to(filePattern)
                .withoutSharding());
  }

Line commented on: AvroIO.writeGenericRecords(AvroUtils.toAvroSchema(schema, tableName, null))

Revised code:
public PDone buildIOWriter(PCollection<Row> input) {
    PTransform<PCollection<Row>, PCollection<GenericRecord>> writeConverter =
        GenericRecordWriteConverter.builder().beamSchema(schema).build();

    return input
        .apply("GenericRecordToRow", writeConverter)
        .apply(
            "AvroIOWrite",
            AvroIO.writeGenericRecords(AvroUtils.toAvroSchema(schema, tableName, null))
                .to(filePattern)
                .withoutSharding());
  }
Code review comment: LOG.warn("Exception: {} does not exist", dbName, e);

Code under review:
public void removeDatabase(String dbName) {
        if (closing) {
            return;
        }

        try {
            LOG.info("begin to remove database {} from replicatedEnviroment", dbName);
            
            replicatedEnvironment.removeDatabase(null, dbName);
            LOG.info("remove database {} from replicatedEnviroment successfully", dbName);
        } catch (DatabaseNotFoundException e) {
            LOG.warn("catch an exception when remove db:{}, this db does not exist", dbName, e);
        }
    }

Line commented on: LOG.warn("catch an exception when remove db:{}, this db does not exist", dbName, e);

Revised code:
public void removeDatabase(String dbName) {
        if (closing) {
            return;
        }

        try {
            
            replicatedEnvironment.removeDatabase(null, dbName);
            LOG.info("remove database {} from replicatedEnviroment successfully", dbName);
        } catch (DatabaseNotFoundException e) {
            LOG.warn("Exception: {} does not exist", dbName, e);
        }
    }
Code review comment: super() should be first in method

Code under review:
protected void doPrepare(DeployState deployState) {
        addAndSendApplicationBundles(deployState);
        sendUserConfiguredFiles(deployState);
        createEndpointList(deployState);
        super.doPrepare(deployState);
    }

Line commented on: super.doPrepare(deployState);

Revised code:
protected void doPrepare(DeployState deployState) {
        super.doPrepare(deployState);
        addAndSendApplicationBundles(deployState);
        sendUserConfiguredFiles(deployState);
        createEndpointList(deployState);
    }
Code review comment: Precicely, I wanted to use the same exact keys as Spring Boot does for the benefit of users who might want to migrate.

Code under review:
InfoBuildTimeValuesBuildItem buildInfo(CurateOutcomeBuildItem curateOutcomeBuildItem, InfoBuildTimeConfig config) {
        ApplicationModel applicationModel = curateOutcomeBuildItem.getApplicationModel();
        ResolvedDependency appArtifact = applicationModel.getAppArtifact();
        Map<String, Object> buildData = new LinkedHashMap<>();
        buildData.put("group", appArtifact.getGroupId());
        buildData.put("artifact", appArtifact.getArtifactId());
        buildData.put("version", appArtifact.getVersion());
        buildData.put("time", ISO_OFFSET_DATE_TIME.format(OffsetDateTime.now())); 
        return new InfoBuildTimeValuesBuildItem("build", finalBuildData(buildData, config.build()));
    }

Line commented on: buildData.put("artifact", appArtifact.getArtifactId());

Revised code:
InfoBuildTimeValuesBuildItem buildInfo(CurateOutcomeBuildItem curateOutcomeBuildItem, InfoBuildTimeConfig config) {
        ApplicationModel applicationModel = curateOutcomeBuildItem.getApplicationModel();
        ResolvedDependency appArtifact = applicationModel.getAppArtifact();
        Map<String, Object> buildData = new LinkedHashMap<>();
        buildData.put("group", appArtifact.getGroupId());
        buildData.put("artifact", appArtifact.getArtifactId());
        buildData.put("version", appArtifact.getVersion());
        buildData.put("time", ISO_OFFSET_DATE_TIME.format(OffsetDateTime.now())); 
        return new InfoBuildTimeValuesBuildItem("build", finalBuildData(buildData, config.build()));
    }
Code review comment: ```suggestion             childAccessPaths.stream().distinct() ``` and add some comment?

Code under review:
private Optional<AccessPath> process(ScalarOperator scalarOperator, Deque<AccessPath> accessPaths) {
            
            List<Optional<AccessPath>> childAccessPaths = scalarOperator.getChildren().stream()
                    .map(child -> process(child, accessPaths))
                    .collect(Collectors.toList());
            
            
            if (!childAccessPaths.isEmpty() && childAccessPaths.stream().noneMatch(Optional::isPresent)) {
                return Optional.empty();
            }
            Optional<AccessPath> currentPath = scalarOperator.accept(this, childAccessPaths);
            AccessPath path = currentPath.orElse(null);
            childAccessPaths.stream().filter(p -> p.isPresent() && p.get() != path)
                    .map(Optional::get).forEach(accessPaths::add);
            return currentPath;
        }

Line commented on: childAccessPaths.stream().filter(p -> p.isPresent() && p.get() != path)

Revised code:
private Optional<AccessPath> process(ScalarOperator scalarOperator, Deque<AccessPath> accessPaths) {
            
            List<Optional<AccessPath>> childAccessPaths = scalarOperator.getChildren().stream()
                    .map(child -> process(child, accessPaths))
                    .collect(Collectors.toList());
            
            
            if (!childAccessPaths.isEmpty() && childAccessPaths.stream().noneMatch(Optional::isPresent)) {
                return Optional.empty();
            }
            Optional<AccessPath> currentPath = scalarOperator.accept(this, childAccessPaths);
            AccessPath path = currentPath.orElse(null);
            
            
            
            
            
            childAccessPaths.stream().filter(p -> p.isPresent() && p.get() != path)
                    .map(Optional::get).forEach(accessPaths::add);
            return currentPath;
        }
Code review comment: If you look at the comments you see this can not be used for anything machine readable.      * If length is 4 or less the string will be truncated to length.      * If length is longer than 4, it will be truncated at length-4 with " ..." added at the end.  We have a lot of public methods that we have only added for our own convenience, and this looks like one of them.  And the change we are making here will already change change something, that is just a theoretical difference. The only value it add over s.substring(), is the optional padding with "...".

Code under review:
public boolean annotate(StringFieldValue text) {
        if (text.getSpanTree(SpanTrees.LINGUISTICS) != null) return true;  

        Tokenizer tokenizer = factory.getTokenizer();
        String input = (text.getString().length() <= config.getMaxTokenizeLength())
                ? text.getString()
                : Text.safeSubstring(text.getString(), config.getMaxTokenizeLength());
        Iterable<Token> tokens = tokenizer.tokenize(input, config.getLanguage(), config.getStemMode(),
                                                    config.getRemoveAccents());
        TermOccurrences termOccurrences = new TermOccurrences(config.getMaxTermOccurrences());
        SpanTree tree = new SpanTree(SpanTrees.LINGUISTICS);
        for (Token token : tokens)
            addAnnotationSpan(text.getString(), tree.spanList(), token, config.getStemMode(), termOccurrences);

        if (tree.numAnnotations() == 0) return false;
        text.setSpanTree(tree);
        return true;
    }

Line commented on: : Text.safeSubstring(text.getString(), config.getMaxTokenizeLength());

Revised code:
public boolean annotate(StringFieldValue text) {
        if (text.getSpanTree(SpanTrees.LINGUISTICS) != null) return true;  

        Tokenizer tokenizer = factory.getTokenizer();
        String input = (text.getString().length() <= config.getMaxTokenizeLength())
                ? text.getString()
                : Text.substringByCodepoints(text.getString(), 0, config.getMaxTokenizeLength());
        Iterable<Token> tokens = tokenizer.tokenize(input, config.getLanguage(), config.getStemMode(),
                                                    config.getRemoveAccents());
        TermOccurrences termOccurrences = new TermOccurrences(config.getMaxTermOccurrences());
        SpanTree tree = new SpanTree(SpanTrees.LINGUISTICS);
        for (Token token : tokens)
            addAnnotationSpan(text.getString(), tree.spanList(), token, config.getStemMode(), termOccurrences);

        if (tree.numAnnotations() == 0) return false;
        text.setSpanTree(tree);
        return true;
    }
Code review comment: Why don't we have a static variable for this one?

Code under review:
public void validateUserGroupProperties() {
        if (this.sessionStateless) {
            if (allowedGroupsConfigured()) {
                LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'.");
            }
        } else if (!allowedGroupsConfigured()) {
            throw new IllegalArgumentException("One of the User Group Properties must be populated. "
                + "Please populate azure.activedirectory.user-group.allowed-groups");
        }
        if (!DEFAULT_GROUP_RELATIONSHIP.equalsIgnoreCase(groupRelationship)
            && !"transitive".equalsIgnoreCase(groupRelationship)) {
            throw new IllegalArgumentException("Configuration 'azure.activedirectory.group-relationship' "
                + "should be 'direct' or 'transitive'.");
        }
    }

Line commented on: && !"transitive".equalsIgnoreCase(groupRelationship)) {

Revised code:
public void validateUserGroupProperties() {
        if (this.sessionStateless) {
            if (allowedGroupsConfigured()) {
                LOGGER.warn("Group names are not supported if you set 'sessionSateless' to 'true'.");
            }
        } else if (!allowedGroupsConfigured()) {
            throw new IllegalArgumentException("One of the User Group Properties must be populated. "
                + "Please populate azure.activedirectory.user-group.allowed-groups");
        }
        if (!GROUP_RELATIONSHIP_DIRECT.equalsIgnoreCase(userGroup.groupRelationship)
            && !GROUP_RELATIONSHIP_TRANSITIVE.equalsIgnoreCase(userGroup.groupRelationship)) {
            throw new IllegalArgumentException("Configuration 'azure.activedirectory.user-group.group-relationship' "
                + "should be 'direct' or 'transitive'.");
        }
    }
Code review comment: Add it into method Javadoc please

Code under review:
public SerializationProxy(Read read) {
        configuration = read.configuration;
        tableId = read.tableId;
        scan = read.scan;
      }

Line commented on: configuration = read.configuration;

Revised code:
public SerializationProxy(Read read) {
        configuration = read.configuration;
        tableId = read.tableId;
        scan = read.scan;
      }
Code review comment: Consider including the exception in the log entry (so that the stack trace is printed to the log).

Code under review:
private JsonResponse v1Response(URI requestUri) {
        try {
            return new JsonResponse(OK, v1Content(requestUri));
        } catch (JSONException e) {
            log.warning("Bad JSON construction in " + V1_PATH +  " response: " + e.getMessage());
            return new ErrorResponse(INTERNAL_SERVER_ERROR,
                                     "An error occurred, please try path '" + VALUES_PATH + "'");
        }
    }

Line commented on: log.warning("Bad JSON construction in " + V1_PATH +  " response: " + e.getMessage());

Revised code:
private JsonResponse v1Response(URI requestUri) {
        try {
            return new JsonResponse(OK, v1Content(requestUri));
        } catch (JSONException e) {
            log.warning("Bad JSON construction in " + V1_PATH +  " response: " + e.getMessage());
            return new ErrorResponse(INTERNAL_SERVER_ERROR,
                                     "An error occurred, please try path '" + VALUES_PATH + "'");
        }
    }
Code review comment: It does not get invoked when the deprecated params doc is not available. So null check is removed

Code under review:
public void exitDeprecatedParametersDocumentation(BallerinaParser.DeprecatedParametersDocumentationContext ctx) {
        if (isInErrorState) {
            return;
        }
        String str = ctx.DeprecatedParametersDocumentation() != null ?
                ctx.DeprecatedParametersDocumentation().getText() : "";
        this.pkgBuilder.endDeprecatedParametersDocumentation(getCurrentPos(ctx.getParent()), getWS(ctx), str);
    }

Line commented on: String str = ctx.DeprecatedParametersDocumentation() != null ?

Revised code:
public void exitDeprecatedParametersDocumentation(BallerinaParser.DeprecatedParametersDocumentationContext ctx) {
        if (isInErrorState) {
            return;
        }
        this.pkgBuilder.endDeprecatedParametersDocumentation(getCurrentPos(ctx.getParent()), getWS(ctx));
    }
Code review comment: ``` "storage_medium" = "SSD" is not need ``` If the BE not specified the SSD, you will can not create table successfully.

Code under review:
void createTable() throws SQLException {
            runSql(db,
                    "create table " + table +
                            " ( pk bigint NOT NULL, v0 string not null) primary KEY (pk) DISTRIBUTED BY HASH(pk) BUCKETS " +
                            numTablet + " PROPERTIES(\"replication_num\" = \"" + replicationNum +
                            "\", \"storage_medium\" = \"SSD\");");
        }

Line commented on: "\", \"storage_medium\" = \"SSD\");");

Revised code:
void createTable() throws SQLException {
            runSql(db,
                    "create table " + table +
                            " ( pk bigint NOT NULL, v0 string not null) primary KEY (pk) DISTRIBUTED BY HASH(pk) BUCKETS " +
                            numTablet + " PROPERTIES(\"replication_num\" = \"" + replicationNum +
                            "\", \"storage_medium\" = \"SSD\");");
        }
Code review comment: It's just to remove the unecessary autoboxing, since you're comparing primitives here, but it's not that relevant anyway

Code under review:
void mapsWithBase() {
        assertEquals("localhost", mapsWithBase.server().get("host"));
        assertEquals(8080, Integer.valueOf(mapsWithBase.server().get("port")));

        assertEquals("localhost", mapsWithBase.group().get("server").host());
        assertEquals(8080, mapsWithBase.group().get("server").port());
    }

Line commented on: assertEquals(8080, Integer.valueOf(mapsWithBase.server().get("port")));

Revised code:
void mapsWithBase() {
        assertEquals("localhost", mapsWithBase.server().get("host"));
        assertEquals(8080, Integer.valueOf(mapsWithBase.server().get("port")));

        assertEquals("localhost", mapsWithBase.group().get("server").host());
        assertEquals(8080, mapsWithBase.group().get("server").port());
    }
Code review comment: "availability" in resolver means that tracked remote repository (by repoID) is available in the context artifact is asked for. So "remote" may come in as "remote repo ID is available in current context asking for artifact" :)

Code under review:
public void testValidTailFromRemoteIgnoringAvailabilityViaSystemPropBlank() throws Exception {
        setSystemProp("maven.repo.local.tail.ignoreAvailability", " "); 
        final BootstrapMavenContext mvn = bootstrapMavenContextForProject("workspace-with-local-repo-tail",
                BootstrapMavenContext.config()
                        .setLocalRepositoryTail(new String[] { M2_FROM_REMOTE }));

        assertNotNull(resolveOrgAcmeFooJar001(mvn));
    }

Line commented on: assertNotNull(resolveOrgAcmeFooJar001(mvn));

Revised code:
public void testValidTailFromRemoteIgnoringAvailabilityViaSystemPropBlank() throws Exception {
        setSystemProp("maven.repo.local.tail.ignoreAvailability", " "); 
        final BootstrapMavenContext mvn = bootstrapMavenContextForProject("workspace-with-local-repo-tail",
                BootstrapMavenContext.config()
                        .setLocalRepositoryTail(new String[] { M2_FROM_REMOTE }));

        assertNotNull(resolveOrgAcmeFooJar001(mvn));
    }
Code review comment: Do we have any numbers that indicate disabling `TCP_NODELAY` is worth it? We unconditionally enabled nodelay for everything to get rid  of spurious latency spikes incurred by the in-kernel deferred packet sending.

Code under review:
public Connection(TransportThread parent, Supervisor owner, Spec spec, Object context, boolean tcpNoDelay) {
        super(context);
        this.parent = parent;
        this.owner = owner;
        this.spec = spec;
        this.tcpNoDelay = tcpNoDelay;
        server = false;
        owner.sessionInit(this);
    }

Line commented on: this.tcpNoDelay = tcpNoDelay;

Revised code:
public Connection(TransportThread parent, Supervisor owner, Spec spec, Object context, boolean tcpNoDelay) {
        super(context);
        this.parent = parent;
        this.owner = owner;
        this.spec = spec;
        this.tcpNoDelay = tcpNoDelay;
        server = false;
        owner.sessionInit(this);
    }
Code review comment: If it is something non-trivial and hard to make a call about, I would propose to skip this refactoring for now.

Code under review:
public void startCluster() throws ClusterEntrypointException {
		LOG.info("Starting {}.", getClass().getSimpleName());

		try {
			
			PluginManager pluginManager = PluginUtils.createPluginManagerFromRootFolder(configuration);
			configureFileSystems(configuration, pluginManager);

			SecurityContext securityContext = installSecurityContext(configuration);

			securityContext.runSecured((Callable<Void>) () -> {
				runCluster(configuration, pluginManager);

				return null;
			});
		} catch (Throwable t) {
			final Throwable strippedThrowable = ExceptionUtils.stripException(t, UndeclaredThrowableException.class);

			try {
				
				shutDownAsync(
					ApplicationStatus.FAILED,
					ExceptionUtils.stringifyException(strippedThrowable),
					false).get(INITIALIZATION_SHUTDOWN_TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
			} catch (InterruptedException | ExecutionException | TimeoutException e) {
				strippedThrowable.addSuppressed(e);
			}

			throw new ClusterEntrypointException(
				String.format("Failed to initialize the cluster entrypoint %s.", getClass().getSimpleName()),
				strippedThrowable);
		}
	}


Revised code:
public void startCluster() throws ClusterEntrypointException {
		LOG.info("Starting {}.", getClass().getSimpleName());

		try {
			PluginManager pluginManager = PluginUtils.createPluginManagerFromRootFolder(configuration);
			configureFileSystems(configuration, pluginManager);

			SecurityContext securityContext = installSecurityContext(configuration);

			securityContext.runSecured((Callable<Void>) () -> {
				runCluster(configuration, pluginManager);

				return null;
			});
		} catch (Throwable t) {
			final Throwable strippedThrowable = ExceptionUtils.stripException(t, UndeclaredThrowableException.class);

			try {
				
				shutDownAsync(
					ApplicationStatus.FAILED,
					ExceptionUtils.stringifyException(strippedThrowable),
					false).get(INITIALIZATION_SHUTDOWN_TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS);
			} catch (InterruptedException | ExecutionException | TimeoutException e) {
				strippedThrowable.addSuppressed(e);
			}

			throw new ClusterEntrypointException(
				String.format("Failed to initialize the cluster entrypoint %s.", getClass().getSimpleName()),
				strippedThrowable);
		}
	}
Code review comment: Sure, I added a link to the Cloud docs about specifying pipeline options. This generalizes across different languages and is a good how-to guide.

Code under review:
public void logHotKeyDetection(String userStepName, Duration hotKeyAge) {
    if (isThrottled()) {
      return;
    }
    LOG.warn(
        "A hot key was detected in step '{}' with age of '{}'. This is "
            + "a symptom of key distribution being skewed. To fix, please inspect your data and "
            + "pipeline to ensure that elements are evenly distributed across your key space. If "
            + "you want to log the plain-text key to Cloud Logging please re-run with the "
            + "`hotKeyLoggingEnabled` pipeline option.",
        userStepName,
        TimeUtil.toCloudDuration(hotKeyAge));
  }

Line commented on: + "`hotKeyLoggingEnabled` pipeline option.",

Revised code:
public void logHotKeyDetection(String userStepName, Duration hotKeyAge) {
    if (isThrottled()) {
      return;
    }
    LOG.warn(
        "A hot key was detected in step '{}' with age of '{}'. This is "
            + "a symptom of key distribution being skewed. To fix, please inspect your data and "
            + "pipeline to ensure that elements are evenly distributed across your key space. If "
            + "you want to log the plain-text key to Cloud Logging please re-run with the "
            + "`hotKeyLoggingEnabled` pipeline option. See "
            + "https:
            + "information.",
        userStepName,
        TimeUtil.toCloudDuration(hotKeyAge));
  }
Code review comment: if you have just `resteasy` or `spring` then there is no problem :)

Code under review:
public QuarkusCommandOutcome execute() throws QuarkusCommandException {
        
        Matcher matcher = JAVA_VERSION_PATTERN
                .matcher(this.javaTarget != null ? this.javaTarget : System.getProperty("java.version", ""));
        if (matcher.matches() && Integer.parseInt(matcher.group(1)) < 11) {
            setValue(JAVA_TARGET, "8");
        } else {
            setValue(JAVA_TARGET, "11");
        }
        if (containsSpringWeb(extensions)) {
            setValue(IS_SPRING, true);
            if (containsRESTEasy(extensions)) {
                values.remove(CLASS_NAME);
                values.remove(PACKAGE_NAME);
                values.remove(RESOURCE_PATH);
            }
        }
        setValue(EXTENSIONS, extensions);
        final QuarkusProject quarkusProject = QuarkusProject.of(projectDirPath, platformDescr, buildTool);
        final QuarkusCommandInvocation invocation = new QuarkusCommandInvocation(quarkusProject, values);
        if (legacyCodegen) {
            return new LegacyCreateProjectCommandHandler().execute(invocation);
        }
        return new CreateProjectCommandHandler().execute(invocation);
    }

Line commented on: values.remove(RESOURCE_PATH);

Revised code:
public QuarkusCommandOutcome execute() throws QuarkusCommandException {
        
        Matcher matcher = JAVA_VERSION_PATTERN
                .matcher(this.javaTarget != null ? this.javaTarget : System.getProperty("java.version", ""));
        if (matcher.matches() && Integer.parseInt(matcher.group(1)) < 11) {
            setValue(JAVA_TARGET, "8");
        } else {
            setValue(JAVA_TARGET, "11");
        }
        if (containsSpringWeb(extensions)) {
            setValue(IS_SPRING, true);
            if (containsRESTEasy(extensions)) {
                values.remove(CLASS_NAME);
                values.remove(PACKAGE_NAME);
                values.remove(RESOURCE_PATH);
            }
        }
        setValue(EXTENSIONS, extensions);
        final QuarkusProject quarkusProject = QuarkusProject.of(projectDirPath, platformDescr, buildTool);
        final QuarkusCommandInvocation invocation = new QuarkusCommandInvocation(quarkusProject, values);
        if (legacyCodegen) {
            return new LegacyCreateProjectCommandHandler().execute(invocation);
        }
        return new CreateProjectCommandHandler().execute(invocation);
    }