auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean hasNext() { START if (this.hasPeek) { END return true; } if (!this.iterator.hasNext()) { this.iterator = this.iterable.iterator(); } return true; } Should simply return true here, right? As written now it is adjusting internal state, and it is best to isolate state manipulation to as few places as possible.

Target:
public boolean hasNext() { return true; }
Source:
public T next() { START final T next = this.nextValue; END this.nextValue = advance(); return next; } no need to use `this.` outside the constructor. Here and below

Target:
public T next() { final T next = nextValue; nextValue = advance(); return next; }
Source:
synchronized Set<String> metadataTopics() { START Set<String> topics = new HashSet<>(groupSubscription); END topics.addAll(subscription); return topics; } It might borderline overkill, but I'm considering if we could avoid the copy here with logic like the following: ``` if (!groupSubscription.isEmpty()) return groupSubscription; else return subscription; ``` Basically relying on the the group subscription being a superset of the local subscription when it is defined.

Target:
synchronized Set<String> metadataTopics() { return groupSubscription.isEmpty() ? subscription : groupSubscription; }
Source:
public Iterator<Header> iterator() { START return (headers == null) ? Collections.emptyIterator() : END headers.iterator(); } nit: parens unnecessary

Target:
public Iterator<Header> iterator() { return headers == null ? Collections.emptyIterator() : headers.iterator(); }
Source:
public ConsumerGroupMetadata groupMetadata() { START return new ConsumerGroupMetadata(groupMetadata); END } Why we want to return a clone of the groupMetadata? If we can declare all the fields as final, and whenever we update we always create a new ConsumerGroupMetadata object, then I think we can safely return the cached object directly.

Target:
public ConsumerGroupMetadata groupMetadata() { return groupMetadata; }
Source:
public void testThreadNameWithoutNumberDemon() { Thread daemonThread = ThreadUtils.createThreadFactory(THREAD_NAME, true).newThread(EMPTY_RUNNABLE); try { Assert.assertEquals(daemonThread.getName(), THREAD_NAME); Assert.assertTrue(daemonThread.isDaemon()); } finally { try { daemonThread.join(); } catch (InterruptedException e) { // can be ignored START e.printStackTrace(); END } } } Maybe we don't need to print the stack trace if we can ignore it

Target:
public void testThreadNameWithoutNumberDemon() { Thread daemonThread = ThreadUtils.createThreadFactory(THREAD_NAME, true).newThread(EMPTY_RUNNABLE); try { assertEquals(THREAD_NAME, daemonThread.getName()); assertTrue(daemonThread.isDaemon()); } finally { try { daemonThread.join(); } catch (InterruptedException e) { // can be ignored } } }
Source:
private ConsumerCoordinator buildCoordinator(final GroupRebalanceConfig rebalanceConfig, final Metrics metrics, final List<ConsumerPartitionAssignor> assignors, final boolean autoCommitEnabled) { return new ConsumerCoordinator( rebalanceConfig, new LogContext(), consumerClient, assignors, metadata, subscriptions, metrics, "consumer" + groupId, time, autoCommitEnabled, autoCommitIntervalMs, START false, END null); } Why do we pass `false` here?

Target:
private ConsumerCoordinator buildCoordinator(final GroupRebalanceConfig rebalanceConfig, final Metrics metrics, final List<ConsumerPartitionAssignor> assignors, final boolean autoCommitEnabled) { return new ConsumerCoordinator( rebalanceConfig, new LogContext(), consumerClient, assignors, metadata, subscriptions, metrics, "consumer" + groupId, time, autoCommitEnabled, autoCommitIntervalMs, null); }
Source:
public void clearChildrenProducerBatch() { START childrenProducerBatch.clear(); END } I'm wondering if we should take care of concurrent modification for this list. We should, maybe?

Target:
private synchronized void clearChildrenProducerBatch() { if (childrenProducerBatch != null) { childrenProducerBatch.clear(); } }
Source:
public void awaitFlushCompletion() throws InterruptedException { try { for (ProducerBatch batch : this.incomplete.copyAll()) { batch.produceFuture.await(); START waitForPossibleSplittedBatches(batch); END batch.clearChildrenProducerBatch(); } } finally { this.flushesInProgress.decrementAndGet(); } } It seems like it might be cleaner if we move all the waitForPossibleSplittedBatches logic into a `ProducerBatch.await` method that performs the await on its produceFuture as well as on the child batches.

Target:
public void awaitFlushCompletion() throws InterruptedException { try { for (ProducerBatch batch : this.incomplete.copyAll()) { batch.await(); } } finally { this.flushesInProgress.decrementAndGet(); } }
Source:
private void addChildrenProducerBatch(final ProducerBatch batch) { if (childrenProducerBatch == null) { childrenProducerBatch = new ArrayList<>(); } START childrenProducerBatch.add(batch); END } This should also be synchronized

Target:
private synchronized void addChildrenProducerBatch(final ProducerBatch batch) { if (childrenProducerBatch == null) { childrenProducerBatch = new ArrayList<>(); } childrenProducerBatch.add(batch); }
Source:
public void shouldNotAllowInvalidTopicNames() { final String invalidName = "not:valid"; final TopologyException e = assertThrows(TopologyException.class, () -> Materialized.as(invalidName)); START assert e.getMessage().equals("Invalid topology: Name \"" + invalidName + END "\" is illegal, it contains a character other than " + "ASCII alphanumerics, '.', '_' and '-'"); } We should not use Java `assert` statement but proper unit testing asserts, ie, `assertThat(e.getMessage(), equalTo("..."));`

Target:
public void shouldNotAllowInvalidTopicNames() { final String invalidName = "not:valid"; final TopologyException e = assertThrows(TopologyException.class, () -> Materialized.as(invalidName)); assertEquals(e.getMessage(), "Invalid topology: Name \"" + invalidName + "\" is illegal, it contains a character other than " + "ASCII alphanumerics, '.', '_' and '-'"); }
Source:
public void close() { log.debug("Closing record collector"); maybeAbortTxn(); if (eosEnabled) { try { producer.close(); } catch (final KafkaException e) { throw new StreamsException("Caught a recoverable exception while closing", e); } START producer = null; END } checkForException(); } req: This is unnecessary

Target:
public void close() { log.debug("Closing record collector"); maybeAbortTxn(); if (eosEnabled) { try { producer.close(); } catch (final KafkaException e) { throw new StreamsException("Caught a recoverable exception while closing", e); } } checkForException(); }
Source:
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer, final Merger<? super K, V> sessionMerger) { START return aggregate(initializer, sessionMerger, Materialized.with(keySerde, null)); END } the `keySerde` is set to `null` in the constructor, hence, I am wondering if we should pass in `null`, here, too? (similar question for `TimeWindowedCogroupedKStreamImpl`)

Target:
public KTable<Windowed<K>, V> aggregate(final Initializer<V> initializer, final Merger<? super K, V> sessionMerger) { return aggregate(initializer, sessionMerger, Materialized.with(null, null)); }
Source:
public ConfigEntry(String name, String value, ConfigSource source, boolean isSensitive, boolean isReadOnly, START List<ConfigSynonym> synonyms) { END Objects.requireNonNull(name, "name should not be null"); this.name = name; this.value = value; this.source = source; this.isSensitive = isSensitive; this.isReadOnly = isReadOnly; this.synonyms = synonyms; } This is a public API, so let's not change it here. If you need a `ConfigEntry` with synonyms for the test, create a static method in `ConfigTest` that will make it. That will keep the change confined to the test code.

Target:
ConfigEntry(String name, String value, ConfigSource source, boolean isSensitive, boolean isReadOnly, List<ConfigSynonym> synonyms) { Objects.requireNonNull(name, "name should not be null"); this.name = name; this.value = value; this.source = source; this.isSensitive = isSensitive; this.isReadOnly = isReadOnly; this.synonyms = synonyms; }
Source:
public <W extends Window> TimeWindowedCogroupedKStream<K, VOut> windowedBy(final Windows<W> windows) { Objects.requireNonNull(windows, "windows can't be null"); START return new TimeWindowedCogroupedKStreamImpl<>(windows, END builder, sourceNodes, name, keySerde, null, aggregateBuilder, streamsGraphNode, groupPatterns); } nit: move `windows` to next line

Target:
public <W extends Window> TimeWindowedCogroupedKStream<K, VOut> windowedBy(final Windows<W> windows) { Objects.requireNonNull(windows, "windows can't be null"); return new TimeWindowedCogroupedKStreamImpl<>( windows, builder, sourceNodes, name, aggregateBuilder, streamsGraphNode, groupPatterns); }
Source:
public void registerClientInformation(final ClientInformation clientInformation) { START if (this.clientInformation != null) { END sensors.connectionsByClient.decrement(this.clientInformation); } this.clientInformation = clientInformation; sensors.connectionsByClient.increment(clientInformation); } If this already exists, we should check to see if it's equal to the new information we wanted to register. If it is, we can skip the decrement metric + increment metric dance.

Target:
public void registerClientInformation(final ClientInformation clientInformation) { if (this.clientInformation != null) { if (this.clientInformation.equals(clientInformation)) return; sensors.connectionsByClient.decrement(this.clientInformation); } this.clientInformation = clientInformation; sensors.connectionsByClient.increment(clientInformation); }
Source:
private void flushAndCheckpointState() { try { stateMgr.flush(); } catch (final ProcessorStateException e) { START if (e.getCause() instanceof ProducerFencedException) { END log.warn("Caught a retriable Kafka exception while flushing state. Initiating a rebalance to attempt recovery.", e); throw new TaskMigratedException(this, e); } } stateMgr.checkpoint(Collections.emptyMap()); } The same argument as for `GlobalStateStore` should apply here -- StandbyTask don't write but only read, hence, no `ProducerFencedException` could ever happen here.

Target:
private void flushAndCheckpointState() { // this could theoretically throw a ProcessorStateException caused by a ProducerFencedException, // but in practice this shouldn't happen for standby tasks, since they don't produce to changelog topics // or downstream topics. stateMgr.flush(); stateMgr.checkpoint(Collections.emptyMap()); }
Source:
boolean hasRestoringTasks() { START if (restoring.isEmpty()) { END restoredPartitions.clear(); restoringByPartition.clear(); } return !restoring.isEmpty(); } It seems a bit awkward to have a `hasXXX` call have side effects. Although I do understand the motivation here, I guess this is something to revisit during a subsequent refactoring/follow-on PR.

Target:
boolean hasRestoringTasks() { return !restoring.isEmpty(); }
Source:
public void testUpdateMetadataAllowedImmediatelyAfterBootstrap() { MockTime time = new MockTime(); Metadata metadata = new Metadata(refreshBackoffMs, metadataExpireMs, new LogContext(), new ClusterResourceListeners()); metadata.bootstrap(Collections.singletonList(new InetSocketAddress("localhost", 9002))); START metadata.requestUpdate(); END assertEquals(0, metadata.timeToAllowUpdate(time.milliseconds())); assertEquals(0, metadata.timeToNextUpdate(time.milliseconds())); } `bootstrap()` itself should mandate an update, right? Do we need to call `requestUpdate`?

Target:
public void testUpdateMetadataAllowedImmediatelyAfterBootstrap() { MockTime time = new MockTime(); Metadata metadata = new Metadata(refreshBackoffMs, metadataExpireMs, new LogContext(), new ClusterResourceListeners()); metadata.bootstrap(Collections.singletonList(new InetSocketAddress("localhost", 9002))); assertEquals(0, metadata.timeToAllowUpdate(time.milliseconds())); assertEquals(0, metadata.timeToNextUpdate(time.milliseconds())); }
Source:
public void reconfigure(Map<String, ?> configs) { synchronized (LOCK) { START this.mbeanPredicate = JmxReporter.compilePredicate(configPrefix, configs); END mbeans.forEach((name, mbean) -> { if (mbeanPredicate.test(name)) { reregister(mbean); } else { unregister(mbean); } }); } } I might be missing something, but in both cases, you just want to use regular expressions, right? There is no need to mess around with predicate functions.

Target:
public void reconfigure(Map<String, ?> configs) { synchronized (LOCK) { this.mbeanPredicate = JmxReporter.compilePredicate(configs); mbeans.forEach((name, mbean) -> { if (mbeanPredicate.test(name)) { reregister(mbean); } else { unregister(mbean); } }); } }
Source:
public void shouldGetLateRecordDropSensor() { final String metricNamePrefix = "late-record-drop"; final String descriptionOfCount = "The total number of dropped late records"; final String descriptionOfRate = "The average number of dropped late records per second"; if (builtInMetricsVersion == Version.FROM_0100_TO_24) { setUpThroughputSensor( metricNamePrefix, descriptionOfRate, descriptionOfCount, RecordingLevel.INFO ); } else { expect(streamsMetrics.nodeLevelSensor( THREAD_ID, TASK_ID, PROCESSOR_NODE_ID, metricNamePrefix, RecordingLevel.INFO START )).andReturn(expectedSensor); END } verifySensor(() -> ProcessorNodeMetrics.lateRecordDropSensor(THREAD_ID, TASK_ID, PROCESSOR_NODE_ID, streamsMetrics)); } What is `expectedSensor` used here since it is just a mock? I feel we can just state that we expect it to be called but not specify returning anything?

Target:
public void shouldGetLateRecordDropSensor() { final String metricNamePrefix = "late-record-drop"; final String descriptionOfCount = "The total number of dropped late records"; final String descriptionOfRate = "The average number of dropped late records per second"; setUpThroughputSensor( metricNamePrefix, descriptionOfRate, descriptionOfCount, RecordingLevel.INFO ); verifySensor(() -> ProcessorNodeMetrics.lateRecordDropSensor(THREAD_ID, TASK_ID, PROCESSOR_NODE_ID, streamsMetrics)); }
Source:
START public NewPartitionReassignment(List<Integer> targetReplicas) { END this.targetReplicas = Collections.unmodifiableList(new ArrayList<>(targetReplicas)); } Does this need to be public? Making it private forces use of `of` method, which I think is good.

Target:
private NewPartitionReassignment(List<Integer> targetReplicas) { this.targetReplicas = Collections.unmodifiableList(new ArrayList<>(targetReplicas)); }
Source:
public static synchronized void unregisterAppInfo(String prefix, String id, Metrics metrics) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { START id = id == null ? "" : id; END ObjectName name = new ObjectName(prefix + ":type=app-info,id=" + Sanitizer.jmxSanitize(id)); if (server.isRegistered(name)) server.unregisterMBean(name); unregisterMetrics(metrics); } catch (JMException e) { log.warn("Error unregistering AppInfo mbean", e); } } Hmm, maybe we can move this check into the KafkaConsumer's catch block before `close` also.

Target:
public static synchronized void unregisterAppInfo(String prefix, String id, Metrics metrics) { MBeanServer server = ManagementFactory.getPlatformMBeanServer(); try { ObjectName name = new ObjectName(prefix + ":type=app-info,id=" + Sanitizer.jmxSanitize(id)); if (server.isRegistered(name)) server.unregisterMBean(name); unregisterMetrics(metrics); } catch (JMException e) { log.warn("Error unregistering AppInfo mbean", e); } }
Source:
public void add(TopicPartition topicPartition, PartitionData data) { START if (sessionPartitions.containsKey(topicPartition)) { END altered.add(topicPartition); } else { added.add(topicPartition); } next.put(topicPartition, data); sessionPartitions.put(topicPartition, data); } I think you may be able to `.put` the added PartitionData into sessionPartitions up front, and capture the value returned by the `.put`, as it will return the previous value. If the previous value was null, then we add to added, if it was not null we add it to altered. This will save us the additional containsKey check.

Target:
public void add(TopicPartition topicPartition, PartitionData data) { if (sessionPartitions.put(topicPartition, data) != null) { altered.add(topicPartition); } else { added.add(topicPartition); } next.put(topicPartition, data); }
Source:
public void remove(TopicPartition topicPartition) { removed.add(topicPartition); START next.remove(topicPartition); END sessionPartitions.remove(topicPartition); } Will any of these partitions be in next? My assumption is that they would not be in partitionStates and would not be in next if they are being removed (especially if we get the locking right). Of course, they would be in sessionPartitions.

Target:
public void remove(TopicPartition topicPartition) { if (sessionPartitions.remove(topicPartition) != null) { removed.add(topicPartition); } // we do not need to call next.remove assuming the caller would not add and then remove // the same element within the same iteration (which is true in both Fetcher and ReplicaFetcherThread), // so saving the search here. }
Source:
public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable throwable) { ApiError error = ApiError.fromThrowable(throwable); DescribeAclsResponseData response = new DescribeAclsResponseData() .setThrottleTimeMs(throttleTimeMs) .setErrorCode(error.error().code()) .setErrorMessage(error.message()) START .setResources(Collections.emptyList()); END return new DescribeAclsResponse(response); } This is not necessary, right?

Target:
public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable throwable) { ApiError error = ApiError.fromThrowable(throwable); DescribeAclsResponseData response = new DescribeAclsResponseData() .setThrottleTimeMs(throttleTimeMs) .setErrorCode(error.error().code()) .setErrorMessage(error.message()); return new DescribeAclsResponse(response); }
Source:
public int bytesRead() { if (buffer == null) return size.position(); START return payload().position() + size.position(); END } Looks odd to use `buffer` a couple of lines above and `payload()` here since both refer to the same thing.

Target:
public int bytesRead() { if (buffer == null) return size.position(); return buffer.position() + size.position(); }
Source:
START @Override public Void deserialize(String topic, byte[] data) { END if (data != null) throw new IllegalArgumentException("Data should be null for a VoidDeserializer."); return null; } nit: put `@Override` on its own line

Target:
public Void deserialize(String topic, byte[] data) { if (data != null) throw new IllegalArgumentException("Data should be null for a VoidDeserializer."); return null; }
Source:
public void close() { START this.adminClient.close(Duration.ZERO); END } The default implementation of `close()` is to wait forever. What's the reasoning for using `Duration.ZERO` here?

Target:
public void close() { this.adminClient.close(); }
Source:
private ConsumerRebalanceListener getConsumerRebalanceListener(final KafkaConsumer<String, String> consumer) { return new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection<TopicPartition> partitions) { } @Override public void onPartitionsAssigned(Collection<TopicPartition> partitions) { // set initial position so we don't need a lookup for (TopicPartition partition : partitions) consumer.seek(partition, 0); } @Override public void onPartitionsLost(Collection<TopicPartition> partitions) { START System.out.println("hit partitions lost " + partitions); END } }; } Is this an outdated debug statement? If not, maybe add a similar line to `onPartitionsRevoked()` ?

Target:
private ConsumerRebalanceListener getConsumerRebalanceListener(final KafkaConsumer<String, String> consumer) { return new ConsumerRebalanceListener() { @Override public void onPartitionsRevoked(Collection<TopicPartition> partitions) { } @Override public void onPartitionsAssigned(Collection<TopicPartition> partitions) { // set initial position so we don't need a lookup for (TopicPartition partition : partitions) consumer.seek(partition, 0); } }; }
Source:
START public ConnectionMetadata get(String connectionId) { END return connections.get(connectionId); } This is wrong. Unsynchronized access to a map could cause more than just "stale or inconsistent" data. It could cause null pointer exceptions or other issues. We cannot access this without synchronization.

Target:
public synchronized ConnectionMetadata get(String connectionId) { return connections.get(connectionId); }
Source:
START OptionalLong lastAckedOffset(TopicPartition topicPartition) { END TopicPartitionEntry entry = topicPartitions.get(topicPartition); if (entry != null && entry.lastAckedOffset != ProduceResponse.INVALID_OFFSET) return OptionalLong.of(entry.lastAckedOffset); else return OptionalLong.empty(); } nit: better to make functions private if we do not have intention to have them accessed by other classes

Target:
private OptionalLong lastAckedOffset(TopicPartition topicPartition) { TopicPartitionEntry entry = topicPartitions.get(topicPartition); if (entry != null && entry.lastAckedOffset != ProduceResponse.INVALID_OFFSET) return OptionalLong.of(entry.lastAckedOffset); else return OptionalLong.empty(); }
Source:
START private boolean isNextSequenceForUnresolvedPartition(TopicPartition topicPartition, int sequence) { END if (this.hasUnresolvedSequence(topicPartition)) { return sequence == this.partitionsWithUnresolvedSequences.get(topicPartition); } return false; } Could be simplified as: `hasUnresolvedSequence(topicPartition) && sequence == this.partitionsWithUnresolvedSequences.get(topicPartition)`

Target:
private boolean isNextSequenceForUnresolvedPartition(TopicPartition topicPartition, int sequence) { return this.hasUnresolvedSequence(topicPartition) && sequence == this.partitionsWithUnresolvedSequences.get(topicPartition); }
Source:
START public void testInitProducerIdRequest() throws Exception { END final long producerId = 343434L; TransactionManager transactionManager = createTransactionManager(); setupWithTransactionState(transactionManager); prepareAndReceiveInitProducerId(producerId, Errors.NONE); assertTrue(transactionManager.hasProducerId()); assertEquals(producerId, transactionManager.producerIdAndEpoch().producerId); assertEquals((short) 0, transactionManager.producerIdAndEpoch().epoch); } nit: the exception is no longer thrown.

Target:
public void testInitProducerIdRequest() { final long producerId = 343434L; TransactionManager transactionManager = createTransactionManager(); setupWithTransactionState(transactionManager); prepareAndReceiveInitProducerId(producerId, Errors.NONE); assertTrue(transactionManager.hasProducerId()); assertEquals(producerId, transactionManager.producerIdAndEpoch().producerId); assertEquals((short) 0, transactionManager.producerIdAndEpoch().epoch); }
Source:
private int maybeUpdateLastAckedSequence(TopicPartition topicPartition, int sequence) { if (sequence > lastAckedSequence(topicPartition).orElse(NO_LAST_ACKED_SEQUENCE_NUMBER)) { topicPartitionBookkeeper.getPartition(topicPartition).lastAckedSequence = sequence; return sequence; } START return NO_LAST_ACKED_SEQUENCE_NUMBER; END } This doesn't seem right. `lastAckedSequence(topicPartition)` may exist.

Target:
private int maybeUpdateLastAckedSequence(TopicPartition topicPartition, int sequence) { int lastAckedSequence = lastAckedSequence(topicPartition).orElse(NO_LAST_ACKED_SEQUENCE_NUMBER); if (sequence > lastAckedSequence) { topicPartitionBookkeeper.getPartition(topicPartition).lastAckedSequence = sequence; return sequence; } return lastAckedSequence; }
Source:
private int maybeUpdateLastAckedSequence(TopicPartition topicPartition, int sequence) { if (sequence > lastAckedSequence(topicPartition).orElse(NO_LAST_ACKED_SEQUENCE_NUMBER)) { topicPartitionBookkeeper.getPartition(topicPartition).lastAckedSequence = sequence; return sequence; } START return lastAckedSequence(topicPartition).orElse(NO_LAST_ACKED_SEQUENCE_NUMBER); END } nit: can we just put this in a variable?

Target:
private int maybeUpdateLastAckedSequence(TopicPartition topicPartition, int sequence) { int lastAckedSequence = lastAckedSequence(topicPartition).orElse(NO_LAST_ACKED_SEQUENCE_NUMBER); if (sequence > lastAckedSequence) { topicPartitionBookkeeper.getPartition(topicPartition).lastAckedSequence = sequence; return sequence; } return lastAckedSequence; }
Source:
int maybeCommitActiveTasksPerUserRequested() { START if (!rebalanceInProgress) { END return active.maybeCommitPerUserRequested(); } return -1; } nit: Ternary operator seems easier to use.

Target:
int maybeCommitActiveTasksPerUserRequested() { return rebalanceInProgress ? -1 : active.maybeCommitPerUserRequested(); }
Source:
int commitAll() { START if (rebalanceInProgress) { END return -1; } final int committed = active.commit(); return committed + standby.commit(); } As long as we have separate tags for standby and primary tasks commit, I don't think the metrics will be messed up.

Target:
int commitAll() { return rebalanceInProgress ? -1 : active.commit() + standby.commit(); }
Source:
public void shouldAllowCleanupBeforeStartAndAfterClose() { final KafkaStreams streams = new KafkaStreams(new StreamsBuilder().build(), props, supplier, time); try { streams.cleanUp(); streams.start(); } finally { streams.close(); } START streams.cleanUp(); END } What's up with this last one? Should it be in the finally block?

Target:
public void shouldAllowCleanupBeforeStartAndAfterClose() { final KafkaStreams streams = new KafkaStreams(new StreamsBuilder().build(), props, supplier, time); try { streams.cleanUp(); streams.start(); } finally { streams.close(); streams.cleanUp(); } }
Source:
public PluginClassLoader pluginClassLoader(String name) { if (!PluginUtils.shouldLoadInIsolation(name)) { return null; } SortedMap<PluginDesc<?>, ClassLoader> inner = pluginLoaders.get(name); if (inner == null) { return null; } ClassLoader pluginLoader = inner.get(inner.lastKey()); START if (!(pluginLoader instanceof PluginClassLoader)) { END return null; } return (PluginClassLoader) pluginLoader; } `return pluginLoader instanceof PluginClassLoader ? (PluginClassLoader) pluginLoader : null;` wdyt? keeps the instanceof closer to the cast and it's concise.

Target:
public PluginClassLoader pluginClassLoader(String name) { if (!PluginUtils.shouldLoadInIsolation(name)) { return null; } SortedMap<PluginDesc<?>, ClassLoader> inner = pluginLoaders.get(name); if (inner == null) { return null; } ClassLoader pluginLoader = inner.get(inner.lastKey()); return pluginLoader instanceof PluginClassLoader ? (PluginClassLoader) pluginLoader : null; }
Source:
public RebalanceInProgressException() { START super("Request cannot be completed since the consumer group is rebalancing. This can happen when a group has started, " + END "but not finished rebalancing before the request is sent. You can try completing the rebalance " + "by calling poll() and then retry the operation"); } Why not have this extend `RetriableCommitFailedException`?

Target:
public RebalanceInProgressException() { super(); }
Source:
START public AlterConsumerGroupOffsetsResult(KafkaFuture<Map<TopicPartition, Errors>> future) { END this.future = future; } Usually we use default access constructors for these Result types. Similarly for `ListOffsetsResult`.

Target:
AlterConsumerGroupOffsetsResult(KafkaFuture<Map<TopicPartition, Errors>> future) { this.future = future; }
Source:
START public boolean shouldRefreshCoordinator(Errors error) { END return error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.COORDINATOR_NOT_AVAILABLE; } This method could be static since it does not depend on any local state. Same for `hasCoordinatorMoved`.

Target:
public static boolean shouldRefreshCoordinator(Errors error) { return error == Errors.COORDINATOR_LOAD_IN_PROGRESS || error == Errors.COORDINATOR_NOT_AVAILABLE; }
Source:
START public ListOffsetsResultInfo(long offset, long timestamp, Optional<Integer> leaderEpoch) { END this.offset = offset; this.timestamp = timestamp; this.leaderEpoch = leaderEpoch; } Default access here too?

Target:
ListOffsetsResultInfo(long offset, long timestamp, Optional<Integer> leaderEpoch) { this.offset = offset; this.timestamp = timestamp; this.leaderEpoch = leaderEpoch; }
Source:
public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows, final StreamJoined<K, V, VO> streamJoined) { return doJoin( START otherStream, END joiner, windows, streamJoined, new KStreamImplJoin(this, false, false) ); } nit: `doJoin(otherStream,` (no new line)

Target:
public <VO, VR> KStream<K, VR> join(final KStream<K, VO> otherStream, final ValueJoiner<? super V, ? super VO, ? extends VR> joiner, final JoinWindows windows, final StreamJoined<K, V, VO> streamJoined) { return doJoin(otherStream, joiner, windows, streamJoined, new KStreamImplJoin(builder, false, false) ); }
Source:
START public void forEachAssignedPartition(Consumer<TopicPartition> consumer) { END this.assignment.partitionSet().forEach(consumer); } Should this be synchronized?

Target:
public synchronized void forEachAssignedPartition(Consumer<TopicPartition> consumer) { this.assignment.partitionSet().forEach(consumer); }
Source:
private void resetOffsetIfNeeded(TopicPartition partition, OffsetResetStrategy requestedResetStrategy, ListOffsetData offsetData) { SubscriptionState.FetchPosition position = new SubscriptionState.FetchPosition( offsetData.offset, offsetData.leaderEpoch, metadata.leaderAndEpoch(partition)); offsetData.leaderEpoch.ifPresent(epoch -> metadata.updateLastSeenEpochIfNewer(partition, epoch)); START subscriptions.maybeSeekUnvalidated(partition, position, requestedResetStrategy); END } Mentioned offline, but there is actually a behavioral change here. Previously we didn't validate after an offset reset in any case, but now I think we might if the offset returned from the ListOffset request has an epoch. I think the simple thing to do is to use `Optional.empty()` above when defining `position`.

Target:
private void resetOffsetIfNeeded(TopicPartition partition, OffsetResetStrategy requestedResetStrategy, ListOffsetData offsetData) { SubscriptionState.FetchPosition position = new SubscriptionState.FetchPosition( offsetData.offset, Optional.empty(), // This will ensure we skip validation metadata.leaderAndEpoch(partition)); offsetData.leaderEpoch.ifPresent(epoch -> metadata.updateLastSeenEpochIfNewer(partition, epoch)); subscriptions.maybeSeekUnvalidated(partition, position, requestedResetStrategy); }
Source:
private boolean isMuted(TopicPartition tp, long now) { Long throttleUntilTime = muted.get(tp); boolean result = throttleUntilTime != null && throttleUntilTime > now; START if (!result) END muted.remove(tp); return result; } This should probably be `throttleUntilTime != null && throttleUntilTime <= now` or something?

Target:
private boolean isMuted(TopicPartition tp, long now) { // Take care to avoid unnecessary map look-ups because this method is a hotspot if producing to a // large number of partitions Long throttleUntilTime = muted.get(tp); if (throttleUntilTime == null) return false; if (now >= throttleUntilTime) { muted.remove(tp); return false; } return true; }
Source:
private boolean isMuted(TopicPartition tp, long now) { Long throttleUntilTime = muted.get(tp); boolean unmute = throttleUntilTime != null && now >= throttleUntilTime; if (unmute) muted.remove(tp); START return unmute; END } I think this got inverted, no?

Target:
private boolean isMuted(TopicPartition tp, long now) { // Take care to avoid unnecessary map look-ups because this method is a hotspot if producing to a // large number of partitions Long throttleUntilTime = muted.get(tp); if (throttleUntilTime == null) return false; if (now >= throttleUntilTime) { muted.remove(tp); return false; } return true; }
Source:
START private AdminClient createAdminClient() { END final Properties properties = new Properties(); properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers()); return AdminClient.create(properties); } method should be static

Target:
private static AdminClient createAdminClient() { final Properties properties = new Properties(); properties.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, CLUSTER.bootstrapServers()); return AdminClient.create(properties); }
Source:
public KStream<K, V> repartition(final Repartitioned<K, V> repartitioned) { START Objects.requireNonNull(repartitioned, "repartitioned parameter can't be null"); END return doRepartition(repartitioned, null); } We can do all `null` checks in a single place within `doRepartition()` -- also, all other methods just say ` <parameterName> can't be null` (ie, please remove `parameter` for consistency)

Target:
public KStream<K, V> repartition(final Repartitioned<K, V> repartitioned) { return doRepartition(repartitioned); }
Source:
public boolean rejoinNeededOrPending() { if (!subscriptions.partitionsAutoAssigned()) return false; // we need to rejoin if we performed the assignment and metadata has changed if (assignmentSnapshot != null && !assignmentSnapshot.matches(metadataSnapshot)) { START maybeLosePartitions("topic metadata has changed and therefore some topics may not exist any moreq"); END return true; } // we need to join if our subscription has changed since the last join if (joinedSubscription != null && !joinedSubscription.equals(subscriptions.subscription())) { maybeLosePartitions("consumer subscription has changed since last joined generation"); return true; } return super.rejoinNeededOrPending(); } typo: moreq -> more

Target:
public boolean rejoinNeededOrPending() { if (!subscriptions.partitionsAutoAssigned()) return false; // we need to rejoin if we performed the assignment and metadata has changed; // also for those owned-but-no-longer-existed partitions we should drop them as lost if (assignmentSnapshot != null && !assignmentSnapshot.matches(metadataSnapshot)) return true; // we need to join if our subscription has changed since the last join if (joinedSubscription != null && !joinedSubscription.equals(subscriptions.subscription())) { return true; } return super.rejoinNeededOrPending(); }
Source:
public void close(Duration timeout) { if (timeout.toMillis() < 0) throw new IllegalArgumentException("The timeout cannot be negative."); acquire(); try { if (!closed) { close(timeout.toMillis(), false); START closed = true; END } } finally { release(); } } What was the motivation to change this?

Target:
public void close(Duration timeout) { if (timeout.toMillis() < 0) throw new IllegalArgumentException("The timeout cannot be negative."); acquire(); try { if (!closed) { // need to close before setting the flag since the close function // itself may trigger rebalance callback that needs the consumer to be open still close(timeout.toMillis(), false); } } finally { closed = true; release(); } }
Source:
private Topology createConnectedStateStoreTopology(final String storeName) { START final StoreBuilder<KeyValueStore<String, String>> storeBuilder = Stores.keyValueStoreBuilder(Stores.inMemoryKeyValueStore(storeName), Serdes.String(), Serdes.String()); END return topology .addSource("source", STRING_DESERIALIZER, STRING_DESERIALIZER, INPUT_TOPIC_1) .addProcessor("processor", defineWithStores(new StatefulProcessor(storeName), Collections.singleton(storeBuilder)), "source") .addSink("counts", OUTPUT_TOPIC_1, "processor"); } nit: line too long

Target:
private Topology createConnectedStateStoreTopology(final String storeName) { final StoreBuilder<KeyValueStore<String, String>> storeBuilder = Stores.keyValueStoreBuilder(Stores.inMemoryKeyValueStore(storeName), Serdes.String(), Serdes.String()); return topology .addSource("source", STRING_DESERIALIZER, STRING_DESERIALIZER, INPUT_TOPIC_1) .addProcessor("processor", defineWithStores(() -> new StatefulProcessor(storeName), Collections.singleton(storeBuilder)), "source") .addSink("counts", OUTPUT_TOPIC_1, "processor"); }
Source:
START protected DefaultRecord(int sizeInBytes, END byte attributes, long offset, long timestamp, int sequence, ByteBuffer key, ByteBuffer value, Header[] headers) { this.sizeInBytes = sizeInBytes; this.attributes = attributes; this.offset = offset; this.timestamp = timestamp; this.sequence = sequence; this.key = key; this.value = value; this.headers = headers; } Default access is probably good enough and is consistent with `PartialDefaultRecord`.

Target:
DefaultRecord(int sizeInBytes, byte attributes, long offset, long timestamp, int sequence, ByteBuffer key, ByteBuffer value, Header[] headers) { this.sizeInBytes = sizeInBytes; this.attributes = attributes; this.offset = offset; this.timestamp = timestamp; this.sequence = sequence; this.key = key; this.value = value; this.headers = headers; }
Source:
START private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { END boolean needMore = false; while (true) { if (needMore) { readMore(buffer, input, bytesRemaining); needMore = false; } if (buffer.remaining() < 1 && bytesRemaining.value > 0) { needMore = true; } else { return buffer.get(); } } } I think we can simplify these functions. Something like this: ```java private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 1) readMore(buffer, input, bytesRemaining); return buffer.get(); } private static long readVarLong(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 10 && bytesRemaining.value > 0) readMore(buffer, input, bytesRemaining); return ByteUtils.readVarlong(buffer); } private static int readVarInt(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 10 && bytesRemaining.value > 0) readMore(buffer, input, bytesRemaining); return ByteUtils.readVarint(buffer); } ``` I think we shouldn't need more than one call to `readMore`.

Target:
private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 1 && bytesRemaining.value > 0) { readMore(buffer, input, bytesRemaining); } return buffer.get(); }
Source:
public Object evaluate(Object feature) { Map map = getExpression(0).evaluate(feature, Map.class); String key = getExpression(1).evaluate(feature, String.class); START if (map.containsKey(key)) { END return map.get(key); } return null; } NPE prone, check if map is not null. Also, no need to check if the map contains, one can simply call get: ```suggestion if (map != null) { return map.get(key); } ```

Target:
public Object evaluate(Object feature) { Map map = getExpression(0).evaluate(feature, Map.class); String key = getExpression(1).evaluate(feature, String.class); if (map != null) { return map.get(key); } return null; }
Source:
public boolean eIsSet(int featureID) { switch (featureID) { case Csw20Package.QUERY_TYPE__ELEMENT_SET_NAME: return elementSetName != null; case Csw20Package.QUERY_TYPE__ELEMENT_NAME: return elementName != null && !elementName.isEmpty(); case Csw20Package.QUERY_TYPE__CONSTRAINT: return constraint != null; case Csw20Package.QUERY_TYPE__SORT_BY: START return SORT_BY_EDEFAULT == null ? sortBy != null : !Arrays.equals(SORT_BY_EDEFAULT, sortBy); END case Csw20Package.QUERY_TYPE__TYPE_NAMES: return typeNames != null; } return super.eIsSet(featureID); } I am never quite sure how to use error prone in IntelliJ, perhaps @aaime has guidance. Does error prone require some configuration to ignore these autogenerated folders?

Target:
public boolean eIsSet(int featureID) { switch (featureID) { case Csw20Package.QUERY_TYPE__ELEMENT_SET_NAME: return elementSetName != null; case Csw20Package.QUERY_TYPE__ELEMENT_NAME: return elementName != null && !elementName.isEmpty(); case Csw20Package.QUERY_TYPE__CONSTRAINT: return constraint != null; case Csw20Package.QUERY_TYPE__SORT_BY: return SORT_BY_EDEFAULT == null ? sortBy != null : !SORT_BY_EDEFAULT.equals(sortBy); case Csw20Package.QUERY_TYPE__TYPE_NAMES: return typeNames != null; } return super.eIsSet(featureID); }
Source:
protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException { Filter f = query.getFilter(); START if (f != null && f.equals(Filter.INCLUDE)) { END try { return new ReferencedEnvelope( CRS.transform(mbtiles.loadMetaData().getBounds(), DEFAULT_CRS)); } catch (TransformException e) { throw new RuntimeException("Unable to retrieve bounds from mbtiles metadata", e); } } else { // summing up all feature bounds would be expensive. // returning null return null; } } ```suggestion if (f == null || f.equals(Filter.INCLUDE)) { ```

Target:
protected ReferencedEnvelope getBoundsInternal(Query query) throws IOException { Filter f = query.getFilter(); if (f == null || f.equals(Filter.INCLUDE)) { try { return new ReferencedEnvelope( CRS.transform(mbtiles.loadMetaData().getBounds(), DEFAULT_CRS)); } catch (TransformException e) { throw new RuntimeException("Unable to retrieve bounds from mbtiles metadata", e); } } else { // summing up all feature bounds would be expensive. // returning null return null; } }
Source:
public boolean hasUserData() { START return userData != null; END } A question: Omitting the map.isEmpty() check is intended? Overrided default method does the check but here only a null check is done.

Target:
public boolean hasUserData() { return userData != null && !userData.isEmpty(); }
Source:
public void registerSqlTypeToSqlTypeNameOverrides(Map<Integer, String> overrides) { //Step 1 Geos-7533 put the types in dialect START overrides.put(4, "int4"); END overrides.put(Types.VARCHAR, "VARCHAR"); overrides.put(Types.BOOLEAN, "BOOL"); overrides.put(Types.BLOB, "BYTEA"); } Please use ``Types.INTEGER`` instead of ``4``.

Target:
public void registerSqlTypeToSqlTypeNameOverrides(Map<Integer, String> overrides) { overrides.put(Types.VARCHAR, "VARCHAR"); overrides.put(Types.BOOLEAN, "BOOL"); overrides.put(Types.BLOB, "BYTEA"); }
Source:
private boolean isValidDomain(double minx, double maxx, double miny, double maxy) { final int width = (int) (maxx - minx); final int height = (int) (maxy - miny); START if (abs(width) == 0 || height == 0) { END return false; } return true; } Can be simpler, return directly: ``return abs(width) > 0 && abs(height)== 0``

Target:
private boolean isValidDomain(double minx, double maxx, double miny, double maxy) { final int width = (int) (maxx - minx); final int height = (int) (maxy - miny); return width > 0 && height > 0; }
Source:
protected AttributesImpl cloneWithGmlId(AttributesImpl atts, String gmlId) { if (gmlId == null) { return atts; } AttributesImpl result; if (atts == null) { result = new AttributesImpl(); } else { result = new AttributesImpl(atts); } START if (encodeGmlId) addGmlId(result, gmlId); END return result; } Probably best at the beginning, ``if gmlId == null || !encodeGMlId``

Target:
protected AttributesImpl cloneWithGmlId(AttributesImpl atts, String gmlId) { if (gmlId == null || !encodeGmlId) { return atts; } AttributesImpl result; if (atts == null) { result = new AttributesImpl(); } else { result = new AttributesImpl(atts); } addGmlId(result, gmlId); return result; }
Source:
START private Object invertGeometryCoordinates(Geometry geometry) throws TransformException { END return transformer.transform(geometry); } Works anyways but a bit weird to have it return an Object, would look better returning a Geometry (that's what the transformer.tranfsorm method does). Not a critical issue, fix if you like.

Target:
private Geometry invertGeometryCoordinates(Geometry geometry) throws TransformException { return transformer.transform(geometry); }
Source:
public void testHiddenTables() throws IOException { String[] typenames = dataStore.getTypeNames(); for (String name:typenames) { START System.out.println(name); END System.out.println(tname(name)); assertFalse("Name should not end with 'MDXT_'",name.startsWith("MDXT_")); assertFalse("Name should not end with '$_BKTS'",name.endsWith("$_BKTS")); assertFalse("Name should not end with '$'",name.endsWith("$")); } } No system outs in tests please (yes, there might be some around, they are leftovers that should not be there)

Target:
public void testHiddenTables() throws IOException { String[] typenames = dataStore.getTypeNames(); for (String name:typenames) { assertFalse("Name should not end with 'MDXT_'",name.startsWith("MDXT_")); assertFalse("Name should not end with '$_BKTS'",name.endsWith("$_BKTS")); assertFalse("Name should not end with '$'",name.endsWith("$")); } }
Source:
public Map<String,String> getSupportedFunctions() { if ( supportedFunctions == null ) { START supportedFunctions = new HashMap(); END dialect.registerFunctions(supportedFunctions); } return supportedFunctions; } Generics, new HashMap<>();

Target:
public Map<String, String> getSupportedFunctions() { if (supportedFunctions == null) { supportedFunctions = new HashMap<>(); dialect.registerFunctions(supportedFunctions); } return supportedFunctions; }
Source:
for (PropertyAccessorFactory factory : ServiceLoader.load(PropertyAccessorFactory.class)) { boolean nonCached = factory instanceof SimpleFeaturePropertyAccessorFactory || factory instanceof DirectPropertyAccessorFactory || factory instanceof NullPropertyAccessorFactory; if (!nonCached) START cache.add(factory); END } Thanks that is a clear way to describe the cache condition. We tend to use braces even for single line if statements

Target:
for (PropertyAccessorFactory factory : ServiceLoader.load(PropertyAccessorFactory.class)) { boolean nonCached = factory instanceof SimpleFeaturePropertyAccessorFactory || factory instanceof DirectPropertyAccessorFactory || factory instanceof NullPropertyAccessorFactory; if (!nonCached) { cache.add(factory); } }
Source:
public void setLatLonBoundingBox(CRSEnvelope latLonBoundingBox) { if( latLonBoundingBox.getSRSName() != null ){ String srsName = latLonBoundingBox.getSRSName(); if( !srsName.equals("CRS:84")){ throw new IllegalStateException("Layer LatLonBoundingBox srsName required to be null or CRS:84"); } START }else { END latLonBoundingBox.setSRSName("CRS:84",false);; } this.latLonBoundingBox = latLonBoundingBox; } Formatting, it should be "} else {". I won't repeat this for all occurrences, please check the diffs and make sure the changes (and only those) respect the coding conventions

Target:
public void setLatLonBoundingBox(CRSEnvelope latLonBoundingBox) { if( latLonBoundingBox.getSRSName() != null ){ String srsName = latLonBoundingBox.getSRSName(); if( !srsName.equals("CRS:84")){ throw new IllegalStateException("Layer LatLonBoundingBox srsName required to be null or CRS:84"); } } else { latLonBoundingBox.setSRSName("CRS:84",false); } this.latLonBoundingBox = latLonBoundingBox; }
Source:
public List<String> getTextFont() { String[] fonts; START if (!(layout.get("text-font") instanceof JSONObject)) { END fonts = parse.array(String.class, layout, "text-font", new String[]{"Open Sans Regular", "Arial Unicode MS Regular"}); return Arrays.asList(fonts); } else { return null; } } Bit of a nitpick, but since we already have an if-else, using: ``` if (layout.get("text-font") instanceof JSONObject) { return null } else { ... } ``` would be a bit clearer.

Target:
public List<String> getTextFont() { String[] fonts; if (layout.get("text-font") instanceof JSONObject) { return null; } else { fonts = parse.array(String.class, layout, "text-font", new String[]{"Open Sans Regular", "Arial Unicode MS Regular"}); return Arrays.asList(fonts); } }
Source:
protected ReferencedEnvelope calculateBounds() { ReferencedEnvelope extent = ReferencedEnvelope.create( getSchema().getCoordinateReferenceSystem() ); for( SimpleFeature feature : list ){ START if( feature == null ) END continue; ReferencedEnvelope bbox = ReferencedEnvelope.reference( feature.getBounds() ); if( bbox == null || bbox.isEmpty() || bbox.isNull() ) continue; extent.expandToInclude( bbox ); } return extent; } we tend to use braces when placing a statement on a seperate line, check developers guide for sun-java-conventions + 100 cols.

Target:
protected ReferencedEnvelope calculateBounds() { ReferencedEnvelope extent = ReferencedEnvelope.create( getSchema().getCoordinateReferenceSystem() ); for( SimpleFeature feature : list ){ if( feature == null ) { continue; } ReferencedEnvelope bbox = ReferencedEnvelope.reference( feature.getBounds() ); if( bbox == null || bbox.isEmpty() || bbox.isNull() ) { continue; } extent.expandToInclude( bbox ); } return extent; }