muttakin2301/ccr_train_1000 huggingface dataset:
Code review comment: The 10MB is a soft-limit as that seems large enough to get efficiency wins of batching over rpcs while keeping things more granular for paging in later. But for the dataflow streaming backend there is a hard-limit of 100MB.  Incoming elements can be up to that limit, so if those elements are directly written to a bag I want to ensure we don't batch beyond that.  I will add some comments

Code before review:
public void asyncClose() throws Exception {
checkState(
!isClosed,
"Bag user state is no longer usable because it is closed for %s",
request.getStateKey());
isClosed = true;
if (!isCleared && newValues.isEmpty()) {
return;
}
if (isCleared) {
beamFnStateClient.handle(
request.toBuilder().setClear(StateClearRequest.getDefaultInstance()));
}
if (!newValues.isEmpty()) {
ByteStringOutputStream out = new ByteStringOutputStream();
for (T newValue : newValues) {
int previousSize = out.size();
valueCoder.encode(newValue, out);
if (out.size() > BAG_APPEND_BATCHING_LIMIT && previousSize > 0) {
beamFnStateClient.handle(
request
.toBuilder()
.setAppend(
StateAppendRequest.newBuilder()
.setData(out.consumePrefixToByteString(previousSize))));
}
if (out.size() > BAG_APPEND_BATCHING_LIMIT) {
beamFnStateClient.handle(
request
.toBuilder()
.setAppend(StateAppendRequest.newBuilder().setData(out.toByteStringAndReset())));
}
}
if (out.size() > 0) {
beamFnStateClient.handle(
request
.toBuilder()
.setAppend(StateAppendRequest.newBuilder().setData(out.toByteStringAndReset())));
}
}
if (isCleared) {
oldValues.clearAndAppend(newValues);
} else {
oldValues.append(newValues);
}
}

Line under review: if (out.size() > BAG_APPEND_BATCHING_LIMIT) {

Code after addressing the review:
public void asyncClose() throws Exception {
checkState(
!isClosed,
"Bag user state is no longer usable because it is closed for %s",
request.getStateKey());
isClosed = true;
if (!isCleared && newValues.isEmpty()) {
return;
}
if (isCleared) {
beamFnStateClient.handle(
request.toBuilder().setClear(StateClearRequest.getDefaultInstance()));
}
if (!newValues.isEmpty()) {
ByteStringOutputStream out = new ByteStringOutputStream();
for (T newValue : newValues) {
int previousSize = out.size();
valueCoder.encode(newValue, out);
if (out.size() > BAG_APPEND_BATCHING_LIMIT && previousSize > 0) {
beamFnStateClient.handle(
request
.toBuilder()
.setAppend(
StateAppendRequest.newBuilder()
.setData(out.consumePrefixToByteString(previousSize))));
}
if (out.size() > BAG_APPEND_BATCHING_LIMIT) {
beamFnStateClient.handle(
request
.toBuilder()
.setAppend(StateAppendRequest.newBuilder().setData(out.toByteStringAndReset())));
}
}
if (out.size() > 0) {
beamFnStateClient.handle(
request
.toBuilder()
.setAppend(StateAppendRequest.newBuilder().setData(out.toByteStringAndReset())));
}
}
if (isCleared) {
oldValues.clearAndAppend(newValues);
} else {
oldValues.append(newValues);
}
}
Code review comment: Removed `println`.

Code before review:
public void testNettyClientConnectRetryMultipleThread() throws Exception {
NettyTestUtil.NettyServerAndClient serverAndClient = createNettyServerAndClient();
UnstableNettyClient unstableNettyClient = new UnstableNettyClient(serverAndClient.client(), 2);
PartitionRequestClientFactory factory = new PartitionRequestClientFactory(unstableNettyClient, 2);
ConnectionID serverAddress = new ConnectionID(new InetSocketAddress(InetAddress.getLocalHost(),
serverAndClient.server().getConfig().getServerPort()), 0);
ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(10);
List<Future<NettyPartitionRequestClient>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<NettyPartitionRequestClient> future = threadPoolExecutor.submit(new Callable<NettyPartitionRequestClient>() {
@Override
public NettyPartitionRequestClient call() {
NettyPartitionRequestClient client = null;
try {
client = factory.createPartitionRequestClient(serverAddress);
} catch (Exception e) {
System.out.println(e.getMessage());
fail();
}
return client;
}
});
futures.add(future);
}
futures.forEach(runnableFuture -> {
NettyPartitionRequestClient client = null;
try {
client = runnableFuture.get();
System.out.println("Result = " + client == null ? "null" : client.toString());
assertNotNull(client);
} catch (Exception e) {
System.out.println(e.getMessage());
fail();
}
});
threadPoolExecutor.shutdown();
serverAndClient.client().shutdown();
serverAndClient.server().shutdown();
}

Line under review: try {

Code after addressing the review:
public void testNettyClientConnectRetryMultipleThread() throws Exception {
NettyTestUtil.NettyServerAndClient serverAndClient = createNettyServerAndClient();
UnstableNettyClient unstableNettyClient = new UnstableNettyClient(serverAndClient.client(), 2);
PartitionRequestClientFactory factory = new PartitionRequestClientFactory(unstableNettyClient, 2);
ConnectionID serverAddress = new ConnectionID(new InetSocketAddress(InetAddress.getLocalHost(),
serverAndClient.server().getConfig().getServerPort()), 0);
ExecutorService threadPoolExecutor = Executors.newFixedThreadPool(10);
List<Future<NettyPartitionRequestClient>> futures = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Future<NettyPartitionRequestClient> future = threadPoolExecutor.submit(new Callable<NettyPartitionRequestClient>() {
@Override
public NettyPartitionRequestClient call() {
NettyPartitionRequestClient client = null;
try {
client = factory.createPartitionRequestClient(serverAddress);
} catch (Exception e) {
fail(e.getMessage());
}
return client;
}
});
futures.add(future);
}
futures.forEach(runnableFuture -> {
NettyPartitionRequestClient client = null;
try {
client = runnableFuture.get();
assertNotNull(client);
} catch (Exception e) {
System.out.println(e.getMessage());
fail();
}
});
threadPoolExecutor.shutdown();
serverAndClient.client().shutdown();
serverAndClient.server().shutdown();
}
Code review comment: I updated the PR to check for the classes' presence in the classpath instead. 

Code before review:
private void registerCompulsoryClasses(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, StreamsPartitionAssignor.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, DefaultProductionExceptionHandler.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, FailOnInvalidTimestamp.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, true,
org.apache.kafka.streams.processor.internals.assignment.HighAvailabilityTaskAssignor.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, true,
org.apache.kafka.streams.processor.internals.assignment.StickyTaskAssignor.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, true,
org.apache.kafka.streams.processor.internals.assignment.FallbackPriorTaskAssignor.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, true,
"org.apache.kafka.streams.processor.internals.StateDirectory$StateDirectoryProcessFile"));
}

Line under review: reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, DefaultProductionExceptionHandler.class));

Code after addressing the review:
private void registerCompulsoryClasses(BuildProducer<ReflectiveClassBuildItem> reflectiveClasses) {
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, StreamsPartitionAssignor.class));
if (QuarkusClassLoader.isClassPresentAtRuntime(DEFAULT_PARTITION_GROUPER)) {
reflectiveClasses.produce(
new ReflectiveClassBuildItem(true, false, false, DEFAULT_PARTITION_GROUPER));
}
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, DefaultProductionExceptionHandler.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, false, false, FailOnInvalidTimestamp.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, true,
org.apache.kafka.streams.processor.internals.assignment.HighAvailabilityTaskAssignor.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, true,
org.apache.kafka.streams.processor.internals.assignment.StickyTaskAssignor.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, true,
org.apache.kafka.streams.processor.internals.assignment.FallbackPriorTaskAssignor.class));
reflectiveClasses.produce(new ReflectiveClassBuildItem(true, true, true,
"org.apache.kafka.streams.processor.internals.StateDirectory$StateDirectoryProcessFile"));
}
Code review comment: Shall we assert this in `join-clause.bal` itself. 

Code before review:
public void testJoinClauseWithLargeList() {
Object values = BRunUtil.invoke(result, "testJoinClauseWithLargeList");
Assert.assertTrue((Boolean) values);
}

Line under review: Assert.assertTrue((Boolean) values);

Code after addressing the review:
public void testJoinClauseWithLargeList() {
BRunUtil.invoke(result, "testJoinClauseWithLargeList");
}
Code review comment: We should use the methods in TestUtils to load the project.

Code before review:
private String readTomlContent(Path projectPath, boolean isSingleFileProject) {
Path configTomlPath;
if (isSingleFileProject) {
configTomlPath = projectPath.getParent();
} else {
configTomlPath = projectPath;
}
return readFileContent(configTomlPath.resolve(CONFIGURATION_TOML));
}

Line under review: Path configTomlPath;

Code after addressing the review:
private String readTomlContent(Path projectPath, boolean isSingleFileProject) {
Path configTomlPath;
if (isSingleFileProject) {
configTomlPath = projectPath.getParent();
} else {
configTomlPath = projectPath;
}
return readFileContent(configTomlPath.resolve(CONFIGURATION_TOML));
}
Code review comment: Maybe it can be simplified as ```java assertThat(res).hasSize(1).containsEntry("LD_LIBRARY_PATH", "/usr/lib/native") ```

Code before review:
void testGetEnvironmentVariables() {
Configuration testConf = new Configuration();
testConf.setString("containerized.master.env.LD_LIBRARY_PATH", "/usr/lib/native");
Map<String, String> res =
ConfigurationUtils.getPrefixedKeyValuePairs("containerized.master.env.", testConf);
assertThat(res).hasSize(1);
Map.Entry<String, String> entry = res.entrySet().iterator().next();
assertThat(entry.getKey()).isEqualTo("LD_LIBRARY_PATH");
assertThat(entry.getValue()).isEqualTo("/usr/lib/native");
}

Line under review: assertThat(entry.getValue()).isEqualTo("/usr/lib/native");

Code after addressing the review:
void testGetEnvironmentVariables() {
Configuration testConf = new Configuration();
testConf.setString("containerized.master.env.LD_LIBRARY_PATH", "/usr/lib/native");
Map<String, String> res =
ConfigurationUtils.getPrefixedKeyValuePairs("containerized.master.env.", testConf);
assertThat(res).hasSize(1).containsEntry("LD_LIBRARY_PATH", "/usr/lib/native");
}
Code review comment: isHost() can now be removed?

Code before review:
private void checkAndRedeploy(InfrastructureApplication application) {
log.log(INFO, () -> "Checking if " + application.name() + " should be redeployed");
if ( ! readiedTypes.remove(application)) return;
log.log(INFO, () -> "Trying to redeploy " + application.id() + " after completing provisioning of " + application.name());
try (Mutex lock = locks.apply(application.id())) {
if (application.nodeType().isHost() && nodes.get().state(State.ready).nodeType(application.nodeType()).isEmpty()) return;
log.log(INFO, () -> "Redeploying " + application.id() + " after completing provisioning of " + application.name());
try {
deployer.getDeployment(application.id()).ifPresent(Deployment::activate);
readied(childOf(application));
}
catch (RuntimeException e) {
log.log(WARNING, "Failed redeploying " + application.id() + ", will be retried by maintainer", e);
}
}
catch (UncheckedTimeoutException collision) {
readied(application);
}
}

Line under review: log.log(INFO, () -> "Trying to redeploy " + application.id() + " after completing provisioning of " + application.name());

Code after addressing the review:
private void checkAndRedeploy(InfrastructureApplication application) {
if ( ! readiedTypes.remove(application)) return;
try (Mutex lock = locks.apply(application.id())) {
if (application.nodeType().isHost() && nodes.get().state(State.ready).nodeType(application.nodeType()).isEmpty()) return;
log.log(FINE, () -> "Redeploying " + application.id() + " after completing provisioning for " + application.name());
try {
deployer.getDeployment(application.id()).ifPresent(Deployment::activate);
childOf(application).ifPresent(this::readied);
}
catch (RuntimeException e) {
log.log(INFO, "Failed redeploying " + application.id() + ", will be retried by maintainer", e);
}
}
catch (UncheckedTimeoutException collision) {
readied(application);
}
}
Code review comment: I'm afraid the default parallelism will be quite large on CI (# CPU cores) and occupy too much resources. Setting parallelism to 2 is enough to reproduce the issue.   This case is for testing the case that only some partitions are empty, so that readers assigned with empty partitions can be closed without exception and other readers can process messages as expected. 

Code before review:
public void testConsumingTopicWithEmptyPartitions() throws Throwable {
String topicWithEmptyPartitions = "topicWithEmptyPartitions-" + UUID.randomUUID();
KafkaSourceTestEnv.createTestTopic(
topicWithEmptyPartitions, KafkaSourceTestEnv.NUM_PARTITIONS, 1);
List<ProducerRecord<String, Integer>> records =
KafkaSourceTestEnv.getRecordsForTopicWithoutTimestamp(topicWithEmptyPartitions);
int partitionWithRecords = 5;
records.removeIf(record -> record.partition() != partitionWithRecords);
KafkaSourceTestEnv.produceToKafka(records);
KafkaSourceTestEnv.setupEarliestOffsets(
Collections.singletonList(
new TopicPartition(topicWithEmptyPartitions, partitionWithRecords)));
KafkaSource<PartitionAndValue> source =
KafkaSource.<PartitionAndValue>builder()
.setBootstrapServers(KafkaSourceTestEnv.brokerConnectionStrings)
.setTopics(topicWithEmptyPartitions)
.setGroupId("topic-with-empty-partition-test")
.setDeserializer(new TestingKafkaRecordDeserializationSchema(false))
.setStartingOffsets(OffsetsInitializer.earliest())
.setBounded(OffsetsInitializer.latest())
.build();
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(2);
executeAndVerify(
env,
env.fromSource(
source,
WatermarkStrategy.noWatermarks(),
"testConsumingTopicWithEmptyPartitions"));
}

Line under review: executeAndVerify(

Code after addressing the review:
public void testConsumingTopicWithEmptyPartitions() throws Throwable {
String topicWithEmptyPartitions = "topicWithEmptyPartitions-" + UUID.randomUUID();
KafkaSourceTestEnv.createTestTopic(
topicWithEmptyPartitions, KafkaSourceTestEnv.NUM_PARTITIONS, 1);
List<ProducerRecord<String, Integer>> records =
KafkaSourceTestEnv.getRecordsForTopicWithoutTimestamp(topicWithEmptyPartitions);
int partitionWithRecords = 5;
records.removeIf(record -> record.partition() != partitionWithRecords);
KafkaSourceTestEnv.produceToKafka(records);
KafkaSourceTestEnv.setupEarliestOffsets(
Collections.singletonList(
new TopicPartition(topicWithEmptyPartitions, partitionWithRecords)));
KafkaSource<PartitionAndValue> source =
KafkaSource.<PartitionAndValue>builder()
.setBootstrapServers(KafkaSourceTestEnv.brokerConnectionStrings)
.setTopics(topicWithEmptyPartitions)
.setGroupId("topic-with-empty-partition-test")
.setDeserializer(new TestingKafkaRecordDeserializationSchema(false))
.setStartingOffsets(OffsetsInitializer.earliest())
.setBounded(OffsetsInitializer.latest())
.build();
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
env.setParallelism(2);
executeAndVerify(
env,
env.fromSource(
source,
WatermarkStrategy.noWatermarks(),
"testConsumingTopicWithEmptyPartitions"));
}
Code review comment: Aren't we creating a `Path` that's converted to a `File` for it to be converted to a `Path` again? :thinking: ...this also applies to the other occurrences below

Code before review:
static void setup() throws IOException {
schema =
new Schema.Parser()
.parse(
"{\"type\": \"record\", "
+ "\"name\": \"User\", "
+ "\"namespace\": \"org.apache.flink.formats.parquet.avro.AvroParquetRecordFormatTest\", "
+ "\"fields\": [\n"
+ "        {\"name\": \"name\", \"type\": \"string\" },\n"
+ "        {\"name\": \"favoriteNumber\",  \"type\": [\"int\", \"null\"] },\n"
+ "        {\"name\": \"favoriteColor\", \"type\": [\"string\", \"null\"] }\n"
+ "    ]\n"
+ "    }");
userRecords.add(createUser("Peter", 1, "red"));
userRecords.add(createUser("Tom", 2, "yellow"));
userRecords.add(createUser("Jack", 3, "green"));
createParquetFile(
AvroParquetWriters.forGenericRecord(schema),
Path.fromLocalFile(temporaryFolder.resolve(USER_PARQUET_FILE_1).toFile()),
userRecords.toArray(new GenericRecord[0]));
GenericRecord user = createUser("Max", 4, "blue");
userRecords.add(user);
createParquetFile(
AvroParquetWriters.forGenericRecord(schema),
Path.fromLocalFile(temporaryFolder.resolve(USER_PARQUET_FILE_2).toFile()),
user);
user = createUser("Alex", 5, "White");
GenericRecord user1 = createUser("Anna", 6, "Pink");
userRecords.add(user);
userRecords.add(user1);
createParquetFile(
AvroParquetWriters.forGenericRecord(schema),
Path.fromLocalFile(temporaryFolder.resolve(USER_PARQUET_FILE_3).toFile()),
user,
user1);
}

Line under review: Path.fromLocalFile(temporaryFolder.resolve(USER_PARQUET_FILE_1).toFile()),

Code after addressing the review:
static void setup() throws IOException {
schema =
new Schema.Parser()
.parse(
"{\"type\": \"record\", "
+ "\"name\": \"User\", "
+ "\"namespace\": \"org.apache.flink.formats.parquet.avro.AvroParquetRecordFormatTest\", "
+ "\"fields\": [\n"
+ "        {\"name\": \"name\", \"type\": \"string\" },\n"
+ "        {\"name\": \"favoriteNumber\",  \"type\": [\"int\", \"null\"] },\n"
+ "        {\"name\": \"favoriteColor\", \"type\": [\"string\", \"null\"] }\n"
+ "    ]\n"
+ "    }");
userRecords.add(createUser("Peter", 1, "red"));
userRecords.add(createUser("Tom", 2, "yellow"));
userRecords.add(createUser("Jack", 3, "green"));
createParquetFile(
AvroParquetWriters.forGenericRecord(schema),
Path.fromLocalFile(temporaryFolder.resolve(USER_PARQUET_FILE_1).toFile()),
userRecords.toArray(new GenericRecord[0]));
GenericRecord user = createUser("Max", 4, "blue");
userRecords.add(user);
createParquetFile(
AvroParquetWriters.forGenericRecord(schema),
Path.fromLocalFile(temporaryFolder.resolve(USER_PARQUET_FILE_2).toFile()),
user);
user = createUser("Alex", 5, "White");
GenericRecord user1 = createUser("Anna", 6, "Pink");
userRecords.add(user);
userRecords.add(user1);
createParquetFile(
AvroParquetWriters.forGenericRecord(schema),
Path.fromLocalFile(temporaryFolder.resolve(USER_PARQUET_FILE_3).toFile()),
user,
user1);
}
Code review comment: We've generally used either 4KB or 8KB as the buffer sizes as it hits a nice point between memory and CPU usage, unless this certificate is always known to be < 1KB then I'll revert this.

Code before review:
private byte[] getCertificateBytes() throws IOException {
if (certificatePath != null) {
return Files.readAllBytes(Paths.get(certificatePath));
} else if (certificate != null) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int read = certificate.read(buffer, 0, buffer.length);
while (read != -1) {
outputStream.write(buffer, 0, read);
read = certificate.read(buffer, 0, buffer.length);
}
return outputStream.toByteArray();
} else {
return new byte[0];
}
}

Line under review: byte[] buffer = new byte[4096];

Code after addressing the review:
private byte[] getCertificateBytes() throws IOException {
if (certificatePath != null) {
return Files.readAllBytes(Paths.get(certificatePath));
} else if (certificate != null) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int read = certificate.read(buffer, 0, buffer.length);
while (read != -1) {
outputStream.write(buffer, 0, read);
read = certificate.read(buffer, 0, buffer.length);
}
return outputStream.toByteArray();
} else {
return new byte[0];
}
}
Code review comment: Could we force constraints on the order of closing `context` and `enumerator` as follows: Because `context` was used by  `enumerator`, This is a bit like the close order in the I/O mechanism.  ```         if (started) {             closeQuietly(enumerator);         }         closeQuietly(context); ```  Although not doing so will not result in semantic errors.

Code before review:
public void close() throws Exception {
LOG.info("Closing SourceCoordinator for source {}.", operatorName);
closeQuietly(context);
if (started) {
closeQuietly(enumerator);
}
LOG.info("Source coordinator for source {} closed.", operatorName);
}

Line under review: closeQuietly(enumerator);

Code after addressing the review:
public void close() throws Exception {
LOG.info("Closing SourceCoordinator for source {}.", operatorName);
if (started) {
closeQuietly(enumerator);
}
closeQuietly(context);
LOG.info("Source coordinator for source {} closed.", operatorName);
}
Code review comment: org.opengauss.core.v3.QueryExecutorImpl#startCopy ``` Utils.encodeUTF8(statementName); ``` seem the client always use the utf-8, and tested succeed at local when contain chinese characters

Code before review:
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
String dataText = StandardCharsets.UTF_8.decode(data).toString();
if (decodeWithXid) {
result = decodeDataWithXid(dataText);
} else {
result = decodeDataIgnoreXid(dataText);
}
result.setLogSequenceNumber(logSequenceNumber);
return result;
}

Line under review: String dataText = StandardCharsets.UTF_8.decode(data).toString();

Code after addressing the review:
public AbstractWALEvent decode(final ByteBuffer data, final BaseLogSequenceNumber logSequenceNumber) {
AbstractWALEvent result;
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
String dataText = new String(bytes, StandardCharsets.UTF_8);
if (decodeWithTX) {
result = decodeDataWithTX(dataText);
} else {
result = decodeDataIgnoreTX(dataText);
}
result.setLogSequenceNumber(logSequenceNumber);
return result;
}
Code review comment: Make sense.

Code before review:
private static Schema deserializeSchema(Map<String, String> map, String schemaKey) {
final Builder builder = Schema.newBuilder();
deserializeColumns(map, schemaKey, builder);
deserializeWatermark(map, schemaKey, builder);
deserializePrimaryKey(map, schemaKey, builder);
return builder.build();
}

Line under review: deserializePrimaryKey(map, schemaKey, builder);

Code after addressing the review:
private static Schema deserializeSchema(Map<String, String> map, String schemaKey) {
final Builder builder = Schema.newBuilder();
deserializeColumns(map, schemaKey, builder);
deserializeWatermark(map, schemaKey, builder);
deserializePrimaryKey(map, schemaKey, builder);
return builder.build();
}
Code review comment: Would it be possible to assert somehow that the `q_session` value has not been created by the default state manager ? May be the session cookie value can be posted to the test resource and used there to return a JSON rep of the stored record and here in the test we can check the id token/access token/rt values are not null or may be something simpler ?

Code before review:
public void testCodeFlow() throws IOException {
try (final WebClient webClient = createWebClient()) {
TextPage textPage = webClient.getPage(url.toString() + "unprotected");
assertEquals("unprotected", textPage.getContent());
HtmlPage page;
page = webClient.getPage(url.toString() + "protected");
assertEquals("Sign in to quarkus", page.getTitleText());
HtmlForm loginForm = page.getForms().get(0);
loginForm.getInputByName("username").setValueAttribute("alice");
loginForm.getInputByName("password").setValueAttribute("alice");
textPage = loginForm.getInputByName("login").click();
assertEquals("alice", textPage.getContent());
assertTokenStateCount(1);
webClient.getOptions().setRedirectEnabled(false);
WebResponse webResponse = webClient
.loadWebResponse(new WebRequest(URI.create(url.toString() + "protected/logout").toURL()));
assertEquals(302, webResponse.getStatusCode());
assertNull(webClient.getCookieManager().getCookie("q_session"));
webClient.getCookieManager().clearCookies();
assertTokenStateCount(0);
}
}

Line under review: assertTokenStateCount(1);

Code after addressing the review:
public void testCodeFlow() throws IOException {
try (final WebClient webClient = createWebClient()) {
TextPage textPage = webClient.getPage(url.toString() + "unprotected");
assertEquals("unprotected", textPage.getContent());
HtmlPage page;
page = webClient.getPage(url.toString() + "protected");
assertEquals("Sign in to quarkus", page.getTitleText());
HtmlForm loginForm = page.getForms().get(0);
loginForm.getInputByName("username").setValueAttribute("alice");
loginForm.getInputByName("password").setValueAttribute("alice");
textPage = loginForm.getInputByName("login").click();
assertEquals("alice", textPage.getContent());
assertTokenStateCount(1);
webClient.getOptions().setRedirectEnabled(false);
WebResponse webResponse = webClient
.loadWebResponse(new WebRequest(URI.create(url.toString() + "protected/logout").toURL()));
assertEquals(302, webResponse.getStatusCode());
assertNull(webClient.getCookieManager().getCookie("q_session"));
webClient.getCookieManager().clearCookies();
assertTokenStateCount(0);
}
}
Code review comment: yes, if we wouldn't have the exists check, `deleteObject` would be called on the empty directory which would internally call `delete(path, false)` that calls the `directory` causing a `FileNotFoundException` in [PrestoS3FileSystem:483](https://github.com/prestodb/presto/blob/master/presto-hive%2Fsrc%2Fmain%2Fjava%2Fcom%2Ffacebook%2Fpresto%2Fhive%2Fs3%2FPrestoS3FileSystem.java#L483). The return value will be `false` which makes us do the `exists` check anyway at the end of `deleteObject`. The rational was to have a clearer code instead handling the empty directory explicitly.

Code before review:
private void deleteObject(Path path) throws IOException {
if (!exists(path)) {
return;
}
boolean success = true;
IOException actualException = null;
try {
success = super.delete(path, false);
} catch (IOException e) {
actualException = e;
}
if (!success || actualException != null) {
if (exists(path)) {
throw Optional.ofNullable(actualException)
.orElse(
new IOException(
path.getPath()
+ " could not be deleted for unknown reasons."));
}
}
}

Line under review: if (!exists(path)) {

Code after addressing the review:
private void deleteObject(Path path) throws IOException {
boolean success = true;
IOException actualException = null;
try {
success = super.delete(path, false);
} catch (IOException e) {
actualException = e;
}
if (!success || actualException != null) {
if (exists(path)) {
throw Optional.ofNullable(actualException)
.orElse(
new IOException(
path.getPath()
+ " could not be deleted for unknown reasons."));
}
}
}
Code review comment: Yes

Code before review:
public Optional<DocumentSymbol> transform(AnnotationDeclarationNode annotationDeclarationNode) {
StringBuilder name = new StringBuilder(SyntaxKind.ANNOTATION_KEYWORD.stringValue());
Optional<Node> typeDesc = annotationDeclarationNode.typeDescriptor();
if (typeDesc.isPresent()) {
name.append(" ").append(typeDesc.get().toSourceCode());
}
name.append(" ").append(annotationDeclarationNode.annotationTag().text());
SymbolKind symbolKind = SymbolKind.Property;
Range range = DocumentSymbolUtil.generateNodeRange(annotationDeclarationNode);
Optional<MetadataNode> metadata = annotationDeclarationNode.metadata();
boolean isDeprecated = metadata.isPresent() &&
DocumentSymbolUtil.isDeprecated(metadata.get());
return Optional.ofNullable(createDocumentSymbol(name.toString(), symbolKind, null,
range, range, isDeprecated, Collections.emptyList(), this.context));
}

Line under review: name.append(" ").append(annotationDeclarationNode.annotationTag().text());

Code after addressing the review:
public Optional<DocumentSymbol> transform(AnnotationDeclarationNode annotationDeclarationNode) {
String name = annotationDeclarationNode.annotationTag().text();
SymbolKind symbolKind = SymbolKind.Property;
Range range = DocumentSymbolUtil.generateNodeRange(annotationDeclarationNode);
Optional<MetadataNode> metadata = annotationDeclarationNode.metadata();
boolean isDeprecated = metadata.isPresent() &&
DocumentSymbolUtil.isDeprecated(metadata.get());
return Optional.of(createDocumentSymbol(name, symbolKind, range, range, isDeprecated,
Collections.emptyList()));
}
Code review comment: ```suggestion             if (warehouse != null) { ```

Code before review:
public void replayDropComputeNode(long computeNodeId) {
LOG.debug("replayDropComputeNode: {}", computeNodeId);
Map<Long, ComputeNode> copiedComputeNodes = Maps.newHashMap(idToComputeNodeRef);
ComputeNode cn = copiedComputeNodes.remove(computeNodeId);
idToComputeNodeRef = ImmutableMap.copyOf(copiedComputeNodes);
final Cluster cluster = GlobalStateMgr.getCurrentState().getCluster();
if (null != cluster) {
cluster.removeComputeNode(computeNodeId);
} else {
LOG.error("Cluster DEFAULT_CLUSTER " + DEFAULT_CLUSTER + " no exist.");
}
if (Config.only_use_compute_node) {
Warehouse warehouse = GlobalStateMgr.getCurrentWarehouseMgr().
getWarehouse(WarehouseManager.DEFAULT_WAREHOUSE_NAME);
if (null != warehouse) {
warehouse.getAnyAvailableCluster().dropNode(cn.getId());
}
}
}

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

Code after addressing the review:
public void replayDropComputeNode(long computeNodeId) {
LOG.debug("replayDropComputeNode: {}", computeNodeId);
Map<Long, ComputeNode> copiedComputeNodes = Maps.newHashMap(idToComputeNodeRef);
ComputeNode cn = copiedComputeNodes.remove(computeNodeId);
idToComputeNodeRef = ImmutableMap.copyOf(copiedComputeNodes);
final Cluster cluster = GlobalStateMgr.getCurrentState().getCluster();
if (null != cluster) {
cluster.removeComputeNode(computeNodeId);
} else {
LOG.error("Cluster DEFAULT_CLUSTER " + DEFAULT_CLUSTER + " no exist.");
}
if (Config.only_use_compute_node) {
Warehouse warehouse = GlobalStateMgr.getCurrentWarehouseMgr().
getWarehouse(WarehouseManager.DEFAULT_WAREHOUSE_NAME);
if (warehouse != null) {
warehouse.getAnyAvailableCluster().dropNode(cn.getId());
}
}
}
Code review comment: We should check StorageAccountManager bean here and for below test.

Code before review:
public void testEventHubOperationProvidedNotStorageUnderMSI() {
this.contextRunner.withUserConfiguration(
TestConfigWithAzureResourceManagerAndConnectionProvider.class,
AzureEventHubAutoConfiguration.class)
.withPropertyValues(
AZURE_PROPERTY_PREFIX + "resource-group=rg1",
AZURE_PROPERTY_PREFIX + "msi-enabled=true",
EVENT_HUB_PROPERTY_PREFIX + "namespace=ns1",
AZURE_PROPERTY_PREFIX + "subscription-id=sub"
)
.run(context -> {
assertThat(context).hasSingleBean(EventHubNamespaceManager.class);
assertThat(context).hasSingleBean(EventHubOperation.class);
});
}

Line under review: assertThat(context).hasSingleBean(EventHubNamespaceManager.class);

Code after addressing the review:
public void testEventHubOperationProvidedNotStorageUnderMSI() {
this.contextRunner.withUserConfiguration(
TestConfigWithAzureResourceManagerAndConnectionProvider.class,
AzureEventHubAutoConfiguration.class)
.withPropertyValues(
AZURE_PROPERTY_PREFIX + "resource-group=rg1",
AZURE_PROPERTY_PREFIX + "msi-enabled=true",
EVENT_HUB_PROPERTY_PREFIX + "namespace=ns1",
AZURE_PROPERTY_PREFIX + "subscription-id=sub"
)
.run(context -> {
assertThat(context).hasSingleBean(EventHubNamespaceManager.class);
assertThat(context).hasSingleBean(EventHubOperation.class);
assertThat(context).doesNotHaveBean(StorageAccountManager.class);
});
}
Code review comment: Shall we have an Option constructor taking the only type since we can set 0 as default?

Code before review:
public Object[] getMainArgs() {
mainArgs.add(null);
if (option != null) {
BMap<BString, Object> recordVal = option.parseRecord(args);
processOperands(option.getOperandArgs());
int optionLocation = option.getLocation() * 2 + 1;
mainArgs.add(optionLocation, recordVal);
mainArgs.add(optionLocation + 1, true);
} else {
RecordType type = TypeCreator.createRecordType("dummy", null, 1, new HashMap<>(), null, true, 6);
Option dummyOption = new Option(type, ValueCreator.createMapValue(type), 0);
dummyOption.parseRecord(args);
processOperands(dummyOption.getOperandArgs());
}
return mainArgs.toArray();
}

Line under review: Option dummyOption = new Option(type, ValueCreator.createMapValue(type), 0);

Code after addressing the review:
public Object[] getMainArgs() {
mainArgs.add(null);
if (option != null) {
BMap<BString, Object> recordVal = option.parseRecord(args);
processOperands(option.getOperandArgs());
int optionLocation = option.getLocation() * 2 + 1;
mainArgs.add(optionLocation, recordVal);
mainArgs.add(optionLocation + 1, true);
} else {
RecordType type = TypeCreator.createRecordType("dummy", null, 1, new HashMap<>(), null, true, 6);
Option dummyOption = new Option(type, ValueCreator.createMapValue(type));
dummyOption.parseRecord(args);
processOperands(dummyOption.getOperandArgs());
}
return mainArgs.toArray();
}
Code review comment: I can replace the "isCopied" or "isCopyable" with "isBufferShared" which may be easier to understand.

Code before review:
BufferAndBacklog pollBuffer(boolean isLocalChannel) {
synchronized (buffers) {
Buffer buffer = null;
if (buffers.isEmpty()) {
flushRequested = false;
}
while (!buffers.isEmpty()) {
BufferConsumer bufferConsumer = buffers.peek();
buffer = bufferConsumer.build();
if (!isLocalChannel && !bufferConsumer.isCopied() && canBeCompressed(buffer)) {
buffer = parent.bufferCompressor.compressToOriginalBuffer(buffer);
}
checkState(bufferConsumer.isFinished() || buffers.size() == 1,
"When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue.");
if (buffers.size() == 1) {
flushRequested = false;
}
if (bufferConsumer.isFinished()) {
buffers.pop().close();
decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer());
}
if (buffer.readableBytes() > 0) {
break;
}
buffer.recycleBuffer();
buffer = null;
if (!bufferConsumer.isFinished()) {
break;
}
}
if (buffer == null) {
return null;
}
updateStatistics(buffer);
return new BufferAndBacklog(
buffer,
isAvailableUnsafe(),
getBuffersInBacklog(),
nextBufferIsEventUnsafe());
}
}

Line under review: if (!isLocalChannel && !bufferConsumer.isCopied() && canBeCompressed(buffer)) {

Code after addressing the review:
BufferAndBacklog pollBuffer(boolean isLocalChannel) {
synchronized (buffers) {
Buffer buffer = null;
if (buffers.isEmpty()) {
flushRequested = false;
}
while (!buffers.isEmpty()) {
BufferConsumer bufferConsumer = buffers.peek();
buffer = bufferConsumer.build();
if (!isLocalChannel && !bufferConsumer.isShareable() && canBeCompressed(buffer)) {
buffer = parent.bufferCompressor.compressToOriginalBuffer(buffer);
}
checkState(bufferConsumer.isFinished() || buffers.size() == 1,
"When there are multiple buffers, an unfinished bufferConsumer can not be at the head of the buffers queue.");
if (buffers.size() == 1) {
flushRequested = false;
}
if (bufferConsumer.isFinished()) {
buffers.pop().close();
decreaseBuffersInBacklogUnsafe(bufferConsumer.isBuffer());
}
if (buffer.readableBytes() > 0) {
break;
}
buffer.recycleBuffer();
buffer = null;
if (!bufferConsumer.isFinished()) {
break;
}
}
if (buffer == null) {
return null;
}
updateStatistics(buffer);
return new BufferAndBacklog(
buffer,
isAvailableUnsafe(),
getBuffersInBacklog(),
nextBufferIsEventUnsafe());
}
}
Code review comment: These changes are already contained in #6638. You could base this PR on #6638.

Code before review:
private void scheduleRelease(JobInfo jobInfo) {
WrappedContext wrapper = getCache().get(jobInfo.jobId());
Preconditions.checkState(
wrapper != null, "Releasing context for unknown job: " + jobInfo.jobId());
PipelineOptions pipelineOptions =
PipelineOptionsTranslation.fromProto(jobInfo.pipelineOptions());
int environmentCacheTTLMillis =
pipelineOptions.as(PortablePipelineOptions.class).getEnvironmentCacheMillis();
if (environmentCacheTTLMillis > 0) {
getExecutor()
.schedule(() -> release(wrapper), environmentCacheTTLMillis, TimeUnit.MILLISECONDS);
} else {
release(wrapper);
}
}

Line under review: .schedule(() -> release(wrapper), environmentCacheTTLMillis, TimeUnit.MILLISECONDS);

Code after addressing the review:
private void scheduleRelease(JobInfo jobInfo) {
WrappedContext wrapper = getCache().get(jobInfo.jobId());
Preconditions.checkState(
wrapper != null, "Releasing context for unknown job: " + jobInfo.jobId());
PipelineOptions pipelineOptions =
PipelineOptionsTranslation.fromProto(jobInfo.pipelineOptions());
int environmentCacheTTLMillis =
pipelineOptions.as(PortablePipelineOptions.class).getEnvironmentCacheMillis();
if (environmentCacheTTLMillis > 0) {
if (this.getClass().getClassLoader() != ExecutionEnvironment.class.getClassLoader()) {
LOG.warn(
"{} is not loaded on parent Flink classloader. "
+ "Falling back to synchronous environment release for job {}.",
this.getClass(),
jobInfo.jobId());
release(wrapper);
} else {
getExecutor()
.schedule(() -> release(wrapper), environmentCacheTTLMillis, TimeUnit.MILLISECONDS);
}
} else {
release(wrapper);
}
}
Code review comment: if status == null, I think we should throw something because this should not happen. Not sure what you'd do with a null status.

Code before review:
public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
for (OperationStatus opStatus : values(OperationStatus.class)) {
if (opStatus.toString().equals(name)) {
if (!(opStatus.isComplete() == isComplete)) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for"
+ " operation status %s", isComplete, name));
}
}
}
status.completed = isComplete;
}
return status;
}

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

Code after addressing the review:
public static OperationStatus fromString(String name, boolean isComplete) {
OperationStatus status = fromString(name, OperationStatus.class);
if (status != null) {
if (operationStatusMap != null && operationStatusMap.containsKey(name)) {
OperationStatus operationStatus = operationStatusMap.get(name);
if (operationStatus.isComplete() != isComplete) {
throw new IllegalArgumentException(String.format("Cannot set complete status %s for operation"
+ "status %s", isComplete, name));
}
}
status.completed = isComplete;
}
return status;
}
Code review comment: Seems PostgreSQL and openGauss could not get `beforeRows` from `UpdateRowsEvent`, not like MySQL binlog. And update event include all columns. ``` scaling1=# update t_order_0 set status='ok1' where order_id=1; UPDATE 1 scaling1=# SELECT * FROM pg_logical_slot_get_changes('regression_slot', NULL, NULL);     lsn    | xid |                                                  data -----------+-----+--------------------------------------------------------------------------------------------------------  0/17B18A8 | 599 | BEGIN 599  0/17B18A8 | 599 | table public.t_order_0: UPDATE: order_id[integer]:1 user_id[integer]:2 status[character varying]:'ok1'  0/17B1CB8 | 599 | COMMIT 599 (3 rows) ```  We'll make `Column.oldValue` not final for now.

Code before review:
private void updateRecordOldValue(final Record record) {
if (!(record instanceof DataRecord)) {
return;
}
DataRecord dataRecord = (DataRecord) record;
if (!ScalingConstant.UPDATE.equals(dataRecord.getType())) {
return;
}
for (Column col: dataRecord.getColumns()) {
if (col.isPrimaryKey() && col.isUpdated()) {
col.setOldValue(col.getValue());
}
}
}

Line under review: }

Code after addressing the review:
private void updateRecordOldValue(final Record record) {
if (!(record instanceof DataRecord)) {
return;
}
DataRecord dataRecord = (DataRecord) record;
if (!ScalingConstant.UPDATE.equals(dataRecord.getType())) {
return;
}
for (Column col: dataRecord.getColumns()) {
if (col.isPrimaryKey() && col.isUpdated()) {
col.setOldValue(col.getValue());
}
}
}
Code review comment: loose -> lose

Code before review:
void assertParkedCountsByApplication(long... nums) {
long expected = LongStream.of(nums).filter(value -> value > 0L).sum();
long actual = (long) nodeRepository.getNodes(Node.State.parked).size();
assertEquals(expected, actual);
}


Code after addressing the review:
void assertParkedCountsByApplication(long... nums) {
long expected = LongStream.of(nums).filter(value -> value > 0L).sum();
long actual = (long) nodeRepository.getNodes(Node.State.parked).size();
assertEquals(expected, actual);
}
Code review comment: Another observation is that in `NotifyingTransactionManager#commit()` we use `this.getTransaction()` for the payload in the beforeDestroyed event but we use `destroyed(this);` for the payload in the destroyed event. If the payload is meant to be the same (which I think it should) then I think the call to `this.getTransaction()` should be cached and the same object used for both events

Code before review:
public void begin() throws NotSupportedException, SystemException {
delegate.begin();
initialized(delegate);
}

Line under review: initialized(delegate);

Code after addressing the review:
public void begin() throws NotSupportedException, SystemException {
delegate.begin();
initialized(getTransactionId());
}
Code review comment: Yes, the `targetValue == null` means that the default value is used (`TemplateData.class` in this particular case). The default values are stored in the annotation defining class, not in the annotation instance. See also the `org.jboss.jandex.AnnotationInstance.valueWithDefault(IndexView, String)`  method and friends. 

Code before review:
public boolean isTargetAnnotatedType() {
AnnotationValue targetValue = annotationInstance.value(ValueResolverGenerator.TARGET);
return targetValue == null || targetValue.asClass().name().equals(ValueResolverGenerator.TEMPLATE_DATA);
}

Line under review: return targetValue == null || targetValue.asClass().name().equals(ValueResolverGenerator.TEMPLATE_DATA);

Code after addressing the review:
public boolean isTargetAnnotatedType() {
AnnotationValue targetValue = annotationInstance.value(ValueResolverGenerator.TARGET);
return targetValue == null || targetValue.asClass().name().equals(ValueResolverGenerator.TEMPLATE_DATA);
}
Code review comment: https://sonarcloud.io/project/issues?id=gwenneg_quarkus&open=AXAxfMfPgbHBif7sECGm&resolutions=FIXED&severities=CRITICAL  The `DEFAULT` constant is actually defined in `ByteBufAllocator` which is implemented by `PartialPooledByteBufAllocator`.

Code before review:
public ByteBuf allocateBuffer(boolean direct) {
if (direct) {
return ByteBufAllocator.DEFAULT.directBuffer(defaultBufferSize);
} else {
return ByteBufAllocator.DEFAULT.heapBuffer(defaultBufferSize);
}
}

Line under review: return ByteBufAllocator.DEFAULT.heapBuffer(defaultBufferSize);

Code after addressing the review:
public ByteBuf allocateBuffer(boolean direct) {
if (direct) {
return ByteBufAllocator.DEFAULT.directBuffer(defaultBufferSize);
} else {
return ByteBufAllocator.DEFAULT.heapBuffer(defaultBufferSize);
}
}
Code review comment: The order does not make any differences. 

Code before review:
public static void configureMapper(ObjectMapper mapper) {
mapper.registerModule(new JavaTimeModule());
mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
UntypedObjectDeserializer defaultDeserializer = new UntypedObjectDeserializer(null, null);
GeoPointDeserializer geoPointDeserializer = new GeoPointDeserializer(defaultDeserializer);
Iso8601DateDeserializer iso8601DateDeserializer = new Iso8601DateDeserializer(geoPointDeserializer);
SimpleModule module = new SimpleModule();
module.addDeserializer(Object.class, iso8601DateDeserializer);
mapper.registerModule(Iso8601DateSerializer.getModule());
mapper.registerModule(module);
}

Line under review: Iso8601DateDeserializer iso8601DateDeserializer = new Iso8601DateDeserializer(geoPointDeserializer);

Code after addressing the review:
public static void configureMapper(ObjectMapper mapper) {
mapper.registerModule(new JavaTimeModule());
mapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
UntypedObjectDeserializer defaultDeserializer = new UntypedObjectDeserializer(null, null);
GeoPointDeserializer geoPointDeserializer = new GeoPointDeserializer(defaultDeserializer);
Iso8601DateDeserializer iso8601DateDeserializer = new Iso8601DateDeserializer(geoPointDeserializer);
SimpleModule module = new SimpleModule();
module.addDeserializer(Object.class, iso8601DateDeserializer);
mapper.registerModule(Iso8601DateSerializer.getModule());
mapper.registerModule(module);
}
Code review comment: Should look into having a ConnectionStringParser class in Azure Core, I've been seeing this functionality in a lot of places.

Code before review:
private void getEndPointFromConnectionString(String connectionString) {
HashMap<String, String> connectionStringPieces = new HashMap<>();
for (String connectionStringPiece : connectionString.split(";")) {
String[] kvp = connectionStringPiece.split("=", 2);
connectionStringPieces.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]);
}
String accountName = connectionStringPieces.get(ACCOUNT_NAME);
try {
this.endpoint = new URL(String.format("https:
} catch (MalformedURLException e) {
throw new IllegalArgumentException(String.format("There is no valid account for the connection string. "
+ "Connection String: %s", connectionString));
}
}

Line under review: for (String connectionStringPiece : connectionString.split(";")) {

Code after addressing the review:
private void getEndPointFromConnectionString(String connectionString) {
HashMap<String, String> connectionStringPieces = new HashMap<>();
for (String connectionStringPiece : connectionString.split(";")) {
String[] kvp = connectionStringPiece.split("=", 2);
connectionStringPieces.put(kvp[0].toLowerCase(Locale.ROOT), kvp[1]);
}
String accountName = connectionStringPieces.get(ACCOUNT_NAME);
try {
this.endpoint = new URL(String.format("https:
} catch (MalformedURLException e) {
LOGGER.asError().log("There is no valid account for the connection string. "
+ "Connection String: %s", connectionString);
throw new IllegalArgumentException(String.format("There is no valid account for the connection string. "
+ "Connection String: %s", connectionString));
}
}
Code review comment: These shouldn't have to change. Input-output models should have setter overloads for both varargs and List. 

Code before review:
public static AnalyzeTextOptions map(com.azure.search.documents.indexes.implementation.models.AnalyzeRequest obj) {
if (obj == null) {
return null;
}
AnalyzeTextOptions analyzeTextOptions = null;
if (obj.getTokenizer() != null) {
LexicalTokenizerName tokenizer = LexicalTokenizerNameConverter.map(obj.getTokenizer());
analyzeTextOptions = new AnalyzeTextOptions(obj.getText(), tokenizer);
} else {
LexicalAnalyzerName analyzer = LexicalAnalyzerNameConverter.map(obj.getAnalyzer());
analyzeTextOptions = new AnalyzeTextOptions(obj.getText(), analyzer);
}
if (obj.getCharFilters() != null) {
CharFilterName[] charFilters = obj.getCharFilters().stream()
.map(CharFilterNameConverter::map)
.toArray(CharFilterName[]::new);
analyzeTextOptions.setCharFilters(charFilters);
}
if (obj.getTokenFilters() != null) {
TokenFilterName[] tokenFilters = obj.getTokenFilters().stream()
.map(TokenFilterNameConverter::map)
.toArray(TokenFilterName[]::new);
analyzeTextOptions.setTokenFilters(tokenFilters);
}
return analyzeTextOptions;
}

Line under review: .toArray(TokenFilterName[]::new);

Code after addressing the review:
public static AnalyzeTextOptions map(com.azure.search.documents.indexes.implementation.models.AnalyzeRequest obj) {
if (obj == null) {
return null;
}
AnalyzeTextOptions analyzeTextOptions = null;
if (obj.getTokenizer() != null) {
LexicalTokenizerName tokenizer = LexicalTokenizerNameConverter.map(obj.getTokenizer());
analyzeTextOptions = new AnalyzeTextOptions(obj.getText(), tokenizer);
} else {
LexicalAnalyzerName analyzer = LexicalAnalyzerNameConverter.map(obj.getAnalyzer());
analyzeTextOptions = new AnalyzeTextOptions(obj.getText(), analyzer);
}
if (obj.getCharFilters() != null) {
analyzeTextOptions.setCharFilters(obj.getCharFilters().stream()
.map(CharFilterNameConverter::map)
.toArray(CharFilterName[]::new));
}
if (obj.getTokenFilters() != null) {
analyzeTextOptions.setTokenFilters(obj.getTokenFilters().stream()
.map(TokenFilterNameConverter::map)
.toArray(TokenFilterName[]::new));
}
return analyzeTextOptions;
}