auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void populateReviews(List<TaskReview> reviewContainers) throws NumberFormatException { for (ITask review : reviews) { reviewContainers.add(new TaskReview(review)); } }

Target:
This doesn't throw NumberFormatException anymore.
Source:
public BPUserLibraryElement getNewLibrary() { BPListElement[] entries = null; Map<String, String> attributes = null; if (fElementToEdit != null) { entries = fElementToEdit.getChildren(); IBuildpathContainer buildpathContainer = fElementToEdit .getUpdatedContainer(); if (buildpathContainer instanceof IBuildpathContainerExtension3) { IBuildpathContainerExtension3 buildpathContainer3 = (IBuildpathContainerExtension3) buildpathContainer; attributes = buildpathContainer3.getAttributes(); } } return new BPUserLibraryElement(fNameField.getText(), fIsSystemField.isSelected(), entries, attributes); }

Target:
I would suggest access attributes in a more direct way, involving IBuildpathContainerExtension3 here seems unnecessary.
Source:
public String getDescription(AbstractOperation op) { if (op instanceof CompositeOperation) { final CompositeOperation compositeOperation = (CompositeOperation) op; // artificial composite because of opposite ref, take description of // main operation if (compositeOperation.getMainOperation() != null) { return getDescription(compositeOperation.getMainOperation()); } } // check of a custom operation label provider can provide a label final OperationCustomLabelProvider customLabelProvider = getLabelProvider(); final String decorate = decorate(customLabelProvider, op); customLabelProvider.dispose(); return decorate; }

Target:
Shouldn't we wrap the dispose call() in an finally block (e.g. in case of NPE)?
Source:
private void configureExistingWindows() { List<MArea> elements = modelService.findElements(window, null, MArea.class, null); for (MArea area : elements) { Object widget = area.getWidget(); if (widget instanceof Control) { installAreaDropSupport((Control) widget); } } }

Target:
First time I saw this code, without to check what the method is doing, I've understood it like : "for each area install D&D support". However, the installAreaDropSupport() has a guard to be installed only once *per page*. Please add break; after that method OR change the "for" loop to something like snippet below if(!elements.isEmpty()) { Object widget = elements.iterator.next(); ... }
Source:
private static DropStrategy findStrategy(Map<DropStrategy, Command> matchingStrategies, Command command) { for (Map.Entry<DropStrategy, Command> entry : matchingStrategies.entrySet()) { if (entry.getValue() == command ) { return entry.getKey(); } } return null; }

Target:
why not protected?
Source:
public void setTreeProviders(ITreeContentProvider contentProvider, ILabelProvider labelProvider) { List items; if (root == null) { items = Collections.emptyList(); } else { // remember checked elements items = getAllWhiteCheckedItems(); // reset all caches for (Object object : items) { setTreeChecked(object, false); } } treeViewer.setContentProvider(contentProvider); treeViewer.setLabelProvider(labelProvider); treeContentProvider = contentProvider; treeLabelProvider = labelProvider; // select (if any) previously checked elements again in the new model for (Object object : items) { setTreeChecked(object, true); } }

Target:
Doesn't this line produce a "raw type" warning?
Source:
public URL getURL() { try { return new URL(url.toString()); } catch (MalformedURLException e) { // shouldn't happen since we checked this in the constructor already return null; } }

Target:
why not just return url?
Source:
private void doPaint(GC gc) { if (fCanvas.isVisible()) { return; } ILineRange visibleModelLines= computeVisibleModelLines(); if (visibleModelLines == null) return; fSensitiveToTextChanges= isViewerCompletelyShown(); fScrollPos= fCachedTextWidget.getTopPixel(); fRevisionPainter.paint(gc, visibleModelLines); if (!fRevisionPainter.hasInformation()) // don't paint quick diff colors if revisions are painted fDiffPainter.paint(gc, visibleModelLines); }

Target:
Did you mean NOT visible?
Source:
public JSchFileManager(IRemoteConnection connection) { if (connection instanceof JSchConnection) try { ((JSchConnection) connection).getSftpChannel(); } catch (RemoteConnectionException e) { throw new UnsupportedOperationException(Messages.JSchConnection_Remote_host_does_not_support_sftp); } fConnection = connection; }

Target:
I don't like constructors throwing exceptions. I think this check should be made in getService() and the constructor access changed to private.
Source:
protected Object doGetValue() { CapsulePartKindEnum kind = null; setUMLPropertiesValue(); // Define what is the kind of the capsulePart based on the multiplicity and the aggregation value if (capsulePartElement.getLower() == capsulePartElement.getUpper()) { kind = CapsulePartKindEnum.FIXED; } else if (capsulePartElement.getLower() == 0) { if (AggregationKind.COMPOSITE_LITERAL.equals(aggregation)) { kind = CapsulePartKindEnum.OPTIONAL; } else if (AggregationKind.SHARED_LITERAL.equals(aggregation)) { kind = CapsulePartKindEnum.PLUGIN; } } return kind; }

Target:
invert == 0
Source:
protected static IWorkbenchWindow getActiveWindow(MApplication app) { return PlatformUI.getWorkbench().getActiveWorkbenchWindow(); }

Target:
why it is protected, not package protected or private?
Source:
public void setBoldStylerProvider(BoldStylerProvider boldStylerProvider) { fBoldStylerProvider= boldStylerProvider; }

Target:
Remove this, so that it becomes package visible only.
Source:
public static String getPath() { CtfCoreTestPlugin plugin = CtfCoreTestPlugin.getDefault(); if (plugin == null) { return null; } Path tracePath = Paths.get("..", "..", "ctf", "org.eclipse.tracecompass.ctf.core.tests", TRACES_DIRECTORY, TRACE_NAME); tracePath = tracePath.toAbsolutePath(); File file = tracePath.toFile(); if (file.exists()) { deleteTrace(tracePath); } generateLttngKernelTrace(file); return file.getAbsolutePath(); }

Target:
we shouldn't do this check
Source:
private void updateTaskWithIncomingReviewState(ITask task, boolean hasIncomingReviews) { task.setAttribute(ReviewsCoreConstants.INCOMING_REVIEW_STATE, hasIncomingReviews ? "true" : "false"); //$NON-NLS-1$//$NON-NLS-2$ }

Target:
Use Boolean.toString.
Source:
public void childRendered(MElementContainer<MUIElement> parentElement, MUIElement element) { super.childRendered(parentElement, element); processContents(parentElement); ToolBar toolbar = (ToolBar) getUIContainer(element); if (toolbar != null && !toolbar.isDisposed()) { toolbar.pack(true); toolbar.requestLayout(); } }

Target:
Remove call to pack
Source:
public Set<GAV> getProjectGAVs() { return Collections.unmodifiableSet(new LinkedHashSet<>(gavs)); }

Target:
synchronized
Source:
public void testCreateSymlink() throws IOException { FS fs = FS.DETECTED; // show test as ignored if the FS doesn't support symlinks Assume.assumeTrue(fs.supportsSymlinks()); fs.createSymLink(new File(trash, "x"), "y"); assertTrue(fs.supportsSymlinks()); String target = fs.readSymLink(new File(trash, "x")); assertEquals("y", target); }

Target:
This assertion is not needed anymore
Source:
public void testCreateSymlinkOverrideExisting() throws IOException { FS fs = FS.DETECTED; // show test as ignored if the FS doesn't support symlinks Assume.assumeTrue(fs.supportsSymlinks()); File file = new File(trash, "x"); fs.createSymLink(file, "y"); assertTrue(fs.supportsSymlinks()); String target = fs.readSymLink(file); assertEquals("y", target); fs.createSymLink(file, "z"); target = fs.readSymLink(file); assertEquals("z", target); }

Target:
This assertion is not needed anymore
Source:
public ITmfStateValue getValue(ITmfEvent event) { if (fStateValue != null) { return fStateValue; } if (fType.equals(TmfXmlStrings.TYPE_NULL)) { return TmfStateValue.nullValue(); } try { return checkNotNull(fXmlStateValue).getValue(event); } catch (AttributeNotFoundException e) { Activator.logError("Failed to get the state value", e); //$NON-NLS-1$ } throw new IllegalStateException("Failed to get the value for the segment field " + fName); //$NON-NLS-1$ }

Target:
I think you've set fStateValue to nullValue in the constructor in this case, so this is pretty much dead code
Source:
public void setRefiningChanges(Diff extension, DifferenceKind extensionKind, Diff refiningDiff) { if (extensionKind == DifferenceKind.CHANGE) { extension.getRefinedBy().addAll( Collections2.filter(getAllDifferencesForChange(refiningDiff), EMFComparePredicates .fromSide(extension.getSource()))); } }

Target:
There is a static import for EMFComparePredicates.fromSide in this class already that you can use.
Source:
void execute(RevWalk rw, List<Command> todo) throws IOException { if (apply(todo) && nextId != null) { commit(rw); } }

Target:
Why a 2nd statusless execute function? It doesn't have any of the safety in the overridden execute() above.
Source:
void removeNestedCopyfiles() { for (RepoProject proj : filteredProjects) { List<CopyFile> copyfiles = new ArrayList<CopyFile>(); copyfiles.addAll(proj.getCopyFiles()); proj.clearCopyFiles(); Iterator<CopyFile> iter = copyfiles.iterator(); while (iter.hasNext()) { if (isNestedCopyfile(iter.next())) iter.remove(); } proj.addCopyFiles(copyfiles); } }

Target:
optional: can use new ArrayList<>()
Source:
public void addKeyListener(KeyListener listener) { if (this.text != null && !this.text.isDisposed()) this.text.addKeyListener(listener); if (this.dropdownTableViewer != null && !this.dropdownTable.isDisposed()) this.dropdownTable.addKeyListener(listener); }

Target:
why a check for the viewer here? shouldn't this be the dropdownTable? Now that we keep the table.
Source:
public void addMouseListener(MouseListener listener) { // only add the mouse listener to the dropdown, as clicking in the text // control should not trigger anything else than it is handled by the // text control itself. if (this.dropdownTableViewer != null && !this.dropdownTable.isDisposed()) this.dropdownTable.addMouseListener(listener); }

Target:
why a check for the viewer here? shouldn't this be the dropdownTable? Now that we keep the table.
Source:
protected String[] getTransformedSelection() { System.out.println(this.selectionStateMap); List<String> selectedItems = new ArrayList<String>(); for (String item : this.selectionStateMap.keySet()) { Boolean isSelected = this.selectionStateMap.get(item); if (isSelected != null && isSelected) { selectedItems.add(item); } } return selectedItems.toArray(new String[selectedItems.size()]); }

Target:
Please remove any System.out calls from the code
Source:
public void doLaunch(String programName) throws Exception { setLaunchAttribute(ICDTLaunchConfigurationConstants.ATTR_PROGRAM_NAME, programName); super.doLaunch(); }

Target:
protected?
Source:
public void setLinkForeground (Color color) { checkWidget(); if (color != null && color.isDisposed ()) error(SWT.ERROR_INVALID_ARGUMENT); linkColor = color; if (getEnabled()) { styleLinkParts(); redraw(); } }

Target:
Please add a check here that would simply return if the color being set is the same as the current foreground color (linkColor).
Source:
public static boolean dialogCancellable(IEditCommandRequest request) { Object value = request.getParameter(RequestParameterConstants.DIALOG_CANCELLABLE); if (value instanceof Boolean) { return (Boolean) value; } else if (value instanceof String) { Boolean booleanObject = Boolean.valueOf((String) value); return booleanObject.booleanValue(); } return true; // Default }

Target:
Default value is false to keep existing behavior for Mars dialogs
Source:
public Annotation getFirstAnnotationForOffset(int offset) { for (CommentAnnotation annotation : Iterables.filter(annotations, CommentAnnotation.class)) { if (annotation instanceof CommentAnnotation) { if (annotation.getPosition().offset <= offset && (annotation.getPosition().length + annotation.getPosition().offset) >= offset) { return annotation; } } } return null; }

Target:
Not needed.
Source:
protected PullWithOptionsAction() { super(ActionCommands.PULL_WITH_OPTIONS, new PullWithOptionsActionHandler()); }

Target:
I get !ENTRY org.eclipse.ui 4 4 2016-01-11 20:56:17.129 !MESSAGE Could not create action delegate for id: org.eclipse.egit.ui.actionpullwithoptions !SUBENTRY 1 org.eclipse.equinox.registry 4 1 2016-01-11 20:56:17.129 !MESSAGE Plug-in "org.eclipse.egit.ui" was unable to instantiate class "org.eclipse.egit.ui.internal.actions.PullWithOptionsAction". !STACK 0 java.lang.IllegalAccessException: Class org.eclipse.core.internal.registry.osgi.RegistryStrategyOSGI can not access a member of class org.eclipse.egit.ui.internal.actions.PullWithOptionsAction with modifiers "protected" Must be public.
Source:
private boolean isModifyAccessEnabled() { boolean returnValue; try { if (SystemGroup.OseeAccessAdmin.isCurrentUserMember()) { returnValue = true; } else if (policyTableViewer.getAccessControlList().size() > 0) { returnValue = AccessControlManager.hasPermission(accessControlledObject, PermissionEnum.OWNER); } else { returnValue = true; } } catch (OseeCoreException ex) { OseeLog.log(Activator.class, Level.SEVERE, ex); returnValue = false; } return returnValue; }

Target:
Adding to Megumi's nit: Consider initializing the value to true, and possibly collapsing these two methods down to one with an argument
Source:
public void setUp() throws Exception { // Automated Test logFileName = Platform.getInstallLocation().getURL().getPath() + ".." + File.separator + ".." + File.separator + "results" + File.separator + "chkpii"; // A tad bogus but this is where // the build wants to copy the // results from! // Runtime Workbench - TODO Put me back to Automated status // logFileName = "d:\\results"; // sourceDirectoryName = "d:\\sourceFetch"; }

Target:
Remove throws Exception
Source:
private static Map<String, RemoteRefUpdate> asUpdateMap( List<RemoteCommand> cmds) { Map<String, RemoteRefUpdate> m = new LinkedHashMap<>(); for (RemoteCommand c : cmds) { m.put(c.getRemoteName(), c); } return m; }

Target:
s/c/cmd/
Source:
public Collection<ReceiveCommand> getCommands() { synchronized (lock) { return commands; } }

Target:
What is this lock doing? The list is being returned unprotected. Maybe just return an unmodifiable list that is created when setting it?
Source:
public List<IDockerContainerListener> getContainerListeners() { final IDockerContainerListener[] listeners = new IDockerContainerListener[this.containerListeners .size()]; for (int i = 0; i < containerListeners.getListeners().length; i++) { listeners[i] = (IDockerContainerListener) containerListeners .getListeners()[i]; } return Arrays.asList(listeners); }

Target:
better put containerListeners.getListeners() in a local variable
Source:
private static synchronized Iterable<ISegmentGenerationListener> getListeners(ListenerList listenersList) { List<ISegmentGenerationListener> listeners = new ArrayList<>(); for (Object listener : listenersList.getListeners()) { if (listener != null) { listeners.add((ISegmentGenerationListener) listener); } } return listeners; }

Target:
instead of != null here, you could do a instanceof ISegmentGenerationListener. There shouldn't be any ClassCastException, but this way, you would avoid any such error
Source:
public AbstractSegmentBaseStateSystemAnalysis() { registerListener(); }

Target:
You should call super() here
Source:
public boolean isProviderFor(CSSDiagram diagram) { if(diagram.getElement() instanceof Element){ //Retrieve the UML2 element Element element = (Element)diagram.getElement(); //Introspect its packages to check if SysML profile is applied if (SysMLResource.isSysMLProfileApplied(element)){ return true; } } return false; }

Target:
return the result without if
Source:
public ThreadedHistoryTreeBackendTest(Boolean reOpen) { super(reOpen); }

Target:
The notion of reopening does not apply to the threaded backend. When you re-open you should always use the non-threaded backend, because there should be no future insertions. Here I'd be tempted to just say "super(false)". It would still run the same tests twice though (it does now anyway).
Source:
protected IStateHistoryBackend getBackendForQuerying(IStateHistoryBackend backend) { if (!fReOpen) { return backend; } backend.dispose(); try { return new HistoryTreeBackend(SSID, checkNotNull(fTempFile), PROVIDER_VERSION); } catch (IOException e) { fail(e.getMessage()); return null; } }

Target:
assertNotNull fTempFile
Source:
public void testGetChangedAttributesWithAttachments() { TaskAttribute attributeAttachment = newData.getRoot().createAttribute("custom"); attributeAttachment.setValue("1"); attributeAttachment.getMetaData().setType(TaskAttribute.TYPE_ATTACHMENT); TaskDataDiff diff = manager.createDiff(newData, oldData, new NullProgressMonitor()); assertEquals(diff.getNewAttachments(), Collections.singleton(attributeAttachment)); }

Target:
Expected value should be first.
Source:
protected void testIntersections(Comparison comparison) { assertFalse(Iterables.any(comparison.getDifferences(), new Predicate<Diff>() { @SuppressWarnings("restriction") public boolean apply(Diff input) { return Iterators.size(Iterators .filter(input.getRefines().iterator(), not(instanceOf(MultiplicityReferenceChange.class)))) > 1; } })); }

Target:
What is the purpose of testIntersections(Comparison)? It looks weird that we need to filter MultiplicityReferenceChanges here and not any of the other numerous UMLDiff extensions. Maybe we should filter those that we are interested in here instead.
Source:
public <T> Set<T> including(Set<T> set, T object) { if (set.contains(object)) { return Sets.newLinkedHashSet(set); } else { Set<T> result = Sets.newLinkedHashSet(set); result.add(object); return result; } }

Target:
we probably want to return the set itself in this case even if it's not the same behavior on List.
Source:
public void childContextAdded(VElement parentElement, EMFFormsViewContext childContext) { final EMFFormsSettingToControlMapper mapper = childContext.getService(EMFFormsSettingToControlMapper.class); validate(getAllEObjectsToValidate(mapper)); }

Target:
use the root controlMapper instead
Source:
public void launch(ISelection selection, String mode) { if (selection instanceof IStructuredSelection) { Object element = ((IStructuredSelection)selection).getFirstElement(); if (element != null && element instanceof IResource) { IResource selectedResource = (IResource) element; launch(selectedResource, mode); } } }

Target:
perhaps it is better to check selection.isEmpty() first before continuing to other checks and also eliminating the need for null checks.
Source:
protected GdbLaunch getGDBLaunch() { return (GdbLaunch) getSession().getModelAdapter(ILaunch.class); }

Target:
Let's not create this new API. Instead, in doInitialize() set a member variable to store the launch. Or make this method private.
Source:
public void stop(BundleContext context) throws Exception { REGISTRY.dispose(); sessionFactoryRegistryListener.dispose(); sessionFactoryRegistryListener = null; deleteHookDescriptorRegistryListener.dispose(); deleteHookDescriptorRegistryListener = null; javaActionRegistryListener.dispose(); javaActionRegistryListener = null; ViewpointRegistry.getInstance().dispose(); MultiLanguagesValidator.getInstance().dispose(); ResourceStrategyRegistry.getInstance().clearRegistry(); super.stop(context); }

Target:
See sessionFactoryRegistryListener.dispose() and other extension points.
Source:
public @NonNull Map<@NonNull String, @NonNull String> getProperties() { Map<@NonNull String, @NonNull String> properties = new HashMap<>(); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyFile), NonNullUtils.checkNotNull(fSourceFile.getName())); properties.put(NonNullUtils.checkNotNull(Messages.XmlModuleHelper_PropertyType), NonNullUtils.checkNotNull(fType.name())); return properties; }

Target:
I don't think this can return null. We should probably add an external annotation.
Source:
protected Composite createControlComposite(Composite composite) { final Composite controlComposite = new Composite(composite, SWT.NONE); GridDataFactory.fillDefaults().grab(true, true).align(SWT.FILL, SWT.FILL).hint(1, getTableHeightHint()) .applyTo(controlComposite); GridLayoutFactory.fillDefaults().numColumns(1).applyTo(controlComposite); return controlComposite; }

Target:
can't you remove this call and only do it later?
Source:
private void reflowAsync() { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { getParentSection().getTaskEditorPage().reflow(); } }); }

Target:
call reflow() instead?
Source:
public static IEditorDescriptor getEditorDescriptor(IFile file) throws PartInitException { try { return getEditorDescriptor(file, true, false); } catch (OperationCanceledException ex) { throw new PartInitException(ex.getMessage(), ex); } }

Target:
This should just call the old method like in 4.5: ==> return getEditorDescriptor(file, true);
Source:
public boolean hasVariable(final String identifier) { if (identifier == null || identifier.isEmpty()) return false; return getVariable(identifier) != null; }

Target:
remove unnecessary checks
Source:
public static SWTBotTreeItem getTreeItem(final SWTBotTreeItem[] treeElements, final String name) { SWTBotTreeItem foundTreeItem = null; if (treeElements != null && treeElements.length > 0) { for (SWTBotTreeItem swtBotTreeItem : treeElements) { if (swtBotTreeItem.getText().equals(name)) { foundTreeItem = swtBotTreeItem; break; } foundTreeItem = getTreeItem(swtBotTreeItem.getItems(), name); if (foundTreeItem != null) { break; } } } return foundTreeItem; }

Target:
You could use SWTBotTreeItem.getNode(s)(String) instead of doing text equality test and catch WidgetNotFoundException to iterate recursively on children items.
Source:
public Map<String, String> getTraceProperties() { Map<String, String> properties = new HashMap<>(); properties.putAll(fTrace.getEnvironment()); properties.put(CLOCK_OFFSET, Long.toUnsignedString(fTrace.getOffset())); properties.put(Messages.CtfTmfTrace_HostID, getHostId()); return properties; }

Target:
This method was added in java 8. It will fail with java 7. Note that it might compile on Gerrit because we compile with java 8.
Source:
public void tearDown() throws Exception { super.tearDown(); if (editor != null) { editor.close(false); editor = null; } }

Target:
The editor can't be null
Source:
public Long getUuid() { return new Long(getArtId()); }

Target:
use Long.valueOf() instead of new Long() - always for performance reasons
Source:
public ITmfStateProvider getNewInstance() { return new KernelMemoryStateProvider(this.getTrace(), this.fLayout); }

Target:
remove the this.
Source:
public @NonNull String eventKmemPageAlloc() { return "kmem:page_alloc"; //$NON-NLS-1$ }

Target:
you do not need the @NonNull
Source:
public int getMaximumSize() { int maxSize = 0; for (IDeclaration field : fFields) { maxSize += field.getMaximumSize(); } return Math.min(maxSize, Integer.MAX_VALUE); }

Target:
maxSize being an int, that Math.min is quite unnecessary. But you do need to make sure it did not overflow, so I'd say Math.max(0, maxSize);
Source:
public final void run() { doRun(); fHasDrawnEntries = true; fDirty.decrementAndGet(); }

Target:
A possible problem with this is that it relies on the zoom thread, and you might have an implementation that does not use any zoom list or thread (could override createZoomThread() to return null). Also, it's not clear what value the flag should have if you have completed the zoom with an empty entry list, or if the entries are all filtered out. Does it work if the build thread has done a first iteration and called refresh() but hasn't discovered any entries yet?
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append("[TimeLineEvent Values=").append(getValues()) //$NON-NLS-1$ .append(", Entry=").append(getEntry()) //$NON-NLS-1$ .append(", fTime=").append(getTime()) //$NON-NLS-1$ .append(", Duration=").append(getDuration()) //$NON-NLS-1$ .append(']'); return builder.toString(); }

Target:
The format of the names is inconsistent, also remove duration.
Source:
public String getLabel() { String label = fLabel; if (label == null) { StringJoiner sj = new StringJoiner(", "); //$NON-NLS-1$ getValues().forEach((Long value) -> sj.add(NumberFormat.getNumberInstance(Locale.getDefault()).format(value))); label = sj.toString(); fLabel = label; } return label; }

Target:
When addValue() is called (or if the user changes the list returned by getValues()), the label is not changed and becomes inconsistent!
Source:
public String getValueAt(int column) { String value = getColumns().get(column); if (value.equals(StringConstants.UNICODE_NULL)) { return null; } return value; }

Target:
Switch equals check (a.equals(b) --> b.equals(a)) is null-safe and potentially faster.
Source:
void setColumns(List<String> columns) { for (ListIterator<String> iterator = columns.listIterator(); iterator .hasNext();) { String string = iterator.next(); iterator.set(StringUtils.defaultIfEmpty(string, StringConstants.UNICODE_NULL)); } m_columns = columns; }

Target:
Editing on setter is making the collection dirty.
Source:
public Map<IPath, RepositoryMapping> getRepositoryMappings() { return mappings; }

Target:
Presumably you'd want to return here a read-only view of mappings.
Source:
private void gtk_swt_set_border_color (GdkColor color) { //Convert GtkColor to GdkRGBA //TODO : Reactor in future commit. This and widget:setForegroundColor have duplicate code. GdkRGBA rgba = null; if (color != null) { rgba = new GdkRGBA (); rgba = display.toGdkRGBA (color); } //Construct CSS String //TODO : Reactor in future commit. // This and Control:setBackgroundColorGradient(..). as there is similar code. // ideally we should have a 'constructCssString(..) that accepts attribute-value pairs. String css_string = "* {\n"; if (rgba != null) { String css_color = gtk_rgba_to_css_string (rgba); css_string += "border-color: " + css_color + ";\n"; } css_string += "}\n"; //Apply CSS to widget. long /*int*/context = OS.gtk_widget_get_style_context (handle); gtk_css_provider_load_from_css (context, css_string); }

Target:
As display.toGdkRGBA never returns null remove "rgba=new GdkRGBA()"
Source:
GdkRGBA gdk_color_to_rgba (GdkColor color) { GdkRGBA rgba = null; if (color != null) { rgba = new GdkRGBA (); rgba = display.toGdkRGBA (color); } return rgba; }

Target:
As display.toGdkRGBA never returns null remove "rgba=new GdkRGBA()"
Source:
private static TmfTreeViewerEntry createTraceEntry(ITmfTrace trace) { TmfTreeViewerEntry traceEntry = new TmfTreeViewerEntry(trace.getName()); Iterable<ITmfAnalysisModuleWithStateSystems> modules = TmfTraceUtils.getAnalysisModulesOfClass(trace, ITmfAnalysisModuleWithStateSystems.class); for (ITmfAnalysisModuleWithStateSystems module : modules) { /* Just schedule the module, the data will be filled when available */ module.schedule(); if (!module.waitForInitialization()) { return traceEntry; } for (ITmfStateSystem ss : module.getStateSystems()) { traceEntry.addChild(new StateSystemEntry(ss)); } } return traceEntry; }

Target:
Don't return, just do a continue so other modules can still add their state systems as children.
Source:
public boolean waitForInitialization() { try { fInitialized.await(); } catch (InterruptedException e) return fInitializationSucceeded; }

Target:
Here too false should be returned
Source:
public void testInitialization() { assertNull(fModule.getStateSystem()); fModule.schedule(); assertEquals("Initialization succeeded", true, fModule.waitForInitialization()); assertNotNull(fModule.getStateSystem()); }

Target:
assertTrue instead
Source:
public boolean visit(LambdaExpression node) { fCurrentMethodsAndLambdas.push(node); return visit((Expression) node); }

Target:
Can be written as: return super.visit(node); for consistency.
Source:
public @NonNull String getSymbolText(long address) { if ((address & (0xFFFFFFFF << 32)) != 0) { return String.format("%08x", address); //$NON-NLS-1$ } return String.format("%016x", address); //$NON-NLS-1$ }

Target:
Wouldn't this implementation apply to all cases? It looks like a generic utility method. Should it be defined as a default, perhaps even a static, method in the interface?
Source:
protected void parseReverseMethod(String output) { if (output.toString().contains("Processor")) { //$NON-NLS-1$ fReverseMethod = ReverseTraceMethod.PROCESSOR_TRACE; } else if (output.toString().contains("Branch")) { //$NON-NLS-1$ fReverseMethod = ReverseTraceMethod.BRANCH_TRACE; } else if (output.toString().contains("full")) { //$NON-NLS-1$ fReverseMethod = ReverseTraceMethod.FULL_TRACE; } else { fReverseMethod = ReverseTraceMethod.STOP_TRACE; } }

Target:
Why the toString()? output is already a String. I've pushed a new patch that removes them and reformats some stuff
Source:
public Iterable<ITmfEventAspect> getEventAspects() { ImmutableSet.Builder<ITmfEventAspect> builder = ImmutableSet.builder(); builder.addAll(super.getEventAspects()); builder.add(KernelTidAspect.INSTANCE); builder.add(ThreadPriorityAspect.INSTANCE); return NonNullUtils.checkNotNull(builder.build()); }

Target:
This method has an external annotation now.
Source:
public Object execute(final ExecutionEvent event) throws ExecutionException { final ISelection currentSelection = HandlerUtil.getCurrentSelection(event); final Resource resourceSelected = getSelectedResource(currentSelection); final TableConfiguration configuration = getEditedTableConfiguration(resourceSelected); CreateNattableConfigurationWizard wizard = new CreateNattableConfigurationWizard(configuration, resourceSelected); WizardDialog dialog = new WizardDialog(Display.getDefault().getActiveShell(), wizard); dialog.open(); return null; }

Target:
final
Source:
protected MasterObjectAxisProvider getMasterObjectAxisProvider(final TableConfiguration configuration) { MasterObjectAxisProvider master = null; // Try to get an existing master axis provider if (0 < configuration.getRowAxisProviders().size()) { final Iterator<AbstractAxisProvider> rowAxisProvidersIterator = configuration.getRowAxisProviders().iterator(); while (rowAxisProvidersIterator.hasNext() && null == master) { AbstractAxisProvider axisProvider = rowAxisProvidersIterator.next(); if (axisProvider instanceof MasterObjectAxisProvider) { master = (MasterObjectAxisProvider) axisProvider; } } } return master; }

Target:
final
Source:
protected SlaveObjectAxisProvider getSlaveObjectAxisProvider(final TableConfiguration configuration) { SlaveObjectAxisProvider slave = null; // Try to get an existing master axis provider if (0 < configuration.getRowAxisProviders().size()) { final Iterator<AbstractAxisProvider> columnAxisProvidersIterator = configuration.getColumnAxisProviders().iterator(); while (columnAxisProvidersIterator.hasNext() && null == slave) { AbstractAxisProvider axisProvider = columnAxisProvidersIterator.next(); if (axisProvider instanceof SlaveObjectAxisProvider) { slave = (SlaveObjectAxisProvider) axisProvider; } } } return slave; }

Target:
final
Source:
public static final boolean isSingleColumnTreeTable(final TableConfiguration tableConfiguration) { TableDisplayStyle style = (TableDisplayStyle) tableConfiguration.getStyle(NattablestylePackage.eINSTANCE.getTableDisplayStyle()); Assert.isNotNull(style); final DisplayStyle displayStyle = style.getDisplayStyle(); return DisplayStyle.HIERARCHIC_SINGLE_TREE_COLUMN.equals(displayStyle); }

Target:
final
Source:
private boolean isOverrideType(String type) { return Arrays.asList(OVERRIDE_TYPES).contains(type); }

Target:
Use the set in the class variable directly.
Source:
public @NonNull Image getIcon() { String iconFile = getIconFile(); if (iconFile != null) { Bundle bundle = getBundle(); if (bundle != null) { Image icon = TmfProjectModelIcons.loadIcon(bundle, iconFile); if (icon != null) { return icon; } } } return TmfProjectModelIcons.DEFAULT_ANALYSIS_ICON; }

Target:
Is this an artifact or intentional? It's not in the interface.
Source:
public UnassociatedEditorStrategyRegistry getUnassociatedEditorStrategyRegistry() { if (unassociatedEditorStrategyRegistry == null) { unassociatedEditorStrategyRegistry = new UnassociatedEditorStrategyRegistry(); } return unassociatedEditorStrategyRegistry; }

Target:
Should be synchronized
Source:
public void before() { writer = new StringWriter(); delegate = new HtmlDocumentBuilder(writer); delegate.setEmitAsDocument(false); builder = new HtmlSubsetDocumentBuilder(delegate); builder.setSupportedBlockTypes(Sets.newHashSet(BlockType.PARAGRAPH)); builder.setSupportedSpanTypes(Sets.newHashSet(SpanType.BOLD), Collections.<SpanHtmlElementStrategy> emptyList(), ImmutableMap.<SpanType, String> of()); builder.setSupportedHeadingLevel(3); builder.beginDocument(); }

Target:
these changes would be unnecessary if the builder had a separate method for setting span substitutions
Source:
private Set<String> toDirSet(String dirs) { if (dirs == null || dirs.length() == 0) return Collections.emptySet(); Set<String> configuredStrings = new HashSet<String>(); StringTokenizer tok = new StringTokenizer(dirs, File.pathSeparator); while (tok.hasMoreTokens()) { configuredStrings .add(workspacePath.resolve(tok.nextToken()).toString()); } return configuredStrings; }

Target:
While you're touching this, why not add the missing braces? And maybe use dirs.isEmpty()?
Source:
protected void setupInternals() throws IOException { if (getObjectDirectory() == null) { if (getGitCommonDir() != null) setObjectDirectory( safeFS().resolve(getGitCommonDir(), OBJECTS)); // $NON-NLS-1$ else if (getGitDir() != null) setObjectDirectory(safeFS().resolve(getGitDir(), OBJECTS)); // $NON-NLS-1$ } }

Target:
style nit: missing braces
Source:
public static SetMultimap<String, String> getRequirementValuesMap(Iterable<IAnalysisRequirementProvider> providers) { SetMultimap<String, String> valuesByType = NonNullUtils.checkNotNull(HashMultimap.create()); for (IAnalysisRequirementProvider provider : providers) { for (TmfAnalysisRequirement requirement : provider.getAnalysisRequirements()) { valuesByType.putAll(requirement.getType(), requirement.getValues()); } } return valuesByType; }

Target:
This should be added to external annotations instead.
Source:
public void cleanup() { File tempFile = fTempFile; if (tempFile != null) { tempFile.delete(); } }

Target:
There is a guarantee that the first statement after a if is executed without being preempted. But only the very first statement [1]. So you could null-check directly on fTempFile here. It's very good practice to extract to a local variable in general, but here it's a very small method that does only one thing, it would be fine, imo. [1] I remember this I think from a class a looong time ago, but I can't find any references online... The compiler seems to agree with me though. Or it's a bug and I'm becoming crazy? :O
Source:
public @NonNull String getTraceHost() { return fHostThread.getHost(); }

Target:
You could add a package-info.java file to the package
Source:
public Object getParameter(String name) { if (name.equals(CriticalPathModule.PARAM_WORKER)) { final HostThread currentHostThread = fCurrentHostThread; if (currentHostThread == null) { return null; } /* Try to find the worker for the critical path */ IAnalysisModule mod = getModule(); if ((mod != null) && (mod instanceof CriticalPathModule)) { LttngWorker worker = new LttngWorker(currentHostThread, "", 0); //$NON-NLS-1$ return worker; } return currentHostThread; } return null; }

Target:
I really don't know why currentHostThread is returned (or the previous entry)... Only the critical path module needs anything. You could remove this line while updating this file.
Source:
private ArrayList<DataChangedEvent> getReuseChangedEvents( Set<IComponentNamePO> reuseChangedCompNames) { ArrayList<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : reuseChangedCompNames) { events.add(new DataChangedEvent(compName, DataState.ReuseChanged, UpdateState.all)); } return events; }

Target:
Please use interfaces where possible.
Source:
private ArrayList<DataChangedEvent> getRenamedEvents(Set<IComponentNamePO> renamedCompNames) { ArrayList<DataChangedEvent> events = new ArrayList<DataChangedEvent>(); for (IComponentNamePO compName : renamedCompNames) { events.add(new DataChangedEvent(compName, DataState.Renamed, UpdateState.all)); } return events; }

Target:
Please use interfaces where possible.
Source:
public String getCellDataValueByPosition(int row, int col) { assertIsLegalCell(row, col); Object obj = widget.getDataValueByPosition(col, row); if(obj != null) { return obj.toString(); } else return ""; }

Target:
block please
Source:
public SWTBotRootMenu contextMenu(final Control control) throws WidgetNotFoundException { waitForEnabled(); rightClick(); Rectangle location = widgetBounds(); return NatTableContextMenuFinder.contextMenu(widget, location.x + (location.width / 2), location.y + (location.height / 2)); }

Target:
In a real application the order of events will be MouseDown, MenuDetect, MouseUp. Here you will send the MenuDetect only later below in the NatTableContextMenuFinder. Since, for now, NatTable requires the MouseDown event, perhaps it would be better to not call rightClick here but instead send those mouse events from the NatTableContextMenuFinder?
Source:
public SWTBotMenu contextMenu(int row, int col, String text) throws WidgetNotFoundException { assertIsLegalCell(row, col); Assert.isNotNull(text); waitForEnabled(); rightClick(row, col); Rectangle location = widget.getBoundsByPosition(col, row); return NatTableContextMenuFinder.contextMenu(widget, location.x + (location.width / 2), location.y + (location.height / 2), text); }

Target:
Here it's OK, assuming getBoundsByPosition is cell's bound relative to NatTable control.
Source:
public SWTBotRootMenu contextMenu(final Control control) throws WidgetNotFoundException { waitForEnabled(); Rectangle location = widgetBounds(); return NatTableContextMenuFinder.contextMenu(widget, location.width / 2, location.height / 2); }

Target:
I think we want to leave this one as protected. The user should call the public contextMenu() that will in turn call this one.
Source:
public @NonNull Iterable<@NonNull TmfAnalysisRequirement> getAnalysisRequirements() { Set<@NonNull TmfAnalysisRequirement> requirements = fAnalysisRequirements; if (requirements == null) { LttngUstTrace trace = getTrace(); ILttngUstEventLayout layout = ILttngUstEventLayout.DEFAULT_LAYOUT; if (trace != null) { layout = trace.getEventLayout(); } requirements = ImmutableSet.of(new LttngUstCallStackAnalysisRequirement(layout)); fAnalysisRequirements = requirements; } return requirements; }

Target:
here, to avoid first assignation, you could (trace != null) ? trace.getEventLayout : ILttngUst....
Source:
static ISideEffectFactory createFactory() { ICompositeSideEffect compositeSideEffect = ICompositeSideEffect.create(); return new SideEffectFactory(compositeSideEffect::add); }

Target:
Oh, I was thinking that the 0-argument version shouldn't create an ICompositeSideEffect at all. You'd use the 0-arg one to obtain an ISideEffectFactory that does exactly the same thing as the static methods on ISideEffect. I'd suggest calling the default constructor on SideEffectFactory here.
Source:
public boolean intersects(long timestamp) { return (start <= timestamp && end >= timestamp); }

Target:
Unrelated to this patch. Again this is a good change, but it adds diff noise.
Source:
private String getCombinedLabels(IThreadDMContext processDmc, IMIExecutionDMContext execDmc) { // get the process label IThreadDMData processData = getData(processDmc); String label = getLabel(processData); // get the execution (thread) context label if (execDmc != null) { int threadId; try { threadId = Integer.parseInt(execDmc.getThreadId()); label += !label.isEmpty() ? ": " : ""; //$NON-NLS-1$//$NON-NLS-2$ label += "Thread [" + Integer.toString(threadId) + "]"; //$NON-NLS-1$//$NON-NLS-2$ } catch (NumberFormatException e) { // No additional label adjustments } } return label; }

Target:
In this block, you could avoid doing two conversions(String -> int, int -> String), and use directly the String value returned by execDmc.getThreadId()? That way this code will be ready to handle the "new" thread ids without change.
Source:
public synchronized static void storeOnImageRegistry(String key, ImageDescriptor descriptor) { getImageRegistry().put(key, descriptor); }

Target:
can now go back to private
Source:
public void tearDown() throws Exception { LogReaderService logReaderService = appContext.get(LogReaderService.class); logReaderService.removeLogListener(listener); if (wb != null) { wb.close(); } appContext.dispose(); }

Target:
I think "throws Exception" is unnecessary
Source:
public boolean isEmpty() { return this.toProcess.isEmpty(); }

Target:
synchronize
Source:
private Session getOrOpenTargetSession(final URI sessionResourceUri) { Session session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); if (session == null) { // Try to open a session. ModelingProjectManager.INSTANCE.loadAndOpenRepresentationsFile(sessionResourceUri, true); // Wait the end of the loading of the representations file try { Job.getJobManager().join(AbstractRepresentationsFileJob.FAMILY, new NullProgressMonitor()); } catch (InterruptedException e) { throw new RuntimeException(e); } session = SessionManager.INSTANCE.getExistingSession(sessionResourceUri); } return session; }

Target:
Before, with waitOtherJobs, we "Do nothing" in case of InterruptedException. Why do you change that? Have you test the difference?
Source:
public TypedElementBoundsRenderer(VControl vElement, ViewModelContext viewContext, ReportService reportService, EMFFormsDatabinding emfFormsDatabinding, EMFFormsLabelProvider emfFormsLabelProvider, VTViewTemplateProvider vtViewTemplateProvider) { super(vElement, viewContext, reportService, emfFormsDatabinding, emfFormsLabelProvider, vtViewTemplateProvider); dbc = new EMFDataBindingContext(); }

Target:
you can use the databindingcontext from the super class
Source:
StackItemsModelChangeListener(Map<VStackLayout, Setting> stackToSetting) { this.stackToSetting = new LinkedHashMap<VStackLayout, EStructuralFeature.Setting>(); this.stackToSetting.putAll(stackToSetting); }

Target:
why not simply assign?
Source:
public void setInitializationData(IConfigurationElement config, String propertyName, Object data) throws CoreException { fAdditionalContentTypesIDs = new String[0]; if (data != null) { if (data instanceof String && data.toString().length() > 0) { fAdditionalContentTypesIDs = StringUtils.unpack(data.toString()); } } }

Target:
This is a bit puzzling. Is instanceof really necessary?
Source:
private ICPPEvaluation deref(ICPPEvaluation ptr, boolean isRef, ActivationRecord record, ConstexprEvaluationContext context) { ICPPEvaluation derefEval = new EvalUnary(ICPPASTUnaryExpression.op_star, ptr, null, context.getPoint()).computeForFunctionCall(record, context); if(isRef) { return derefEval; } else { return new EvalFixed(derefEval.getType(null), derefEval.getValueCategory(null), derefEval.getValue(null)); } }

Target:
This can be static like isEqual().
Source:
public ICPPEvaluation[] getAll() { return new ICPPEvaluation[] {this.getEvaluation()}; }

Target:
"this" is redundant here
Source:
public static IoOperationType getType(int rwbs) { if (rwbs % 2 == 0) { return READ; } return WRITE; }

Target:
return ((rwbs & 1) == 0) ? READ:WRITE; ?
Source:
public boolean isModelerResource() { if (resource.getURI() != null) { return new FileQuery(resource.getURI().fileExtension()).isVSMFile(); } return false; }

Target:
Looks like we might need the same try catch here.
Source:
protected final void activate(BundleContext bundleContext) { databindingServiceReference = bundleContext.getServiceReference(EMFFormsDatabindingEMF.class); if (databindingServiceReference == null) { throw new IllegalStateException( "The org.eclipse.emfforms.spi.core.services.databinding.emf.EMFFormsDatabindingEMF Service is not available!"); //$NON-NLS-1$ } setEMFFormsDatabinding(bundleContext.getService(databindingServiceReference)); }

Target:
should be loaded lazy
Source:
public void init(Composite parent, String viewerName, ITmfTrace trace) { super.init(parent, viewerName); // Increment a counter to make sure the tree ID is unique. fCountInstance++; fInstanceNb = fCountInstance; fTrace = trace; // The viewer will process all events if he is assigned to an experiment fProcessAll = (trace instanceof TmfExperiment); initContent(parent); initInput(); fSash.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { internalDispose(); } }); }

Target:
lambda?
Source:
public synchronized IndexWriter getTimestampsWriter() { if (fTimestampsWriter == null) { try { Directory indexDir = FSDirectory .open(Paths.get(fIndexRoot.append(fContainerId) .append(TIMESTAMPS_DIR).toOSString())); IndexWriterConfig config = new IndexWriterConfig( new SimpleAnalyzer()); config.setOpenMode(OpenMode.CREATE_OR_APPEND); fTimestampsWriter = new IndexWriter(indexDir, config); } catch (IOException e) { Logger.logException(e); } } return fTimestampsWriter; }

Target:
as Lucene works with java7 Path, then IPath from eclipse is probably not needed, fIndexRoot can be declared as string, and then: Paths.get(fIndexRoot, fContainerId, TIMESTAMPS_DIR) (similar code in a few places)
Source:
protected EEFWidgetStyle getWidgetStyle(EEFConditionalStyle conditionalStyle) { return ((EEFButtonConditionalStyle) conditionalStyle).getStyle(); }

Target:
if (conditionalStyle instanceof EEFButtonConditionalStyle) { ... } Even if given the state of the code we could safely say today that we will not have a class cast exception, I can't condone casting something without testing its type first.
Source:
public void setInstallLocation(File installLocation) { if (installLocation != null && !installLocation.equals(fInstallLocation)) { fInstallLocation= installLocation; } }

Target:
Why is the equals needed here?
Source:
public void setJSRuntimeArguments(String runtimeArgs) { if (fRuntimeArgs == null) { if (runtimeArgs == null) { // No change return; } } else if (fRuntimeArgs.equals(runtimeArgs)) { // No change return; } fRuntimeArgs = runtimeArgs; }

Target:
Is there a reason for not trying to update the fRuntimeArgs value if there are not changes?
Source:
private static Integer getSelectionIndex(SWTBotView viewBot) { final TimeGraphControl timegraph = viewBot.bot().widget(WidgetOfType.widgetOfType(TimeGraphControl.class)); return UIThreadRunnable.syncExec(new IntResult() { @Override public Integer run() { return timegraph.getSelectedIndex(); } }); }

Target:
lambda
Source:
public void run() { FindTarget findTarget = fFindTarget; if (findTarget == null) { return; } checkShell(findTarget); if (fDialog == null) { fDialog = new TimeGraphFindDialog(findTarget.getShell()); } if (fDialog != null) { fDialog.update(findTarget); fDialog.open(); fDialog.getShell().setMinimumSize(SHELL_MINIMUM_SIZE, SHELL_MINIMUM_SIZE); } }

Target:
This would better belong in TimeGraphFindDialog.create(), once you have a Shell but before it is made visible. Also, the minimumSize should be set using the result of computeTrim() to which you pass these values. I intermittently get a minimum height that is too small by the height of the trim, this might be the reason.
Source:
public Repository open(HttpServletRequest req, String name) throws RepositoryNotFoundException, ServiceNotEnabledException { if (!name.equals(repoName)) throw new RepositoryNotFoundException(name); final Repository db = repo.getRepository(); db.incrementOpen(); return db; }

Target:
unnecessary
Source:
public String getMessage(EObject eObject, String value) { URI uri = eObject.eResource().getURI(); if (uri != null && uri.isPlatformPlugin() && uri.segmentCount() > 1) { // Segment 0 is the scheme // Segment 1 is the bundle Bundle bundle = Platform.getBundle(uri.segment(1)); return MessageTranslator.INSTANCE.getMessage(bundle, value); } return value; }

Target:
Possible NPE if we're passed an EObject which is not part of a Resource.
Source:
protected void tearDown() throws Exception { Locale.getDefault(); Locale.setDefault(default_language); sessionAirdResource = null; localSession = null; editor = null; super.tearDown(); }

Target:
Why is this needed?
Source:
protected Supplier<String> internalGetAttribute(String attr) { if ("type".equals(attr)) { return () -> attributeType; } return super.internalGetAttribute(attr); }

Target:
This is unsafe, since attributeType is protected and can be set to null, but the contract is to return supplier only on non null values. This must be rewritten to check for the null value first.