auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public TorrentStatistic getStatistics(String dotTorrentFilePath) throws IOException { FileMetadataProvider metadataProvider = new FileMetadataProvider(dotTorrentFilePath); TorrentMetadata metadata = metadataProvider.getTorrentMetadata(); LoadedTorrent loadedTorrent = communicationManager.getTorrentsStorage().getLoadedTorrent(metadata.getHexInfoHash()); if (loadedTorrent != null) { START return loadedTorrent.getTorrentStatistic(); END } throw new IllegalStateException("Torrent has not been loaded yet"); } let's return here a copy of `TorrentStatistic ` instance because this class is mutable

Target:
public TorrentStatistic getStatistics(String dotTorrentFilePath) throws IOException { FileMetadataProvider metadataProvider = new FileMetadataProvider(dotTorrentFilePath); TorrentMetadata metadata = metadataProvider.getTorrentMetadata(); LoadedTorrent loadedTorrent = communicationManager.getTorrentsStorage().getLoadedTorrent(metadata.getHexInfoHash()); if (loadedTorrent != null) { return new TorrentStatistic(loadedTorrent.getTorrentStatistic()); } throw new IllegalStateException("Torrent has not been loaded yet"); }
Source:
public static byte[] hash(byte[] data) throws NoSuchAlgorithmException { MessageDigest crypt; crypt = MessageDigest.getInstance("SHA-1"); crypt.reset(); crypt.update(data); START return crypt.digest(); END } Can you call the other version of `hash()` from here instead? ``` java public static byte[] hash(byte[] data) throws NoSuchAlgorithmException { return hash(data, 0, data.length); } ```

Target:
public static byte[] hash(byte[] data) throws NoSuchAlgorithmException { return hash(data, 0, data.length); }
Source:
START static Pair<TextSelection, Boolean> getSelection(@NotNull Editor editor) { END SelectionModel selectionModel = editor.getSelectionModel(); int selectionStart = selectionModel.getSelectionStart(); int selectionEnd = selectionModel.getSelectionEnd(); TextSelection selection = calculateSelectionPosition(editor, selectionStart, selectionEnd); boolean isBackwardsSelection = isBackwardsSelection(editor, selectionStart, selectionEnd); return new Pair<>(selection, isBackwardsSelection); } As already written in a previous PR: I would expect that isBackwardsSelection could be moved in TextSelection.

Target:
static TextSelection getSelection(@NotNull Editor editor) { SelectionModel selectionModel = editor.getSelectionModel(); int selectionStart = selectionModel.getSelectionStart(); int selectionEnd = selectionModel.getSelectionEnd(); return calculateSelectionPosition(editor, selectionStart, selectionEnd); }
Source:
START protected int getSize() { END return queue.size(); } Make package private? ```suggestion int getSize() { ```

Target:
int getSize() { return queue.size(); }
Source:
public void testInsertWhileNotEnable() { store.setValue(EclipsePreferenceConstants.SHOW_CONTRIBUTION_ANNOTATIONS, false); START final User ALICE_TEST_USER = new User(new JID("ALICE_TEST_USER@test"), false, false, null); END manager.insertAnnotation(model, 5, 7, ALICE_TEST_USER); assertEquals(0, getAnnotationCount(model)); } Remove and use static variable instead?

Target:
public void testInsertWhileNotEnable() { store.setValue(EclipsePreferenceConstants.SHOW_CONTRIBUTION_ANNOTATIONS, false); manager.insertAnnotation(model, 5, 7, ALICE_TEST_USER); assertEquals(0, getAnnotationCount(model)); }
Source:
public void asyncExec(Runnable runnable) { try { EDTExecutor.invokeLater(runnable); } catch (ProcessCanceledException e) { START log.error("Synchronous execution on EDT interrupted - " + runnable, e); END } } ```suggestion log.error("Asynchronous execution on EDT interrupted - " + runnable, e); ```

Target:
public void asyncExec(Runnable runnable) { EDTExecutor.invokeLater(runnable); }
Source:
public boolean hasPrivilege(UserPrivilege.Keys privilege) { //System.out.println("3 - hasPrivilege() " + privilege + " : " + this.privileges.containsKey(privilege)); if (this.privileges.containsKey(privilege)) { START return this.privileges.get(privilege).getValue(); END } return false; } NPE

Target:
public synchronized boolean hasPrivilege(UserPrivilege.Keys privilege) { if (this.privileges.containsKey(privilege)) { return this.privileges.get(privilege).getValue(); } return false; }
Source:
START static String getRequireBundleValue(File manifestFile) { END String bundleValue; try (FileInputStream manifestStream = new FileInputStream(manifestFile)) { Manifest manifest = new Manifest(manifestStream); bundleValue = manifest.getMainAttributes().getValue(REQUIRE_BUNDLE_KEY); } catch (IOException e) { throw new GradleException( "Unable to determine the bundle dependencies defined in manifest: " + manifestFile.getAbsolutePath(), e); } return bundleValue; } Can be private according to IntelliJ code inspection.

Target:
private static String getRequireBundleValue(File manifestFile) { String bundleValue; try (FileInputStream manifestStream = new FileInputStream(manifestFile)) { Manifest manifest = new Manifest(manifestStream); bundleValue = manifest.getMainAttributes().getValue(REQUIRE_BUNDLE_KEY); } catch (IOException e) { throw new GradleException( "Unable to determine the bundle dependencies defined in manifest: " + manifestFile.getAbsolutePath(), e); } return bundleValue; }
Source:
START static String[] parseRequireBundleValue(String value, List<String> bundlesToExclude) { END return Arrays.stream(value.split(",")) .map( (it) -> { return it.split(";")[0]; }) .filter( (it) -> { return !bundlesToExclude.contains(it); }) .toArray(String[]::new); } Can be private according to IntelliJ code inspection.

Target:
private static String[] parseRequireBundleValue(String value, List<String> bundlesToExclude) { return Arrays.stream(value.split(",")) .map(it -> it.split(";")[0]) .filter(it -> !bundlesToExclude.contains(it)) .toArray(String[]::new); }
Source:
private Project getProjectFromSession() { ISarosSession currentSession = sarosSession; if (currentSession == null) { return null; } START SharedIDEContext sharedIDEContext = currentSession.getComponent(SharedIDEContext.class); END if (!sharedIDEContext.isInitialized()) { return null; } return sharedIDEContext.getProject(); } Nullcheck missing.

Target:
private Project getProjectFromSession() { ISarosSession currentSession = sarosSession; if (currentSession == null) { return null; } SharedIDEContext sharedIDEContext = currentSession.getComponent(SharedIDEContext.class); if (sharedIDEContext == null || !sharedIDEContext.isInitialized()) { return null; } return sharedIDEContext.getProject(); }
Source:
public boolean isOnline() { START if (status == Type.AVAILABLE || status == Type.AWAY) return true; END return false; } why not `return status == Type.AVAILABLE || status == Type.AWAY`

Target:
public boolean isOnline() { return status == Type.AVAILABLE || status == Type.AWAY; }
Source:
public void dispose() { sessionManager.removeSessionLifecycleListener(sessionLifecycleListener); ISarosSession currentSession = session; if (currentSession != null) { currentSession.removeListener(sessionListener); removeSessionNode(currentSession); } START sessionNodeList.clear(); END userNodeList.clear(); } The job of a dispose method is either to free unmanaged resources / memory and to deregister stuff properly so that the object can be garbage collected. Of course you can set all references to null / clear datastructures etc. to help the garbage collector but this is just boiler plate code with little benefits.

Target:
public void dispose() { sessionManager.removeSessionLifecycleListener(sessionLifecycleListener); ISarosSession currentSession = session; if (currentSession != null) { currentSession.removeListener(sessionListener); } }
Source:
private XStream createXStream() { START XStream xStream = new XStream(new DomDriver(CHARSET)); END xStream.alias("colorIDSet", ColorIDSet.class); return xStream; } Is this the same behavior as before ? To be more specific, is there any need for a charset at all ? Because you are producing already a string.

Target:
private XStream createXStream() { XStream xStream = new XStream(); xStream.alias("colorIDSet", ColorIDSet.class); return xStream; }
Source:
public void setSize(final int width, final int height) { START this.syncExec(() -> browser.setSize(width, height)); END } Isn't the coding convention like: omit "this" when it is not needed ?

Target:
public void setSize(final int width, final int height) { syncExec(() -> browser.setSize(width, height)); }
Source:
private void syncExec(final Runnable runnable) { final AtomicReference<RuntimeException> exception = new AtomicReference<RuntimeException>(); browser .getDisplay() .syncExec( () -> { try { runnable.run(); } catch (RuntimeException e) { exception.set(e); } START }); END if (exception.get() != null) { throw exception.get(); } } syncExec( () -> {runnable.run(); return null;});

Target:
private void syncExec(final Runnable runnable) { syncExec( () -> { runnable.run(); return null; }); }
Source:
public boolean selectionExists(ISelector selector) { START return (Boolean) END this.browser.syncRun(String.format("return %s.length > 0;", selector.getStatement())); } Can the value returned by ```Java this.browser.syncRun(String.format("return %s.length > 0;", selector.getStatement())) ``` be `null`? If this is the case, you need a nullcheck before returning the value as the implicit unboxing needed to convert the returned `Boolean` into a `boolean` (which is the actual return type of the method) will throw a NPE if the value is `null`.

Target:
public boolean selectionExists(ISelector selector) { Boolean result = (Boolean) this.browser.syncRun(String.format("return %s.length > 0;", selector.getStatement())); return result != null && result; }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ReferencePointImpl other = (ReferencePointImpl) obj; START if (path == null) { END if (other.path != null) return false; } else if (!path.equals(other.path)) return false; return true; } You can simplify the if-else block to ```Java if (path == null) { return other.path == null; } else { return path.equals(other.path); } ```

Target:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ReferencePointImpl other = (ReferencePointImpl) obj; if (!path.equals(other.path)) return false; return true; }
Source:
public SharedReferencePointMapper() { START idToReferencePointMapping = new HashMap<String, IReferencePoint>(); END referencePointToIDMapping = new HashMap<IReferencePoint, String>(); referencePointsOfUsers = new HashMap<User, List<String>>(); partiallySharedResourceMapping = new HashMap<IReferencePoint, Set<IResource>>(); completelySharedReferencePoints = new HashSet<IReferencePoint>(); partiallySharedReferencePoints = new HashSet<IReferencePoint>(); } Minor - Unnecessary type declarations during initialization. There are a lot of these in this class, so I'm not going to address them all individually.

Target:
public SharedReferencePointMapper() { idToReferencePointMapping = new HashMap(); referencePointToIDMapping = new HashMap(); referencePointsOfUsers = new HashMap(); partiallySharedResourceMapping = new HashMap(); completelySharedReferencePoints = new HashSet(); partiallySharedReferencePoints = new HashSet(); }
Source:
public synchronized void addMissingReferencePointsToUser(User user) { START List<String> referencePoints = new ArrayList<String>(); END for (String referencePoint : idToReferencePointMapping.keySet()) { referencePoints.add(referencePoint); } this.referencePointsOfUsers.put(user, referencePoints); } Loop can be replaced by passing the collection to CTOR: ```suggestion List<String> referencePoints = new ArrayList<>(idToReferencePointMapping.keySet()); ```

Target:
public synchronized void addMissingReferencePointsToUser(User user) { List<String> referencePoints = new ArrayList(idToReferencePointMapping.keySet()); this.referencePointsOfUsers.put(user, referencePoints); }
Source:
private static IActivityListener createForwarder(final IActivityConsumer target) { return new IActivityListener() { @Override public void created(IActivity activity) { if (activity instanceof GitRequestActivity) { target.exec(rewriteGitRequestActivity((GitRequestActivity) activity)); } else if (activity instanceof GitCollectActivity) { target.exec(rewriteGitCollectActivity((GitCollectActivity) activity)); } else if (activity instanceof GitSendBundleActivity) { target.exec(rewriteGitSendBundleActivity((GitSendBundleActivity) activity)); } else { START return; END } } }; } else branch is not needed

Target:
private static IActivityListener createForwarder(final IActivityConsumer target) { return new IActivityListener() { @Override public void created(IActivity activity) { if (activity instanceof GitRequestActivity) { target.exec(rewriteGitRequestActivity((GitRequestActivity) activity)); } else if (activity instanceof GitCollectActivity) { target.exec(rewriteGitCollectActivity((GitCollectActivity) activity)); } else if (activity instanceof GitSendBundleActivity) { target.exec(rewriteGitSendBundleActivity((GitSendBundleActivity) activity)); } } }; }
Source:
START public synchronized void start() { END session.addActivityConsumer(consumer, Priority.ACTIVE); session.addActivityProducer(this); } There is no need using synchronized here and in the stop method.

Target:
public void start() { session.addActivityConsumer(consumer, Priority.ACTIVE); session.addActivityProducer(this); }
Source:
void queueViewPortChange( @NotNull String path, @Nullable Editor editor, @Nullable LineRange range, @Nullable TextSelection selection) { QueuedViewPortChange requestedViewportChange = new QueuedViewPortChange(editor, range, selection); QueuedViewPortChange previouslyQueuedRequest = queuedViewPortChanges.put(path, requestedViewportChange); START if (previouslyQueuedRequest != null) { END if (log.isTraceEnabled()) { log.trace( "Dropping previously queued viewport change request for " + path + "; old request: " + previouslyQueuedRequest + ", new request: " + requestedViewportChange); } } } Can remain if you remove the `toString` method.

Target:
void queueViewPortChange( @NotNull String path, @Nullable Editor editor, @Nullable LineRange range, @Nullable TextSelection selection) { QueuedViewPortChange requestedViewportChange = new QueuedViewPortChange(editor, range, selection); queuedViewPortChanges.put(path, requestedViewportChange); }
Source:
public void run() { ISarosSession session = sessionManager.getSession(); JID jid = getSelectedJID(); if (session != null || jid == null) { return; } // TODO: Currently only Saros/S is known to have a working JoinSessionRequestHandler, // remove this once the situation changes / change this to it's own feature. START if (!discoveryManager.isFeatureSupported(jid, SarosConstants.NAMESPACE_SERVER)) { END return; } transmitter.sendPacketExtension( jid, JoinSessionRequestExtension.PROVIDER.create(new JoinSessionRequestExtension())); } Is there a reason to check twice whether the selected user is a Saros server (here and in line 445 of `SarosView`)? Or am I misunderstanding the checks? This check is also missing the null-check for the result of ´discoveryManager.isFeatureSupported(...)`.

Target:
public void run() { ISarosSession session = sessionManager.getSession(); JID jid = getSelectedJID(); if (session != null || jid == null) { return; } transmitter.sendPacketExtension( jid, JoinSessionRequestExtension.PROVIDER.create(new JoinSessionRequestExtension())); }
Source:
protected void executeCancellation() { START if (!session.isHost() || session.getRemoteUsers().isEmpty()) END sessionManager.stopSession(SessionEndReason.LOCAL_USER_LEFT); } ```suggestion if (session.isHost() && session.getRemoteUsers().isEmpty()) ``` you have to check if we are the host, otherwise the client disconnects on a canceled outgoing negotiation

Target:
protected void executeCancellation() { if (session.isHost() && session.getRemoteUsers().isEmpty()) sessionManager.stopSession(SessionEndReason.LOCAL_USER_LEFT); }
Source:
public void setEnabled(boolean enabled) { if (this.enabled && !enabled) { if (LOG.isTraceEnabled()) { START LOG.trace("Disabling filesystem listener"); END } this.enabled = false; intellijWorkspace.removeResourceListener(this); } else if (!this.enabled && enabled) { if (LOG.isTraceEnabled()) { LOG.trace("Enabling filesystem listener"); } this.enabled = true; intellijWorkspace.addResourceListener(this); } } the if around is not needed

Target:
public void setEnabled(boolean enabled) { if (this.enabled && !enabled) { LOG.trace("Disabling filesystem listener"); this.enabled = false; intellijWorkspace.removeResourceListener(this); } else if (!this.enabled && enabled) { LOG.trace("Enabling filesystem listener"); this.enabled = true; intellijWorkspace.addResourceListener(this); } }
Source:
START public synchronized IProject get(IReferencePoint referencePoint) { END if (referencePointToProjectMapper.containsKey(referencePoint)) { return referencePointToProjectMapper.get(referencePoint); } return null; } check not needed as `HashMap.get(...)` returns null if mapping for given key is not present

Target:
public synchronized IProject get(IReferencePoint referencePoint) { return referencePointToProjectMapper.get(referencePoint); }
Source:
private List<IRecord> create(BrowserAction action) { START List<IRecord> records = new LinkedList<IRecord>(); END // since the library fabric.js (used in the html whiteboard) does not // support parent hierarchies this function will always add the new // element to the root element ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; } ArrayList should be sufficient, this applies to all appearances in this patch set.

Target:
private List<IRecord> create(BrowserAction action) { List<IRecord> records = new ArrayList<IRecord>(); // since the library fabric.js (used in the html whiteboard) does not // support parent hierarchies this function will always add the new // element to the root element ElementRecord parent = sxe.getDocumentRecord().getRoot(); ElementRecord newElement = parent.createNewElementRecord(null, action.getElementType()); newElement.setRid(action.getID()); records.add(newElement); records.addAll(setAttributes(newElement, action.getAttributes())); return records; }
Source:
protected void cleanup(IProgressMonitor monitor, Map<String, IProject> projectMapping) { START addProjectsToSession(projectMapping); END for (IProject project : projectMapping.values()) activityQueuer.disableQueuing(project); super.cleanup(monitor, projectMapping); } Why is this called in the cleanup and not at the end of the `transfer(...)` method? It should basically be the same order (only `checkCancellation(...)` would be called afterwards instead of beforehand). The only big difference would be that with the current implementation, the `addprojectToSession(...)` call is located in the `finally` block, meaning it also gets executed when the incoming project negotiation fails. This is probably the wrong behavior as it does not make much sense to add the "shared" resources to the session when the negotiation/resource sharing failed.

Target:
protected void cleanup(IProgressMonitor monitor, Map<String, IProject> projectMapping) { for (IProject project : projectMapping.values()) activityQueuer.disableQueuing(project); super.cleanup(monitor, projectMapping); }
Source:
START @Override public void start() { END session.addActivityConsumer(this, Priority.ACTIVE); } Do you use a formatter ? I haven seen this style when using our Eclipse formatter.

Target:
public void start() { session.addActivityConsumer(this, Priority.ACTIVE); }
Source:
private void executeFolderRemoval(FolderDeletedActivity activity) throws IOException { SPath path = activity.getPath(); IFolder folder = path.getFolder(); START this.editorManager.closeEditorsInFolder(path); END folder.delete(IResource.NONE); } this keyword is unnecessary

Target:
private void executeFolderRemoval(FolderDeletedActivity activity) throws IOException { SPath path = activity.getPath(); IFolder folder = path.getFolder(); folder.delete(IResource.NONE); editorManager.closeEditorsInFolder(path); }
Source:
public void applyTextEdit(TextEditActivity edit) { START content.delete(edit.getOffset(), edit.getReplacedText().length()); END content.insert(edit.getOffset(), edit.getText()); } Check which actions are needed? Only execute `content.delete(....)` if `edit.getReplacedText().length() > 0`, likewise with `content.insert(....)`?

Target:
public void applyTextEdit(TextEditActivity edit) { if (edit.getReplacedText().length() > 0) { content.delete(edit.getOffset(), edit.getReplacedText().length()); } if (edit.getText().length() > 0) { content.insert(edit.getOffset(), edit.getText()); } }
Source:
public final void createNonCoreComponents(ISarosSession session, MutablePicoContainer container) { container.addComponent(ServerEditorManager.class); container.addComponent(FileActivityExecutor.class); container.addComponent(FolderActivityExecutor.class); container.addComponent(TextEditActivityExecutor.class); START container.addComponent(NegotiationHandler.class); END } As you attach this class here I highly suggest to implement Startable or move this handler into application scope.

Target:
public final void createNonCoreComponents(ISarosSession session, MutablePicoContainer container) { container.addComponent(ServerEditorManager.class); container.addComponent(FileActivityExecutor.class); container.addComponent(FolderActivityExecutor.class); container.addComponent(TextEditActivityExecutor.class); }
Source:
public void loadBuildData(@NotNull Properties properties) { loadBuildVersionAndTimeData(properties); loadBuildHostData(properties); START loadBuildNumber(System.getenv(), properties); END } Change ``loadBuildNumber(System.getenv(), properties);`` to ``loadBuildNumber(properties);`` once the BuildServerDataProvider also has a reference to env...

Target:
public void loadBuildData(@NotNull Properties properties) { loadBuildVersionAndTimeData(properties); loadBuildHostData(properties); loadBuildNumber(properties); }
Source:
public void testCompareBasic() throws Exception { // Test on all available basic repos to ensure that the output is identical. for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo == AvailableGitTestRepo.GIT_COMMIT_ID) { continue; START } END mavenSandbox.withParentProject("my-basic-project", "jar").withNoChildProject().withGitRepoInParent(testRepo).create(); MavenProject targetProject = mavenSandbox.getParentProject(); verifyNativeAndJGit(testRepo, targetProject, DEFAULT_FORMAT_STRING); } } please rewrite to not use continue, harder to track code.

Target:
public void testCompareBasic() throws Exception { // Test on all available basic repos to ensure that the output is identical. for (AvailableGitTestRepo testRepo : AvailableGitTestRepo.values()) { if (testRepo != AvailableGitTestRepo.GIT_COMMIT_ID) { mavenSandbox.withParentProject("my-basic-project", "jar").withNoChildProject().withGitRepoInParent(testRepo).create(); MavenProject targetProject = mavenSandbox.getParentProject(); verifyNativeAndJGit(testRepo, targetProject, DEFAULT_FORMAT_STRING); } } }
Source:
public void setConfigurable(boolean configurable) { if (configurable) { this.configurable = configurable; START } END } Why this if statement? This prevents the configurable element to be set to false!

Target:
public void setConfigurable(boolean configurable) { this.configurable = configurable; }
Source:
@Override public E element() { lock.lock(); try { if (queue.isEmpty()) { throw new NoSuchElementException(); } return queue.peek(); } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); START return null; END } finally { lock.unlock(); } } throws

Target:
@Override public E element() { lock.lock(); try { if (queue.isEmpty()) { throw new NoSuchElementException(); } return queue.peek(); } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
@Override public Iterator<E> iterator() { lock.lock(); try { START return queue.iterator(); END } finally { lock.unlock(); } } is locking while creating this factory necessary? the iterator still iterates on the backing ObjectQueue (not a clone of it or anything).

Target:
@Override public Iterator<E> iterator() { return queue.iterator(); }
Source:
@Override public boolean addAll(Collection<? extends E> c) { if (c.isEmpty()) { return false; } lock.lock(); try { for (E e : c) { queue.add(e); } nonEmpty.signal(); return true; } catch (IOException e) { QueueFile.<Error>getSneakyThrowable(e); START return false; END } finally { lock.unlock(); } } throws

Target:
@Override public boolean addAll(Collection<? extends E> c) { if (c.isEmpty()) { return false; } lock.lock(); try { for (E e : c) { queue.add(e); } nonEmpty.signal(); return true; } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
@Override public void clear() { lock.lock(); try { queue.clear(); } catch (IOException e) { START QueueFile.<Error>getSneakyThrowable(e); END } finally { lock.unlock(); } } nit: throws for consistency and clarity.

Target:
@Override public void clear() { lock.lock(); try { queue.clear(); } catch (IOException e) { throw QueueFile.<Error>getSneakyThrowable(e); } finally { lock.unlock(); } }
Source:
@Test public void testMissingFileInitializes() throws Exception { testFile = File.createTempFile(FRESH_SERIALIZED_QUEUE, "test"); assertTrue(testFile.delete()); assertFalse(testFile.exists()); QueueFile queue = new QueueFile.Builder(testFile).build(); try { assertEquals(0, queue.size()); assertTrue(testFile.exists()); } finally { START queue.close(); END } } i guess the close could in `cleanup()`? dunno which is preferable.

Target:
@Test public void testMissingFileInitializes() throws Exception { testFile = File.createTempFile(FRESH_SERIALIZED_QUEUE, "test"); assertTrue(testFile.delete()); assertFalse(testFile.exists()); QueueFile queue = new QueueFile.Builder(testFile).build(); assertEquals(0, queue.size()); assertTrue(testFile.exists()); queue.close(); }
Source:
static File copyTestFile(String file) throws IOException { File newFile = File.createTempFile(file, "test"); InputStream in = QueueTestUtils.class.getResourceAsStream(file); BufferedSink sink = Okio.buffer(Okio.sink(newFile)); sink.writeAll(Okio.source(in)); START sink.flush(); END sink.close(); assertTrue(newFile.exists()); return newFile; } Close will flush. Or even better, try-with-resources!

Target:
static File copyTestFile(String file) throws IOException { File newFile = File.createTempFile(file, "test"); InputStream in = QueueTestUtils.class.getResourceAsStream(file); try (BufferedSink sink = Okio.buffer(Okio.sink(newFile))) { sink.writeAll(Okio.source(in)); } assertTrue(newFile.exists()); return newFile; }
Source:
@Override public T next() { if (closed) throw new IllegalStateException("closed"); checkForComodification(); if (size() == 0) throw new NoSuchElementException(); START if (nextElementIndex >= size()) throw new NoSuchElementException(); END return entries.get(nextElementIndex++); } Does this make the check on the previous line unnecessary?

Target:
@Override public T next() { if (closed) throw new IllegalStateException("closed"); checkForComodification(); if (nextElementIndex >= size()) throw new NoSuchElementException(); return entries.get(nextElementIndex++); }
Source:
@Test public void testIteratorRemoveDisallowsConcurrentModification() throws IOException { QueueFile queueFile = new QueueFile(file); for (int i = 0; i < 15; i++) { queueFile.add(values[i]); } Iterator<byte[]> iterator = queueFile.iterator(); iterator.next(); queueFile.remove(); try { iterator.remove(); START fail("remove should not permit concurrent modifications."); END } catch (ConcurrentModificationException ignored) { } } can you switch the import to `org.junit.Assert.fail` and remove these two messages? If this fails the reason is already clear and I don't like being forced to provide a redundant message.

Target:
@Test public void testIteratorRemoveDisallowsConcurrentModification() throws IOException { QueueFile queueFile = new QueueFile(file); for (int i = 0; i < 15; i++) { queueFile.add(values[i]); } Iterator<byte[]> iterator = queueFile.iterator(); iterator.next(); queueFile.remove(); try { iterator.remove(); fail(); } catch (ConcurrentModificationException ignored) { } }
Source:
public final void remove(int n) throws IOException { try { queueFile.remove(n); if (listener != null) { START for (int i = 0; i < n; i++) END listener.onRemove(this); } } catch (IOException e) { throw new FileException("Failed to remove.", e, file); } } braces for body

Target:
public final void remove(int n) throws IOException { try { queueFile.remove(n); if (listener != null) { for (int i = 0; i < n; i++) { listener.onRemove(this); } } } catch (IOException e) { throw new FileException("Failed to remove.", e, file); } }
Source:
START private StackExchangeApi() { END } make it protected. It was my fault to make all API constructors private. I fixed that. In master branch all API constructors are protected, so anyone can extend API in their code if they want. But couldn't instantiate directly, forcing them to use singleton

Target:
protected StackExchangeApi() { }
Source:
START public boolean isOob(final OAuthConfig config) { END return "oob".equals(config.getCallback()); } May be make it static and invoke like ImgurApi.isOob() instead of ((ImgurApi) getApi()).isOob()?

Target:
public static boolean isOob(final OAuthConfig config) { return "oob".equals(config.getCallback()); }
Source:
public List<File> getContextScreenshots() { List<File> screenshots = currentContextScreenshots.get(); return Collections.unmodifiableList(screenshots == null ? Collections.emptyList() : screenshots); START } END I would change the order: there is no need to call `unmodifiableList` for `emptyList`: ``` return screenshots == null ? Collections.emptyList() : Collections.unmodifiableList(screenshots); ```

Target:
public List<File> getContextScreenshots() { List<File> screenshots = currentContextScreenshots.get(); return screenshots == null ? Collections.emptyList() : Collections.unmodifiableList(screenshots); }
Source:
private boolean isBoolean(String value) { START return "true".equals(value) || "false".equals(value); END } Suppose makes sense to convert value to lower case before comparing.

Target:
private boolean isBoolean(String value) { return "true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value); }
Source:
CloseDriverCommand(WebDriver webDriver, SelenideProxyServer selenideProxyServer) { this.webDriver = webDriver; this.selenideProxyServer = selenideProxyServer; START this.closeBrowserTimeoutMs = 5000; END } I suggest to remove this field at all. There is no need to limit lifetime of `CloseDriverCommand`. Let it work as long as it takes.

Target:
CloseDriverCommand(WebDriver webDriver, SelenideProxyServer selenideProxyServer) { this.webDriver = webDriver; this.selenideProxyServer = selenideProxyServer; }
Source:
public void setLevel(Level newLevel) throws SecurityException { // We have to propagate our level to an internal data structure in the superclass super.setLevel(newLevel); START LogContext.checkAccess(); END loggerNode.setLevel(newLevel); } This should be moved below the `LogContext.checkAccess()`.

Target:
public void setLevel(Level newLevel) throws SecurityException { LogContext.checkAccess(); // We have to propagate our level to an internal data structure in the superclass super.setLevel(newLevel); loggerNode.setLevel(newLevel); }
Source:
private RedirectHandler getOrInstall(Logger logger) { synchronized (this) { for (Handler handler : logger.getHandlers()) { if (handler instanceof RedirectHandler) { return (RedirectHandler) handler; } } RedirectHandler redirectHandler = new RedirectHandler(logContext.getLogger(logger.getName())); logger.addHandler(redirectHandler); logger.setUseParentHandlers(false); START return redirectHandler; END } } This doesn't seem quite right. If the `logger.setUseParentHandlers(true)` is set elsewhere this could override it.

Target:
private RedirectHandler getOrInstall(Logger logger) { synchronized (this) { for (Handler handler : logger.getHandlers()) { if (handler instanceof RedirectHandler) { logger.setUseParentHandlers(false); return (RedirectHandler) handler; } } RedirectHandler redirectHandler = new RedirectHandler(logContext.getLogger(logger.getName())); logger.addHandler(redirectHandler); logger.setUseParentHandlers(false); return redirectHandler; } }
Source:
protected void doPublish(final ExtLogRecord record) { record.copyAll(); synchronized (buffer) { if (isLoggable(record)) { if (buffer.size() == limit) { buffer.removeFirst(); } buffer.addLast(record); } for (Handler handler : getHandlers()) { START if (handler.isLoggable(record)) { END handler.publish(record); } } } } Does this not duplicate an existing check?

Target:
protected void doPublish(final ExtLogRecord record) { record.copyAll(); synchronized (buffer) { if (isLoggable(record)) { if (buffer.size() == limit) { buffer.removeFirst(); } buffer.addLast(record); } for (Handler handler : getHandlers()) { handler.publish(record); } } }
Source:
public static void dropFunctions(final PrintWriter writer, final PgDiffArguments arguments, final PgSchema oldSchema, final PgSchema newSchema, final SearchPathHelper searchPathHelper) { if (oldSchema == null) { return; } // Drop functions that exist no more for (final PgFunction oldFunction : oldSchema.getFunctions()) { if (!newSchema.containsFunction(oldFunction.getSignature())) { searchPathHelper.outputSearchPath(writer); writer.println(); START writer.println(oldFunction.getDropSQL(arguments)); END } } } the majority of your changes are simply passing arguments all around the codebase

Target:
public static void dropFunctions(final PrintWriter writer, final PgDiffArguments arguments, final PgSchema oldSchema, final PgSchema newSchema, final SearchPathHelper searchPathHelper) { if (oldSchema == null) { return; } // Drop functions that exist no more for (final PgFunction oldFunction : oldSchema.getFunctions()) { if (!newSchema.containsFunction(oldFunction.getSignature())) { searchPathHelper.outputSearchPath(writer); writer.println(); writer.println(oldFunction.getDropSQL()); } } }
Source:
private static String currenciesToJSON(final ArrayList<String> currencies) { HashMap map = new HashMap<>(); START for (String e : currencies) END map.put("currencies", e); System.out.println("map : " + map); return new Gson().toJson(map); } Please use braces

Target:
private static String currenciesToJSON(final ArrayList<String> currencies) { HashMap map = new HashMap<>(); for (String e : currencies) { map.put("currencies", e); } System.out.println("map : " + map); return new Gson().toJson(map); }
Source:
public List<Integer> getProjects() { START assert projects == null || !projects.isEmpty(); END if (projects == null) { int fieldCount = target.getFieldCount(); List<Integer> res = new ArrayList<>(fieldCount); for (int i = 0; i < fieldCount; i++) { res.add(i); } return res; } return projects; } Shouldn't we allow empty projects as distinct from null. I guess `null` means "all the table fields", empty projects would mean no columns are actually selected. For the query `SELECT current_date() FORM map`

Target:
public List<Integer> getProjects() { if (projects == null) { int fieldCount = target.getFieldCount(); List<Integer> res = new ArrayList<>(fieldCount); for (int i = 0; i < fieldCount; i++) { res.add(i); } return res; } return projects; }
Source:
START public PhoneHome(Node node, String baseurl) { END hazelcastNode = node; logger = hazelcastNode.getLogger(com.hazelcast.internal.util.phonehome.PhoneHome.class); basePhoneHomeUrl = baseurl; } Please make this constructor package-private. We use it only from the tests, so there is no need to expose it publicly.

Target:
PhoneHome(Node node, String baseurl) { hazelcastNode = node; logger = hazelcastNode.getLogger(com.hazelcast.internal.util.phonehome.PhoneHome.class); basePhoneHomeUrl = baseurl; }
Source:
public int hashCode() { START return operand != null ? operand.hashCode() : 0; END } Does the operand really can be null?

Target:
public int hashCode() { return operand.hashCode(); }
Source:
public void testPhoneHomeParameterCreator() { PhoneHomeParameterCreator phoneHomeParameterCreator = new PhoneHomeParameterCreator(); phoneHomeParameterCreator.addParam("1", "hazelcast"); phoneHomeParameterCreator.addParam("2", "phonehome"); Map<String, String> map = phoneHomeParameterCreator.getParameters(); assertEquals("?1=hazelcast&2=phonehome", phoneHomeParameterCreator.build()); START assertNotNull(map); END assertEquals(ImmutableMap.of("1", "hazelcast", "2", "phonehome"), map); assertNull(map.get("3")); } Since we have the `assertEquals(ImmutableMap.of("1", "hazelcast", "2", "phonehome"), map);` check now, you can remove the `assertNotNull(map);` and the `assertNull(map.get("3"));` assertions, since these are unnecessary. The `assertEquals()` call covers these conditions.

Target:
public void testPhoneHomeParameterCreator() { PhoneHomeParameterCreator phoneHomeParameterCreator = new PhoneHomeParameterCreator(); phoneHomeParameterCreator.addParam("1", "hazelcast"); phoneHomeParameterCreator.addParam("2", "phonehome"); Map<String, String> map = phoneHomeParameterCreator.getParameters(); assertEquals("?1=hazelcast&2=phonehome", phoneHomeParameterCreator.build()); assertEquals(ImmutableMap.of("1", "hazelcast", "2", "phonehome"), map); }
Source:
public PhoneHomeParameterCreator createParameters() { PhoneHomeParameterCreator parameterCreator = new PhoneHomeParameterCreator(); MetricsCollector[] metricsCollectorArray = new MetricsCollector[]{new BuildInfoCollector(), new ClusterInfoCollector(), new ClientInfoCollector(), new MapInfoCollector(), new OSInfoCollector()}; START List<MetricsCollector> metricsCollectorList = Arrays.asList(metricsCollectorArray); END metricsCollectorList.forEach((metricsCollector -> parameterCreator. addMap(metricsCollector.computeMetrics(hazelcastNode)))); return parameterCreator; } `Arrays.asList()` accepts variable-length argument list, so you can write `List<MetricsCollector> metricsCollectorList = Arrays.asList(new BuildInfoCollector(), new ClusterInfoCollector(), ...);` and drop the `metricsCollectorArray` variable. Also please let's make it a field instead of a local variable.

Target:
public PhoneHomeParameterCreator createParameters() { PhoneHomeParameterCreator parameterCreator = new PhoneHomeParameterCreator(); metricsCollectorList.forEach((metricsCollector -> parameterCreator. addMap(metricsCollector.computeMetrics(hazelcastNode)))); return parameterCreator; }
Source:
public void start() { if (!enabled) { logger.info(format("Diagnostics disabled. To enable add -D%s=true to the JVM arguments.", ENABLED.getName())); return; } START if (stdout) { END this.diagnosticsLog = new DiagnosticsStdout(this); } else { this.diagnosticsLog = new DiagnosticsLogFile(this); } this.scheduler = new ScheduledThreadPoolExecutor(1, new DiagnosticSchedulerThreadFactory()); logger.info("Diagnostics started"); } Can you convert this into using a ternary operator? ``` this.diagnosticsLogs = stdOut ? new DiagnosticsStdout(this) : new DiagnosticsLogFile(this); ``` It makes the code less verbose.

Target:
public void start() { if (!enabled) { logger.info(format("Diagnostics disabled. To enable add -D%s=true to the JVM arguments.", ENABLED.getName())); return; } this.diagnosticsLog = stdout ? new DiagnosticsStdout(this) : new DiagnosticsLogFile(this); this.scheduler = new ScheduledThreadPoolExecutor(1, new DiagnosticSchedulerThreadFactory()); logger.info("Diagnostics started"); }
Source:
public boolean schedule() { // If the fragment is already scheduled, we do not need to do anything else, because executor will re-check queue state // before exiting. START if (scheduled.get()) { END return false; } // Otherwise we schedule the fragment into the worker pool. boolean res = scheduled.compareAndSet(false, true); if (res) { fragmentPool.submit(this); } return res; } It seems this check is not necessary because it is covered by the `scheduled.compareAndSet` logic.

Target:
public boolean schedule() { boolean res = !scheduled.get() && scheduled.compareAndSet(false, true); if (res) { submit(); } return res; }
Source:
protected Collection<Address> getPossibleAddressesForInitialJoin() { long deadLine = System.nanoTime() + SECONDS.toNanos(maximumWaitingTimeBeforeJoinSeconds); START for (int i = 0; System.nanoTime() - deadLine < 0; i++) { END Collection<Address> possibleAddresses = getPossibleAddresses(); if (!possibleAddresses.isEmpty()) { return possibleAddresses; } idleStrategy.idle(i); } return Collections.emptyList(); } I'm not sure about this one. Please pull this out of this PR because it isn't related to timing and lets run some ad hoc examples to make sure we don't run into some nasty overflow/sign related problems.

Target:
protected Collection<Address> getPossibleAddressesForInitialJoin() { long deadLine = System.nanoTime() + SECONDS.toNanos(maximumWaitingTimeBeforeJoinSeconds); for (int i = 0; System.nanoTime() < deadLine; i++) { Collection<Address> possibleAddresses = getPossibleAddresses(); if (!possibleAddresses.isEmpty()) { return possibleAddresses; } idleStrategy.idle(i); } return Collections.emptyList(); }
Source:
public Object getArgument(int index) { START assert index >= 0 && index <= arguments.size(); END return arguments.get(index); } `index < arguments.size()` ?

Target:
public Object getArgument(int index) { assert index >= 0 && index < arguments.size(); return arguments.get(index); }
Source:
START public Entry(int coreId, AffinityLock lock) { END this.coreId = coreId; this.lock = lock; } Private constructor

Target:
private Entry(int coreId, AffinityLock lock) { this.coreId = coreId; this.lock = lock; }
Source:
public IndexConfig setBitmapIndexOptions(BitmapIndexOptions bitmapIndexOptions) { START this.bitmapIndexOptions.setUniqueKey(bitmapIndexOptions.getUniqueKey()); END this.bitmapIndexOptions.setUniqueKeyTransformation(bitmapIndexOptions.getUniqueKeyTransformation()); return this; } These two lines look dangerous to me because we mutate an object which was set earlier. Consider the following code: ``` IndexConfig config = new IndexConfig(); BitmapIndexOptions options = config1.getBitmapIndexOptions(); // ... config.setBitmapIndexOptions(<new options>); // "options" object changed unexpectedly ``` I would rather overwrite an object in the setter and perform a lazy initialization in getter as we do in other config classes (e.g. `IndexConfig.getAttributes()` copies this approach).

Target:
public IndexConfig setBitmapIndexOptions(BitmapIndexOptions bitmapIndexOptions) { this.bitmapIndexOptions = bitmapIndexOptions == null ? null : new BitmapIndexOptions(bitmapIndexOptions); return this; }
Source:
private void validateSetOptimizeQueriesOption(boolean optimizeQueries) { if (!setCacheDeserializedValuesExplicitlyInvoked) { return; } if ((cacheDeserializedValues == CacheDeserializedValues.INDEX_ONLY || START cacheDeserializedValues == CacheDeserializedValues.NEVER) && optimizeQueries) { END throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to true, " + "but 'cacheDeserializedValues' was set to NEVER or INDEX_ONLY. " + "These are conflicting options. Please remove the `optimize-queries'"); } else if (cacheDeserializedValues == CacheDeserializedValues.ALWAYS && !optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to false, " + "but 'cacheDeserializedValues' was set to ALWAYS. " + "These are conflicting options. Please remove the `optimize-queries'"); } } really minor: for symmetry with `validateCacheDeserializedValuesOption`, maybe use: `if (cacheDeserializedValues != CacheDeserializedValues.ALWAYS)`?

Target:
private void validateSetOptimizeQueriesOption(boolean optimizeQueries) { if (!setCacheDeserializedValuesExplicitlyInvoked) { return; } if (cacheDeserializedValues != CacheDeserializedValues.ALWAYS && optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to true, " + "but 'cacheDeserializedValues' was set to NEVER or INDEX_ONLY. " + "These are conflicting options. Please remove the `optimize-queries'"); } else if (cacheDeserializedValues == CacheDeserializedValues.ALWAYS && !optimizeQueries) { throw new ConfigurationException("Deprecated option 'optimize-queries' is being set to false, " + "but 'cacheDeserializedValues' was set to ALWAYS. " + "These are conflicting options. Please remove the `optimize-queries'"); } }
Source:
public DistributedObjectEvent(EventType eventType, String serviceName, String objectName, DistributedObject distributedObject, UUID source) { super(source); this.eventType = eventType; this.serviceName = serviceName; this.objectName = objectName; this.distributedObject = distributedObject; START this.source = source; END } This line is unnecessary.

Target:
public DistributedObjectEvent(EventType eventType, String serviceName, String objectName, DistributedObject distributedObject, UUID source) { super(source); this.eventType = eventType; this.serviceName = serviceName; this.objectName = objectName; this.distributedObject = distributedObject; }
Source:
public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); type = IndexType.getById(in.readInt()); attributes = readNullableList(in); if (type == IndexType.BITMAP) { START bitmapIndexOptions = in.readObject(); END } } If we do not write options unconditionally, we will not validate them on the server-side. Consider a user who submits `IndexConfig{type=HASH, bitmapOptions=<not null object>}`. This is an invalid config, but how do we know what was his real intention - to create a hash index or a bitmap index? I would rather read/write the object as is, and throw an exception on invalid config, rather than ignoring invalid state silently.

Target:
public void readData(ObjectDataInput in) throws IOException { name = in.readUTF(); type = IndexType.getById(in.readInt()); attributes = readNullableList(in); bitmapIndexOptions = in.readObject(); }
Source:
public void assertNoMBeans() { Set<ObjectInstance> instances = queryOurInstances(); START assertEquals(Arrays.toString(instances.toArray()), 0, instances.size()); END } minor: `assertThat(instances, is(empty()))`?

Target:
public void assertNoMBeans() { Set<ObjectInstance> instances = queryOurInstances(); assertEquals(0, instances.size()); }
Source:
void onServerClose(final String reason) { executor.executeIncoming(new Runnable() { @Override public String toString() { return "Server Closed EOF. " + MockedClientConnection.this; } @Override public void run() { MockedClientConnection.this.close(reason, new TargetDisconnectedException("Mocked Remote socket closed")); } }); executor.shutdownOutgoing(); START System.out.println("<<<< <<<<"); END } Leftover?

Target:
void onServerClose(final String reason) { executor.executeIncoming(new Runnable() { @Override public String toString() { return "Server Closed EOF. " + MockedClientConnection.this; } @Override public void run() { MockedClientConnection.this.close(reason, new TargetDisconnectedException("Mocked Remote socket closed")); } }); executor.shutdownOutgoing(); }
Source:
public void clear() { takeWriteLock(); try { bitmap.clear(); if (internalKeys != null) { internalKeys.clear(); internalKeyCounter = 0; } if (internalObjectKeys != null) { internalObjectKeys.clear(); START internalKeyCounter = 0; END } } finally { releaseWriteLock(); } } In case of "no remapping, raw attribute values are used as long keys" it seems both `internalKeys` and `internalObjectKeys` are `null` and then we don't reset `internalKeyCounter` to 0?

Target:
public void clear() { takeWriteLock(); try { bitmap.clear(); if (internalKeys != null) { internalKeys.clear(); } if (internalObjectKeys != null) { internalObjectKeys.clear(); } internalKeyCounter = 0; } finally { releaseWriteLock(); } }