auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Set<String> dependantsToCheck(PluginDisableStrategy strategy) { Set<String> dependantsToCheck; switch (strategy) { case MANDATORY: // As of getDependants has all the dependants, we get the difference between them and only the optionals dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); break; case ALL: // getDependants returns all the dependant plugins, mandatory or optional. dependantsToCheck = this.getDependants(); break; START case NONE: END default: // with NONE, the process only fail if mandatory dependant plugins exists dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); } return dependantsToCheck; } Why not putting NONE and MANDATORY together?

Target:
private Set<String> dependantsToCheck(PluginDisableStrategy strategy) { Set<String> dependantsToCheck; switch (strategy) { case ALL: // getDependants returns all the dependant plugins, mandatory or optional. dependantsToCheck = this.getDependants(); break; default: // It includes MANDATORY, NONE: // with NONE, the process only fail if mandatory dependant plugins exists // As of getDependants has all the dependants, we get the difference between them and only the optionals dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); } return dependantsToCheck; }
Source:
public List<Action> getActions() { List<Action> result = new ArrayList<Action>(); result.addAll(getOwner().getViewActions()); START synchronized (this) { END result.addAll(TransientViewActionFactory.createAllFor(this)); } return result; } @agentgonzo I don't think there is a need to keep this `synchronized` anymore is there?

Target:
public List<Action> getActions() { List<Action> result = new ArrayList<>(); result.addAll(getOwner().getViewActions()); result.addAll(TransientViewActionFactory.createAllFor(this)); return result; }
Source:
public CauseOfBlockage getCauseOfBlockage() { long diff = -(System.currentTimeMillis() - timestamp.getTimeInMillis()); START if (diff > 100) END return CauseOfBlockage.fromMessage(Messages._Queue_InQuietPeriod(Util.getTimeSpanString(diff))); else return CauseOfBlockage.fromMessage(Messages._Queue_FinishedWaiting()); } The problem you're originally trying to address is that values are too frequently `???`. This will make it more common, so the exact opposite of what you want. `> -100` if you want to reduce the number of times we enter `else`, but that will need a `Math.max(0, diff)` in the `getTimeSpanString` to not output nonsensical values. TBH I think we can keep this line, or just go with `>=`, and let the _Finished waiting_ message do the rest to make Jenkins look not broken.

Target:
public CauseOfBlockage getCauseOfBlockage() { long diff = timestamp.getTimeInMillis() - System.currentTimeMillis(); if (diff >= 0) return CauseOfBlockage.fromMessage(Messages._Queue_InQuietPeriod(Util.getTimeSpanString(diff))); else return CauseOfBlockage.fromMessage(Messages._Queue_FinishedWaiting()); }
Source:
protected void checkRename(String newName) throws Failure { START Jenkins.get().getProjectNamingStrategy().checkName(newName); END if (isBuilding()) { throw new Failure(Messages.Job_NoRenameWhileBuilding()); } } Should be pulled up to `AbstractItem.doCheckNewName`—it is not specific to `Job`.

Target:
protected void checkRename(String newName) throws Failure { if (isBuilding()) { throw new Failure(Messages.Job_NoRenameWhileBuilding()); } }
Source:
public StreamTaskListener(Writer w) throws IOException { // It's not possible to retrieve the charset that the writer is using; // however, for all uses of this constructor, the writer is an instance // of StringWriter, so it's okay to assume UTF-8. START this(new WriterOutputStream(w), StandardCharsets.UTF_8); END } The `WriterOutputStream` constructor needs to specify the encoding too, I think, or you will get junk.

Target:
public StreamTaskListener(Writer w) throws IOException { // It's not possible to retrieve the charset that the writer is using; // however, for all uses of this constructor, the writer is an instance // of StringWriter, so it's okay to assume UTF-8. this(new WriterOutputStream(w, StandardCharsets.UTF_8), StandardCharsets.UTF_8); }
Source:
protected ToolDescriptor() { START super(); END } Or can just be omitted: ```java protected ToolDescriptor() ```

Target:
protected ToolDescriptor() { }
Source:
public static void proceedToNextStateFrom(InstallState prior) { InstallState next = getNextInstallState(prior); START LOGGER.log(Main.isDevelopmentMode ? Level.INFO : Level.FINE, "Install state transitioning from: " + prior + " to: " + next); END if (next != null) { Jenkins.getInstance().setInstallState(next); } } NIT: use parameterized logging ```java LOGGER.log(Main.isDevelopmentMode ? Level.INFO : Level.FINE, "Install state transitioning from: {0} to: {1}", new Object[] {from, to}); ```

Target:
public static void proceedToNextStateFrom(InstallState prior) { InstallState next = getNextInstallState(prior); if (next != null) { Jenkins.getInstance().setInstallState(next); } }
Source:
private static void _chmod(File f, int mask) throws IOException { // TODO WindowsPosix actually does something here (WindowsLibC._wchmod); should we let it? // Anyway the existing calls already skip this method if on Windows. if (File.pathSeparatorChar==';') return; // noop if (Util.NATIVE_CHMOD_MODE) { PosixAPI.jnr().chmod(f.getAbsolutePath(), mask); } else { START Files.setPosixFilePermissions(Util.fileToPath(f).toAbsolutePath(), Util.modeToPermissions(mask)); END } } Why the call `toAbsolutePath`? Should be unnecessary.

Target:
private static void _chmod(File f, int mask) throws IOException { // TODO WindowsPosix actually does something here (WindowsLibC._wchmod); should we let it? // Anyway the existing calls already skip this method if on Windows. if (File.pathSeparatorChar==';') return; // noop if (Util.NATIVE_CHMOD_MODE) { PosixAPI.jnr().chmod(f.getAbsolutePath(), mask); } else { Files.setPosixFilePermissions(Util.fileToPath(f), Util.modeToPermissions(mask)); } }
Source:
public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { Object apiTokenValid = request.getAttribute(BasicHeaderApiTokenAuthenticator.class.getName()); START if (apiTokenValid != null && apiTokenValid == Boolean.TRUE) { END chain.doFilter(request, response); return true; } return false; } i.e., ```java if (Boolean.TRUE.equals(request.getAttribute(BasicHeaderApiTokenAuthenticator.class.getName())) { ```

Target:
public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (Boolean.TRUE.equals(request.getAttribute(BasicHeaderApiTokenAuthenticator.class.getName()))) { chain.doFilter(request, response); return true; } return false; }
Source:
private void makeRequestAndVerify(String expected) throws IOException, SAXException { WebRequest req = new WebRequest(new URL(j.getURL(), "test-post")); req.setHttpMethod(HttpMethod.POST); req.setEncodingType(null); Page p = wc.getPage(req); START assertEquals(expected, p.getWebResponse().getContentAsString().trim()); END } BTW `trim` should be unnecessary now that we are using `text` not `plainText`.

Target:
private void makeRequestAndVerify(String expected) throws IOException, SAXException { WebRequest req = new WebRequest(new URL(j.getURL(), "test-post")); req.setHttpMethod(HttpMethod.POST); req.setEncodingType(null); Page p = wc.getPage(req); assertEquals(expected, p.getWebResponse().getContentAsString()); }
Source:
private void makeRequestWithAuthCodeAndVerify(String authCode, String expectedLogin) throws IOException, SAXException { WebRequest req = new WebRequest(new URL(j.getURL(),"test")); req.setEncodingType(null); if (authCode!=null) req.setAdditionalHeader("Authorization", authCode); Page p = wc.getPage(req); START assertEquals(expectedLogin, p.getWebResponse().getContentAsString().trim()); END } ditto, could drop `trim`

Target:
private void makeRequestWithAuthCodeAndVerify(String authCode, String expectedLogin) throws IOException, SAXException { WebRequest req = new WebRequest(new URL(j.getURL(),"test")); req.setEncodingType(null); if (authCode!=null) req.setAdditionalHeader("Authorization", authCode); Page p = wc.getPage(req); assertEquals(expectedLogin, p.getWebResponse().getContentAsString()); }
Source:
START public java.util.Calendar getLastModifiedAsCalendar() { END final java.util.Calendar cal = new java.util.GregorianCalendar(); cal.setTimeInMillis(lastModified); return cal; } Should probably be `@Restricted` when the only reason this exists is the Jelly view.

Target:
public Calendar getLastModifiedAsCalendar() { final Calendar cal = new GregorianCalendar(); cal.setTimeInMillis(lastModified); return cal; }
Source:
public void verifyRestartable() throws RestartNotSupportedException { // see http://lists.apple.com/archives/cocoa-dev/2005/Oct/msg00836.html and // http://factor-language.blogspot.com/2007/07/execve-returning-enotsup-on-mac-os-x.html // on Mac, execv fails with ENOTSUP if the caller is multi-threaded, resulting in an error like // the one described in http://www.nabble.com/Restarting-hudson-not-working-on-MacOS--to24641779.html // // according to http://www.mail-archive.com/wine-devel@winehq.org/msg66797.html this now works on Snow Leopard START if (EXIT_ON_RESTART == null) { END if (Platform.isDarwin() && !Platform.isSnowLeopardOrLater()) throw new RestartNotSupportedException("Restart is not supported on Mac OS X"); if (args==null) throw new RestartNotSupportedException("Failed to obtain the command line arguments of the process",failedToObtainArgs); } } unrelated change?

Target:
public void verifyRestartable() throws RestartNotSupportedException { // see http://lists.apple.com/archives/cocoa-dev/2005/Oct/msg00836.html and // http://factor-language.blogspot.com/2007/07/execve-returning-enotsup-on-mac-os-x.html // on Mac, execv fails with ENOTSUP if the caller is multi-threaded, resulting in an error like // the one described in http://www.nabble.com/Restarting-hudson-not-working-on-MacOS--to24641779.html // // according to http://www.mail-archive.com/wine-devel@winehq.org/msg66797.html this now works on Snow Leopard if (Platform.isDarwin() && !Platform.isSnowLeopardOrLater()) throw new RestartNotSupportedException("Restart is not supported on Mac OS X"); if (args==null) throw new RestartNotSupportedException("Failed to obtain the command line arguments of the process",failedToObtainArgs); }
Source:
public UserProperty reconfigure(StaplerRequest req, JSONObject form) throws FormException { if (form==null) { return null; } UserPropertyDescriptor descriptor = getDescriptor(); START return descriptor==null ? null : descriptor.newInstance(req, form); END } if the descriptor is null, I think you should just return this (ie keep the property so that it is not lost)

Target:
public UserProperty reconfigure(StaplerRequest req, JSONObject form) throws FormException { if (form==null) { return null; } UserPropertyDescriptor descriptor = getDescriptor(); return descriptor==null ? this : descriptor.newInstance(req, form); }
Source:
public ParameterDefinition newInstance(@Nullable StaplerRequest req, @Nonnull JSONObject formData) throws FormException { String name = formData.getString("name"); String desc = formData.getString("description"); String choiceText = formData.getString("choices"); ChoiceParameterDefinition parameterDefinition = new ChoiceParameterDefinition(name, desc); START parameterDefinition.setChoicesText(choiceText); END return parameterDefinition; } Why not just use the original constructor?

Target:
public ParameterDefinition newInstance(@Nullable StaplerRequest req, @Nonnull JSONObject formData) throws FormException { String name = formData.getString("name"); String desc = formData.getString("description"); String choiceText = formData.getString("choices"); return new ChoiceParameterDefinition(name, choiceText, desc); }
Source:
public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = new SearchIndexBuilder().addAllAnnotations(this); sib.add(new CollectionSearchIndex<TopLevelItem>() {// for jobs in the view protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } @Override protected String getName(TopLevelItem o) { // return the name instead of the display for suggestion searching return o.getName(); } }); // add the display name for each item in the search index START addDisplayNamesToSearchIndex(sib, getItems(false)); END return sib; } Why is there `false` here?

Target:
public SearchIndexBuilder makeSearchIndex() { SearchIndexBuilder sib = new SearchIndexBuilder().addAllAnnotations(this); sib.add(new CollectionSearchIndex<TopLevelItem>() {// for jobs in the view protected TopLevelItem get(String key) { return getItem(key); } protected Collection<TopLevelItem> all() { return getItems(); } @Override protected String getName(TopLevelItem o) { // return the name instead of the display for suggestion searching return o.getName(); } }); // add the display name for each item in the search index addDisplayNamesToSearchIndex(sib, getItems(true)); return sib; }
Source:
protected ChangeLogSet(Run<?,?> run, RepositoryBrowser<?> browser) { this.run = run; build = run instanceof AbstractBuild ? (AbstractBuild) run : null; this.browser = browser; START this.scm = null; END } Use `this(run, browser, null)` to avoid code duplication

Target:
protected ChangeLogSet(Run<?,?> run, RepositoryBrowser<?> browser) { this(run, browser, null); }
Source:
public DeprecatedAgentProtocolMonitor() { START super(AgentProtocol.class.getName() + "-deprecated"); END } delete and use the default ID

Target:
public DeprecatedAgentProtocolMonitor() { super(); }
Source:
public VersionNumber getNeededDependenciesRequiredCore() { VersionNumber versionNumber = null; try { versionNumber = requiredCore == null ? null : new VersionNumber(requiredCore); } catch (NumberFormatException nfe) { // unable to parse version } for (Plugin p: getAllDependencies()) { START VersionNumber v = new VersionNumber(p.version); END if (versionNumber == null || v.isNewerThan(versionNumber)) versionNumber = v; } return versionNumber; } This looks wrong, it needs to be a core version, not a plugin version, right? I think it should be replaced with `new VersionNumber(p.requiredCore)`.

Target:
public VersionNumber getNeededDependenciesRequiredCore() { VersionNumber versionNumber = null; try { versionNumber = requiredCore == null ? null : new VersionNumber(requiredCore); } catch (NumberFormatException nfe) { // unable to parse version } for (Plugin p: getAllDependencies()) { VersionNumber v = new VersionNumber(p.requiredCore); if (versionNumber == null || v.isNewerThan(versionNumber)) versionNumber = v; } return versionNumber; }
Source:
public View getView(String name) { for (View v : views) { if (v.getViewName().equals(name)) return v; START if (v instanceof ViewGroup) { END View nestedView = ((ViewGroup) v).getView(name); if (nestedView != null) { return nestedView; } } } return null; } The only problem with this approach is that Nested views may appear as a search result even if there is TopLevel view with such name. And as a user I would expect them to have higher priority. Maybe it worth checking all TopLevel views first. I would also vote for making a parameterizable method `View getView(String name, boolean recursive)` and maybe changing only the API calls which are really related to search. Otherwise it it hard to predict the impact of the defaukt behavior change

Target:
public View getView(String name) { //Top level views returned first if match for (View v : views) { if (v.getViewName().equals(name)) { return v; } } for (View v : views) { if (v instanceof ViewGroup) { View nestedView = ((ViewGroup) v).getView(name); if (nestedView != null) { return nestedView; } } } return null; }
Source:
public @Nonnull String getDescription() { Node node = getNode(); START return (node != null) ? node.getNodeDescription() : ""; END } Maybe better to return null

Target:
public @Nonnull String getDescription() { Node node = getNode(); return (node != null) ? node.getNodeDescription() : null; }
Source:
public void find(String token, List<SearchItem> result) { boolean caseInsensitive = UserSearchProperty.isCaseInsensitive(); for (SearchItem i : items){ String name = i.getSearchName(); if(caseInsensitive){ token=token.toLowerCase(); name=name.toLowerCase(); } START if(token.equals(name)) END result.add(i); } } Maybe deserves a separate JIRA ticket if it is important enough

Target:
public void find(String token, List<SearchItem> result) { boolean caseInsensitive = UserSearchProperty.isCaseInsensitive(); for (SearchItem i : items) { String name = i.getSearchName(); if (name.equals(token) || (caseInsensitive && name.equalsIgnoreCase(token))) { result.add(i); } } }
Source:
public void rewind() throws IOException { super.rewind(); for (int i=size-1;i>=0;i--) { File fi = getNumberedFileName(i); if (fi.exists()) { File next = getNumberedFileName(i+1); if (!next.delete()){ START throw new IOException(String.format("Could not delete %s", next.getAbsolutePath())); END } fi.renameTo(next); } } } Why do you think that this behaviour is right?

Target:
public void rewind() throws IOException { super.rewind(); for (int i=size-1;i>=0;i--) { File fi = getNumberedFileName(i); if (fi.exists()) { File next = getNumberedFileName(i+1); next.delete(); fi.renameTo(next); } } }
Source:
public boolean removeAll(Collection<?> c) { try { boolean removed = false; for (Object o : c) { removed |= removeSync(o); } return removed; } finally { if (extensions != null) { START fireOnChangeListeners(); END } } } I do not see a reason for invoking listeners if nothing has been removed. 🐜

Target:
public boolean removeAll(Collection<?> c) { boolean removed = false; try { for (Object o : c) { removed |= removeSync(o); } return removed; } finally { if (extensions != null && removed) { fireOnChangeListeners(); } } }
Source:
public List<Descriptor<ListViewColumn>> getColumnsDescriptors() { StaplerRequest request = Stapler.getCurrentRequest(); START View view = request.findAncestorObject(clazz); END return view == null ? DescriptorVisibilityFilter.applyType(clazz, ListViewColumn.all()) : DescriptorVisibilityFilter.apply(view, ListViewColumn.all()); } `request` could be null.

Target:
public List<Descriptor<ListViewColumn>> getColumnsDescriptors() { StaplerRequest request = Stapler.getCurrentRequest(); if (request != null) { View view = request.findAncestorObject(clazz); return view == null ? DescriptorVisibilityFilter.applyType(clazz, ListViewColumn.all()) : DescriptorVisibilityFilter.apply(view, ListViewColumn.all()); } return ListViewColumn.all(); }
Source:
public void onRollback(@Nonnull NodeProvisioner.PlannedNode plannedNode, @Nonnull Node node, @Nonnull Throwable t) { START ; // Noop by default END } remove redundant `;` it will only cause static analysis to complain

Target:
public void onRollback(@Nonnull NodeProvisioner.PlannedNode plannedNode, @Nonnull Node node, @Nonnull Throwable t) { // Noop by default }
Source:
START private Object readResolve() { END // If we get invalid state from the configuration, fallback to unknown if (StringUtils.isBlank(name)) { LOGGER.log(Level.WARNING, "Read install state with blank name: ''{0}''. It will be ignored", name); return UNKNOWN; } InstallState state = InstallState.valueOf(name); if (state == null) { LOGGER.log(Level.WARNING, "Cannot locate an extension point for the state ''{0}''. It will be ignored", name); return UNKNOWN; } // Otherwise we return the actual state return state; } Not a final class. Also it's an extension point, which may be potentially doing some migrations in custom implementations from plugins 🐛

Target:
protected Object readResolve() { // If we get invalid state from the configuration, fallback to unknown if (StringUtils.isBlank(name)) { LOGGER.log(Level.WARNING, "Read install state with blank name: ''{0}''. It will be ignored", name); return UNKNOWN; } InstallState state = InstallState.valueOf(name); if (state == null) { LOGGER.log(Level.WARNING, "Cannot locate an extension point for the state ''{0}''. It will be ignored", name); return UNKNOWN; } // Otherwise we return the actual state return state; }
Source:
START public final Integer getUnstableReturn() { END return unstableReturn; } Add CheckForNull. 🐜

Target:
public final Integer getUnstableReturn() { return new Integer(0).equals(unstableReturn) ? null : unstableReturn; }
Source:
public void writeToAtomicFile() throws Exception { // Given afw.write(expectedContent, 0, expectedContent.length()); // When afw.flush(); // Then assertTrue("File writer did not properly flush to temporary file", START Files.size(afw.getTemporaryPath()) == expectedContent.length()); END } use `assertEquals`

Target:
public void writeToAtomicFile() throws Exception { // Given afw.write(expectedContent, 0, expectedContent.length()); // When afw.flush(); // Then assertEquals("File writer did not properly flush to temporary file", expectedContent.length(), Files.size(afw.getTemporaryPath())); }
Source:
public void disable() throws IOException { START throw new IllegalStateException("does not support disable/enable"); END } Maybe IOException since it's supported here?

Target:
public void disable() throws IOException { throw new IOException("does not support disable/enable"); }
Source:
public BallColor getIconColor() { RunT lastBuild = getLastBuild(); while (lastBuild != null && lastBuild.hasntStartedYet()) lastBuild = lastBuild.getPreviousBuild(); if(DisableableJobMixIn.isDisabled(this)) START return isBuilding() ? BallColor.DISABLED_ANIME : BallColor.DISABLED; END else if (lastBuild != null) return lastBuild.getIconColor(); else return BallColor.NOTBUILT; } NIT: would be great to have brackets in the new code

Target:
public BallColor getIconColor() { RunT lastBuild = getLastBuild(); while (lastBuild != null && lastBuild.hasntStartedYet()) lastBuild = lastBuild.getPreviousBuild(); if(DisableableJobMixIn.isDisabled(this)) { return isBuilding() ? BallColor.DISABLED_ANIME : BallColor.DISABLED; } else if (lastBuild != null) { return lastBuild.getIconColor(); } else { return BallColor.NOTBUILT; } }
Source:
START UrlFactory getUrlFactory() { END if (urlFactory != null) { return urlFactory; } else { return DEFAULT_URL_FACTORY; } } should be able to make this private.

Target:
private UrlFactory getUrlFactory() { if (urlFactory != null) { return urlFactory; } else { return DEFAULT_URL_FACTORY; } }
Source:
public static String resolveSymlink(@Nonnull File link) throws InterruptedException, IOException { try { Path path = link.toPath(); return Files.readSymbolicLink(path).toString(); } catch (UnsupportedOperationException | FileSystemException x) { // no symlinks on this platform (windows?), // or not a link (// Thrown ("Incorrect function.") on JDK 7u21 in Windows 2012 when called on a non-symlink, // rather than NotLinkException, contrary to documentation. Maybe only when not on NTFS?) ? START return null; END } catch (Exception x) { throw (IOException) new IOException(x.toString()).initCause(x); } } need to catch IOException and rethrow to avoid wrapping it in another IOException below.

Target:
public static String resolveSymlink(@Nonnull File link) throws InterruptedException, IOException { try { Path path = link.toPath(); return Files.readSymbolicLink(path).toString(); } catch (UnsupportedOperationException | FileSystemException x) { // no symlinks on this platform (windows?), // or not a link (// Thrown ("Incorrect function.") on JDK 7u21 in Windows 2012 when called on a non-symlink, // rather than NotLinkException, contrary to documentation. Maybe only when not on NTFS?) ? return null; } catch (IOException x) { throw x; } catch (Exception x) { throw (IOException) new IOException(x.toString()).initCause(x); } }
Source:
static void move(File src, File dest) throws IOException { try { START Files.move(src.toPath(), dest.toPath()); END } catch (Exception x) { throw new IOException(x); } } catch IOException and rethrow to avoid wrapping an IOException with an IOException

Target:
static void move(File src, File dest) throws IOException { try { Files.move(src.toPath(), dest.toPath()); } catch (IOException x) { throw x; } catch (Exception x) { throw new IOException(x); } }
Source:
private Object sortPlugins(List<JSONObject> list) { List<JSONObject> sorted = new ArrayList<>(list); Collections.sort(sorted, new Comparator<JSONObject>() { public int compare(JSONObject j1, JSONObject j2) { return j1.getString("name").compareTo(j2.getString("name")); } START ; END }); return sorted; } NIT: strange formatting glitches

Target:
private Object sortPlugins(List<JSONObject> list) { List<JSONObject> sorted = new ArrayList<>(list); Collections.sort(sorted, new Comparator<JSONObject>() { public int compare(JSONObject j1, JSONObject j2) { return j1.getString("name").compareTo(j2.getString("name")); } }); return sorted; }
Source:
public void onLoaded() { wa.contextDestroyed(null); // make the Jenkins.<init> thread abort START throw new Error(); END } Not going to work once we fix `ItemListener` to catch errors from `onLoaded` implementations, though that is also true of `InduceBootFailure`. But the :bug: is because the fact you needed to do this suggests to me that you somehow regressed the logic in `WebAppMain.contextDestroyed` which is supposed to be interrupting the `initThread` and which this test (from #1950) was verifying.

Target:
public void onLoaded() { wa.contextDestroyed(null); }
Source:
/*package*/ void resolvePluginDependencies() throws IOException { START List<Dependency> missingDependencies = new ArrayList<Dependency>(); END // make sure dependencies exist for (Dependency d : dependencies) { if (parent.getPlugin(d.shortName) == null) missingDependencies.add(d); } if (!missingDependencies.isEmpty()) throw new MissingDependencyException(missingDependencies); // add the optional dependencies that exists for (Dependency d : optionalDependencies) { if (parent.getPlugin(d.shortName) != null) dependencies.add(d); } } Source is on 1.7 level, see diamond operator.

Target:
/*package*/ void resolvePluginDependencies() throws IOException { List<Dependency> missingDependencies = new ArrayList<>(); // make sure dependencies exist for (Dependency d : dependencies) { if (parent.getPlugin(d.shortName) == null) missingDependencies.add(d); } if (!missingDependencies.isEmpty()) throw new MissingDependencyException(this.shortName, missingDependencies); // add the optional dependencies that exists for (Dependency d : optionalDependencies) { if (parent.getPlugin(d.shortName) != null) dependencies.add(d); } }
Source:
public Maven(String targets,String name, String pom, String properties, String jvmOptions, boolean usePrivateRepository, SettingsProvider settings, GlobalSettingsProvider globalSettings) { START this(targets, name, pom, properties, jvmOptions, usePrivateRepository, settings, globalSettings, true); END } @deprecated unless you are going to use a `DataBoundSetter` as suggested by @KostyaSha

Target:
public Maven(String targets,String name, String pom, String properties, String jvmOptions, boolean usePrivateRepository, SettingsProvider settings, GlobalSettingsProvider globalSettings) { this(targets, name, pom, properties, jvmOptions, usePrivateRepository, settings, globalSettings, false); }
Source:
START private boolean isEmpty() { END for (JDKFamily f : data) { if (f.releases.length>0) return false; } return true; } :bug: Binary compatibility

Target:
public boolean isEmpty() { for (JDKFamily f : data) { if (f.releases.length>0) return false; } return true; }
Source:
public void makeDisabled(boolean b) throws IOException { if(disabled==b) return; // noop if (b && !supportsMakeDisabled()) return; // do nothing if the disabling is unsupported this.disabled = b; if (b) { this.disabledSince = System.currentTimeMillis(); Jenkins.getInstance().getQueue().cancel(this); START } END save(); ItemListener.fireOnUpdated(this); } `disabledSince` is never reset.

Target:
public void makeDisabled(boolean b) throws IOException { if(disabled==b) return; // noop if (b && !supportsMakeDisabled()) return; // do nothing if the disabling is unsupported this.disabled = b; if (b) { this.disabledSince = System.currentTimeMillis(); Jenkins.getInstance().getQueue().cancel(this); } else { this.disabledSince = null; } save(); ItemListener.fireOnUpdated(this); }
Source:
protected int run() throws Exception { boolean errorOccurred = false; try { Jenkins.getActiveInstance().doReload(); } catch (AccessDeniedException e) { stderr.println(e.getMessage()); errorOccurred = true; } catch (Exception e) { START final String errorMsg = String.format("Unexpected exception occurred during performing clear-queue command: %s", END e.getMessage()); stderr.println(errorMsg); LOGGER.warning(errorMsg); errorOccurred = true; } return errorOccurred ? 1 : 0; } `clear-queue` instead of `reload-configuration` I guess copy-paste has bitten with #1942 ;-). Couldn't an AbstractCLICommand + strategy pattern be introduced to try and factorize common code?

Target:
protected int run() throws Exception { Jenkins.getActiveInstance().doReload(); return 0; }
Source:
START public void addAction(Action a) { END super.addAction(a); } I mean such changes, this is special @jglick coding style.

Target:
@Override public void addAction(Action a) { super.addAction(a); }
Source:
private OutputStream decorate(OutputStream os) { for (ConsoleLogFilter f : ConsoleLogFilter.all()) { try { os = f.decorateLogger(this,os); } catch (IOException|InterruptedException e) { START logger.log(Level.WARNING, "Failed to filter log with "+f, e); END } } return os; } I think LOGGER was legitimate in this case, because it is not related to slave logs

Target:
private OutputStream decorate(OutputStream os) { for (ConsoleLogFilter f : ConsoleLogFilter.all()) { try { os = f.decorateLogger(this,os); } catch (IOException|InterruptedException e) { LOGGER.log(Level.WARNING, "Failed to filter log with "+f, e); } } return os; }
Source:
START public void setBuildDiscarder(BuildDiscarder bd) throws IOException { END BulkChange bc = new BulkChange(this); try { removeProperty(BuildDiscarderProperty.class); if (bd != null) { addProperty(new BuildDiscarderProperty(bd)); } bc.commit(); } finally { bc.abort(); } } The new method implementation should be synchronized

Target:
public synchronized void setBuildDiscarder(BuildDiscarder bd) throws IOException { BulkChange bc = new BulkChange(this); try { removeProperty(BuildDiscarderProperty.class); if (bd != null) { addProperty(new BuildDiscarderProperty(bd)); } bc.commit(); } finally { bc.abort(); } }
Source:
START public void buildDependencyGraph(final AbstractProject downstream, DependencyGraph graph) { END for (AbstractProject upstream : Items.fromNameList(downstream.getParent(), upstreamProjects, AbstractProject.class)) { graph.addDependency(new DependencyGraph.Dependency(upstream, downstream) { @Override public boolean shouldTriggerBuild(AbstractBuild upstreamBuild, TaskListener listener, List<Action> actions) { return shouldTrigger(upstreamBuild, listener); } }); } } Gratuitous whitespace-only changes should be avoided to minimize work with cherry-picking etc.

Target:
@Override public void buildDependencyGraph(final AbstractProject downstream, DependencyGraph graph) { for (AbstractProject upstream : Items.fromNameList(downstream.getParent(), upstreamProjects, AbstractProject.class)) { graph.addDependency(new DependencyGraph.Dependency(upstream, downstream) { @Override public boolean shouldTriggerBuild(AbstractBuild upstreamBuild, TaskListener listener, List<Action> actions) { return shouldTrigger(upstreamBuild, listener); } }); } }
Source:
private File makeJunction(File baseDir, File pointToDir) throws Exception { File junc = new File(baseDir, "test Junction"); String cmd = "mklink /J \"" + junc.getPath() + "\" \"" + pointToDir.getPath() + "\""; ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", cmd); pb.inheritIO(); Process p = pb.start(); START assertTrue("Running mklink failed (cmd=" + cmd + ")", p.waitFor() == 0); END return junc; } NIT, the error code may be usefull. `assertEquals(""Running mklink failed (cmd=" + cmd + ")", 0, p.waitFor());`

Target:
private File makeJunction(File baseDir, File pointToDir) throws Exception { File junc = new File(baseDir, "test Junction"); String cmd = "mklink /J \"" + junc.getPath() + "\" \"" + pointToDir.getPath() + "\""; ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", cmd); pb.inheritIO(); Process p = pb.start(); assertEquals("Running mklink failed (cmd=" + cmd + ")", 0, p.waitFor()); return junc; }
Source:
START @Override public CauseOfBlockage getCauseOfBlockage() { END // Block builds until they are done with post-production if (isLogUpdated() && !isConcurrentBuild()) { return new BlockedBecauseOfBuildInProgress(getLastBuild()); } if (blockBuildWhenDownstreamBuilding()) { AbstractProject<?,?> bup = getBuildingDownstream(); if (bup!=null) return new BecauseOfDownstreamBuildInProgress(bup); } if (blockBuildWhenUpstreamBuilding()) { AbstractProject<?,?> bup = getBuildingUpstream(); if (bup!=null) return new BecauseOfUpstreamBuildInProgress(bup); } return null; } :ant: for not follow the convention in this file.

Target:
public CauseOfBlockage getCauseOfBlockage() { // Block builds until they are done with post-production if (isLogUpdated() && !isConcurrentBuild()) { return new BlockedBecauseOfBuildInProgress(getLastBuild()); } if (blockBuildWhenDownstreamBuilding()) { AbstractProject<?,?> bup = getBuildingDownstream(); if (bup!=null) return new BecauseOfDownstreamBuildInProgress(bup); } if (blockBuildWhenUpstreamBuilding()) { AbstractProject<?,?> bup = getBuildingUpstream(); if (bup!=null) return new BecauseOfUpstreamBuildInProgress(bup); } return null; }
Source:
START public void setJDKs(Collection<? extends JDK> jdks) { END this.jdks = new ArrayList<JDK>(jdks); } Definitely restricted, especially if we consider moving JDK installer into plugin.

Target:
public synchronized void setJDKs(Collection<? extends JDK> jdks) { this.jdks = new ArrayList<JDK>(jdks); }
Source:
public static List<ProcessKillingVeto> all() { Jenkins jenkins = Jenkins.getInstance(); START if ( null == jenkins ) return Collections.emptyList(); END return jenkins.getExtensionList(ProcessKillingVeto.class); } Commonly in Jenkins we use another order of parameters in comparisons. I'm not sure if it's defined somewhere in code conventions

Target:
public static List<ProcessKillingVeto> all() { Jenkins jenkins = Jenkins.getInstance(); if (jenkins == null) return Collections.emptyList(); return jenkins.getExtensionList(ProcessKillingVeto.class); }
Source:
public void testMaskResourceClassLoader() throws Exception { PluginWrapper pw = jenkins.getPluginManager().getPlugin("foo1"); Class<?> clazz = pw.classLoader.loadClass("org.apache.http.impl.io.SocketInputBuffer"); ClassLoader cl = clazz.getClassLoader(); URL url = cl.getResource("org/apache/http/impl/io/SocketInputBuffer.class"); START assert url != null; END assertTrue("expected to find the class from foo1 plugin", url.toString().contains("plugins/foo1")); } Minor: Its better to use JUnit assertions

Target:
public void testMaskResourceClassLoader() throws Exception { PluginWrapper pw = jenkins.getPluginManager().getPlugin("foo1"); Class<?> clazz = pw.classLoader.loadClass("org.apache.http.impl.io.SocketInputBuffer"); ClassLoader cl = clazz.getClassLoader(); URL url = cl.getResource("org/apache/http/impl/io/SocketInputBuffer.class"); assertNotNull(url); assertTrue("expected to find the class from foo1 plugin", url.toString().contains("plugins/foo1")); }
Source:
START public TerminationRequest(String message) { END super(message); } would be helpful to record the date/time here as well.

Target:
public TerminationRequest(String message) { super(message); this.when = System.currentTimeMillis(); }
Source:
public boolean isInRange(int idx) { START return find(idx)>-1; END } This should be trivial to unittest.

Target:
public boolean isInRange(int idx) { return 0<=idx && idx<size; }
Source:
public void buildDependencyGraph(AbstractProject owner,DependencyGraph graph) { for (Object o : this) { if (o instanceof DependencyDeclarer) { DependencyDeclarer dd = (DependencyDeclarer) o; try { dd.buildDependencyGraph(owner,graph); } catch (RuntimeException e) { String projectName = owner == null ? "unknown" : owner.getFullDisplayName(); START LOGGER.log(Level.SEVERE, "Failed to build dependency graph for " + projectName,e); END } } } } For log messages, better to use `getFullName`. Or simply ``` LOGGER.log(Level.SEVERE, "Failed to build dependency graph for " + owner, e); ``` which will contain the same information (and more) anyway.

Target:
public void buildDependencyGraph(AbstractProject owner,DependencyGraph graph) { for (Object o : this) { if (o instanceof DependencyDeclarer) { DependencyDeclarer dd = (DependencyDeclarer) o; try { dd.buildDependencyGraph(owner,graph); } catch (RuntimeException e) { LOGGER.log(Level.SEVERE, "Failed to build dependency graph for " + owner,e); } } } }
Source:
START public static boolean isDefaultName(String name) { END if (name != null) { return false; } else if (name.equals(DEFAULT_NAME)) { return false; } else if (name.equals("(Default)")) { // DEFAULT_NAME took this value prior to 1.598. return false; } return true; } Consider `@Restricted(NoExternalUse.class)`, I see no reason to make this public API.

Target:
public static boolean isDefaultName(String name) { if ("(Default)".equals(name)) { // DEFAULT_NAME took this value prior to 1.598. return true; } return DEFAULT_NAME.equals(name); }
Source:
public CloudProvisioningRequest(Label label, int workloadToProvision, START Collection<? extends Actionable> queue) { END this.label = label; this.workloadToProvision = workloadToProvision; this.queue = new ArrayList<Actionable>(queue); } Could be package-private I think, since the only expected caller is `NodeProvisioner`, and the point of factoring out a request class is to be able to add more parameters later.

Target:
CloudProvisioningRequest(Label label, int workloadToProvision, Collection<? extends Actionable> queue) { this.label = label; this.workloadToProvision = workloadToProvision; this.queue = new ArrayList<Actionable>(queue); }
Source:
START public int size() { END return permissions.size(); } IMO it should be synchronized as well

Target:
public synchronized int size() { return permissions.size(); }
Source:
public Shell(String command) { START this(command, 0); END } Not actually backwards compatible: Existing shell steps will report UNSTABLE instead of SUCCESS.

Target:
public Shell(String command) { this(command, null); }
Source:
public byte[] readFileToByteArray(File file) throws IOException { InputStream in = null; try { in = org.apache.commons.io.FileUtils.openInputStream(file); return org.apache.commons.io.IOUtils.toByteArray(in); } finally { org.apache.commons.io.IOUtils.closeQuietly(in); START } END } `closeQuietly` is nonsense, do not use it. Simpler to write: ``` InputStream in = org.apache.commons.io.FileUtils.openInputStream(file); try { return org.apache.commons.io.IOUtils.toByteArray(in); } finally { in.close(); } ``` which when we use `-source 7` can be simplified further to ``` try (InputStream in = org.apache.commons.io.FileUtils.openInputStream(file)) { return org.apache.commons.io.IOUtils.toByteArray(in); } ```

Target:
public byte[] readFileToByteArray(File file) throws IOException { InputStream in = org.apache.commons.io.FileUtils.openInputStream(file); try { return org.apache.commons.io.IOUtils.toByteArray(in); } finally { in.close(); } }
Source:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly) { START this(artifacts, excludes, latestOnly, false, false, true); END } Your new constructor takes 4 bools, this passes 3. This calls the 'onlyIfSuccessful' constructor. You can just leave these alone and they'll eventually arrive at the new constructor.

Target:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly) { this(artifacts, excludes, latestOnly, false, false); }
Source:
public byte[] get() { try { FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); return IOUtils.toByteArray(inputStream); } finally { if (inputStream != null) { inputStream.close(); } START } END } catch (IOException e) { throw new Error(e); } } Note that the simpler idiom (which also converts more cleanly to Java 7 syntax) is ``` InputStream inputStream = new FileInputStream(file); try { return IOUtils.toByteArray(inputStream); } finally { inputStream.close(); } ```

Target:
public byte[] get() { try { FileInputStream inputStream = new FileInputStream(file); try { return IOUtils.toByteArray(inputStream); } finally { inputStream.close(); } } catch (IOException e) { throw new Error(e); } }
Source:
protected void setSyncConfig(SyncToolConfig syncConfig) { this.syncConfig = syncConfig; this.syncConfig.setVersion(version); File exclusionListFile = this.syncConfig.getExcludeList(); if(exclusionListFile != null){ this.fileExclusionManager = new FileExclusionManager(exclusionListFile); } else{ START fileExclusionManager = new FileExclusionManager(); END } ChangedList.getInstance() .setFileExclusionManager(this.fileExclusionManager); } would be more consistent to use this.fileExclusionManager here

Target:
protected void setSyncConfig(SyncToolConfig syncConfig) { this.syncConfig = syncConfig; this.syncConfig.setVersion(version); File exclusionListFile = this.syncConfig.getExcludeList(); if(exclusionListFile != null){ this.fileExclusionManager = new FileExclusionManager(exclusionListFile); } else{ this.fileExclusionManager = new FileExclusionManager(); } ChangedList.getInstance() .setFileExclusionManager(this.fileExclusionManager); }
Source:
private void init() { try { //optional properties if (hasPropertyAndNotNull("manual_output")) { manualOutput = Boolean.valueOf(getProperty("manual_output")); } if (hasPropertyAndNotNull("greeting")) { greeting = getProperty("greeting"); } //these two properties are essential to the workflow. If they are null or do not //exist in the INI, the workflow should exit. catPath = getProperty("cat"); echoPath = getProperty("echo"); } catch (Exception e) { e.printStackTrace(); START System.exit(1); END } } Also, don't use System.exit. Just throw a RuntimeException or something

Target:
private void init() { try { //optional properties if (hasPropertyAndNotNull("manual_output")) { manualOutput = Boolean.valueOf(getProperty("manual_output")); } if (hasPropertyAndNotNull("greeting")) { greeting = getProperty("greeting"); } //these two properties are essential to the workflow. If they are null or do not //exist in the INI, the workflow should exit. catPath = getProperty("cat"); echoPath = getProperty("echo"); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
Source:
START public Iterable<IClasspathEntry> load(IJavaProject project) throws FileNotFoundException, CoreException { END Iterable<IClasspathEntry> classpath = super.load(project); if(configuration.isDownloadJavaDoc()) { return attacher.attach(project, classpath); } return classpath; } You can just wrap any weird, checked exceptions like `CoreException` in the unchecked `ProjectConfigurationException`. This means you don't need to modify a bunch of unrelated classes when you throw it.

Target:
public Iterable<IClasspathEntry> load(IJavaProject project) throws FileNotFoundException { Iterable<IClasspathEntry> classpath = super.load(project); if(configuration.isDownloadJavaDoc()) { return attacher.attach(project, classpath); } return classpath; }
Source:
public void canRetrieveUsers() throws Exception { MatcherAssert.assertThat( "Retrieved inexistent user", new User.Smart( new MkGithub().users().get("other") ).exists(), START new IsEqual<>(true) END ); } @paulodamaso but, according to the ticket's [description](https://github.com/jcabi/jcabi-github/issues/1370#issue-306858750) this should be ``false`` since the user doesn't actually exist

Target:
public void canRetrieveUsers() throws Exception { MatcherAssert.assertThat( "Retrieved inexistent user", new User.Smart( new MkGithub().users().get("other") ).exists(), new IsEqual<Boolean>(false) ); }
Source:
START private Long createdAt(final Release release) { END Long result = 0L; try { final Date created = this.smart(release).createdAt(); if (created != null) { result = created.getTime(); } } catch (final IOException iox) { throw new IllegalArgumentException(iox); } return result; } @weisebrazil `long` should be enough (lower case `l`)

Target:
private long createdAt(final Release release) { long result = 0; try { final Date created = this.smart(release).createdAt(); if (created != null) { result = created.getTime(); } } catch (final IOException iox) { throw new IllegalArgumentException(iox); } return result; }
Source:
public void connectsToAnotherGithubServer() throws Exception { START final RtGithub github = new RtGithub(URI.create("http://localhost:12345")); END MatcherAssert.assertThat( github.entry().uri().toString(), Matchers.equalTo( "http://localhost:12345/" ) ); } @perfa we can inline this variable.

Target:
public void connectsToAnotherGithubServer() throws Exception { MatcherAssert.assertThat( new RtGithub(URI.create("http://localhost:12345")) .entry().uri().toString(), Matchers.equalTo( "http://localhost:12345/" ) ); }
Source:
START public void fetchesCommit() throws IOException { END final Commit cmmt = StatusTest.commit(); MatcherAssert.assertThat( new Status.Smart( new RtStatus(cmmt, Json.createObjectBuilder().build()) ).commit(), Matchers.equalTo(cmmt) ); } @cvrebert Let's declare this method (as well as the other methods in this class) as throwing `Exception`, as prescribed [here](http://www.yegor256.com/2014/04/27/typical-mistakes-in-java-code.html?expand=1#test-method-names).

Target:
public void fetchesCommit() throws Exception { final Commit cmmt = StatusTest.commit(); MatcherAssert.assertThat( new Status.Smart( new RtStatus(cmmt, Json.createObjectBuilder().build()) ).commit(), Matchers.equalTo(cmmt) ); }
Source:
private static long now() { final long sinceepoch = new Date().getTime(); START return sinceepoch - (sinceepoch % Tv.THOUSAND); END } @cvrebert why not use integer division instead of subtracting the remainder?

Target:
private static long now() { final long sinceepoch = System.currentTimeMillis(); return sinceepoch - (sinceepoch % Tv.THOUSAND); }
Source:
START public String xpath() { END return String.format( "/github/repos/repo[@coords='%s']/milestones[number='%d']", this.coords, this.code ); } I don't think it's a good idea to make it public. What for?

Target:
private String xpath() { return String.format( "/github/repos/repo[@coords='%s']/milestones[number='%d']", this.coords, this.code ); }
Source:
public void canSearchForCodes() throws Exception { final MkGithub github = new MkGithub("jeff"); github.repos().create( Json.createObjectBuilder().add("name", "TestCode").build() ); START github.users().self(); END MatcherAssert.assertThat( github.search().codes("jeff", "repositories", "desc"), Matchers.not(Matchers.emptyIterable()) ); } what this line is for? I didn't get it

Target:
public void canSearchForCodes() throws Exception { final MkGithub github = new MkGithub("jeff"); github.repos().create( Json.createObjectBuilder().add("name", "TestCode").build() ); MatcherAssert.assertThat( github.search().codes("jeff", "repositories", "desc"), Matchers.not(Matchers.emptyIterable()) ); }
Source:
public final void canBeRendered() throws Exception { MatcherAssert.assertThat( new MkMarkdown().render( Json.createObjectBuilder() .add("text", "Hello, **world**!") .build() ), START Matchers.equalTo("{\"text\":\"Hello, **world**!\"}") END ); } brr.. this doesn't look like a real implementation. would be much better to return `Hello, **world**!`.

Target:
public final void canBeRendered() throws Exception { final String text = "Hello, **world**!"; MatcherAssert.assertThat( new MkMarkdown().render( Json.createObjectBuilder() .add("text", text) .build() ), Matchers.equalTo(text) ); }
Source:
public final String raw( @NotNull(message = "Markdown can't be NULL") final String text ) throws IOException { START throw new NotImplementedException("MkMarkdown#raw()"); END } I think this implementation is exactly the same as `render()`, no need to make a puzzle of it - just copy the line from above.

Target:
public final String raw( @NotNull(message = "Markdown can't be NULL") final String text ) { return text; }