auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void applyGlobalLogRotators( Job<?,?> job, List<LogRotatorMapping> rotators ) throws IOException, InterruptedException { for( LogRotatorMapping mapping : rotators ) { if( job.getFullName().matches( mapping.getJobNameRegex() ) ) { mapping.getLogRotator().perform( job ); return; } } LOGGER.log( FINE, Messages.LogRotatorPeriodicTask_noGlobalMatch( job.getFullName() ) ); }

Target:
```suggestion LOGGER.log( FINE, () -> Messages.LogRotatorPeriodicTask_noGlobalMatch( job.getFullName() ) ); ```
Source:
public int getClassLoadingCount() throws IOException, InterruptedException { if (getChannel() == null) { return -1; } return channel.call(new LoadingCount(false)); }

Target:
The main difference i see between the two PRs is that this PR leverages the use of `getChannel()` which only returns a `channel` object. Just a few lines later the same function uses the `channel` object directly. From a readability standpoint this is pretty confusing as a reader might misinterpret that `getChannel()` does something different behind the scenes which in actual fact it doesn't.
Source:
public void cancelQuietDownShouldSuccessOnQuietDownedJenkins() throws Exception { j.jenkins.get().doQuietDown(); QuietDownCommandTest.assertJenkinsInQuietMode(j); final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER) .invoke(); assertThat(result, succeededSilently()); QuietDownCommandTest.assertJenkinsNotInQuietMode(j); }

Target:
```suggestion j.jenkins.doQuietDown(); ```
Source:
public static final void assertJenkinsInQuietMode(final JenkinsRule j) { await().pollInterval(250, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) .until(() -> j.jenkins.get().getQueue().isBlockedByShutdown(task)); }

Target:
```suggestion .until(() -> j.jenkins.getQueue().isBlockedByShutdown(task)); ```
Source:
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { if (!ResourceDomainConfiguration.isResourceRequest(req) && ResourceDomainConfiguration.isResourceDomainConfigured()) { resourceToken = ExtensionList.lookupSingleton(ResourceDomainRootAction.class).getToken(this, req); } try { serveFile(req,rsp,base,icon,serveDirIndex); } catch (InterruptedException e) { throw new IOException("interrupted",e); } }

Target:
More legible to introduce a `ResourceDomainRootAction.get()`.
Source:
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException { Jenkins.get().checkPermission(Jenkins.ADMINISTER); if(dismiss!=null) { disable(true); return HttpResponses.redirectViaContextPath("/manage"); } else { return HttpResponses.redirectTo("rule/"); } }

Target:
👎 Strongly against restoring this insanity again. Currently we do not need to rely on individual admin monitor authors having their shit together, this would once again negate this.
Source:
public ListBoxModel doFillTimeZoneNameItems() { String current = forCurrentUser(); ListBoxModel items = new ListBoxModel(); items.add(Messages.TimeZoneProperty_DisplayDefaultTimeZone(), ""); for (String id : TimeZone.getAvailableIDs()) { if (id.equalsIgnoreCase(current)) { items.add(new Option(id, id, true)); } else { items.add(id); } } Messages.TimeZoneProperty_DisplayName(); return items; }

Target:
Is this line doing something?
Source:
public FormValidation doCheckURIEncoding(StaplerRequest request) { Jenkins.get().checkPermission(Jenkins.ADMINISTER); // expected is non-ASCII String final String expected = "\u57f7\u4e8b"; final String value = fixEmpty(request.getParameter("value")); if (!expected.equals(value)) return FormValidation.warningWithMarkup(hudson.model.Messages.Hudson_NotUsesUTF8ToDecodeURL()); return FormValidation.ok(); }

Target:
unrelated
Source:
public void startupShouldNotFailOnIOExceptionOnlineListener() { // We do nothing, IOExceptionOnOnlineListener & JenkinsRule should cause the // boot failure if the issue is not fixed. Assert.assertEquals(1, IOExceptionOnOnlineListener.onOnlineCount); }

Target:
```suggestion assertEquals(1, IOExceptionOnOnlineListener.onOnlineCount); ``` I suggest following the existing pattern in this file and calling the assert() methods directly. Then the new import also wouldn't be needed.
Source:
private JSONArray formatEventsAndInitialize() { // Save the current events and clean for next (not this one) telemetry send ConcurrentHashMap<List<StackTraceElement>, MissingClassEvent> toReport = MissingClassTelemetry.events.getEventsAndClean(); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Cleaned events for missing classes"); return formatEvents(toReport); }

Target:
I think we tend to use brackets here.
Source:
public void replaceNodeShouldNotRemoveIdenticalOldNode() throws Exception { Node oldNode = r.createSlave("foo", "", null); Node newNode = r.createSlave("foo", "", null); r.jenkins.addNode(oldNode); r.jenkins.getNodesObject().replaceNode(oldNode, newNode); r.jenkins.getNodesObject().load(); assertNotNull(r.jenkins.getNode(oldNode.getNodeName())); }

Target:
```suggestion assertNotNull(r.jenkins.getNode("foo")); ```
Source:
protected Object readResolve() { if(defaultExcludes == null) { defaultExcludes = true; } if(caseSensitive == null) { caseSensitive = true; } return this; }

Target:
Better `private`.
Source:
public boolean isActivePeriod() { LocalDate now = LocalDate.now(); if (getStart().isAfter(now)) { return false; } if (getEnd().isBefore(now)) { return false; } return true; }

Target:
I at least would find this easier to read as ```suggestion return now.isAfter(getStart()) && now.isBefore(getEnd()); ```
Source:
private boolean verifySignature(Signature signature, String providedSignature) { // We can only make one call to Signature#verify here. // Since we need to potentially check two values (one decoded from hex, the other decoded from base64), // try hex first: It's almost certainly going to fail decoding if a base64 string was passed. // It is extremely unlikely for base64 strings to be a valid hex string. // This way, if it's base64, the #verify call will be skipped, and we continue with the #verify for decoded base64. // This approach might look unnecessarily clever, but short of having redundant Signature instances, // there doesn't seem to be a better approach for this. try { if (signature.verify(Hex.decodeHex(providedSignature.toCharArray()))) { return true; } } catch (SignatureException|DecoderException ignore) { // ignore } try { if (signature.verify(Base64.getDecoder().decode(providedSignature))) { return true; } } catch (SignatureException ignore) { // ignore } return false; }

Target:
Should it be also IllegalStateException here?
Source:
public boolean isEnabled() { return !(Jenkins.get()).getDisabledAdministrativeMonitors().contains(id); }

Target:
```suggestion return !Jenkins.get().getDisabledAdministrativeMonitors().contains(id); ```
Source:
private static void sendOneZipEntry(ZipOutputStream zos, VirtualFile vf, String relativePath) throws IOException { // In ZIP archives "All slashes MUST be forward slashes" (http://pkware.com/documents/casestudies/APPNOTE.TXT) // TODO On Linux file names can contain backslashes which should not treated as file separators. // Unfortunately, only the file separator char of the master is known (File.separatorChar) // but not the file separator char of the (maybe remote) "dir". ZipEntry e = new ZipEntry(relativePath.replace('\\', '/')); e.setTime(vf.lastModified()); zos.putNextEntry(e); try (InputStream in = vf.open()) { IOUtils.copy(in, zos); } zos.closeEntry(); }

Target:
add it to `finally`? Otherwise ZIP stream may be corrupted if `cf.open()` or copy fail
Source:
private static void sendZipUsingMap(ZipOutputStream zos, VirtualFile dir, Map<String, VirtualFile> nameToVirtualFiles) throws IOException { for (Map.Entry<String, VirtualFile> entry : nameToVirtualFiles.entrySet()) { String n = entry.getKey(); String relativePath; // JENKINS-19947: traditional behavior is to prepend the directory name relativePath = dir.getName() + '/' + n; VirtualFile f = entry.getValue(); sendOneZipEntry(zos, f, relativePath); } }

Target:
Why not join declaration and assignment?
Source:
public HttpResponse doClear() throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); LOGGER.info("Called clearing..."); clear(); return HttpResponses.redirectViaContextPath("/manage"); }

Target:
```suggestion ```
Source:
protected void printUsageSummary(PrintStream stderr) { stderr.println(Messages.DisablePluginCommand_PrintUsageSummary()); }

Target:
For `printUsageSummary` if you could follow the same format as in `LoginCommand` and `LogoutCommand` for consistency.
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; case NONE: default: // with NONE, the process only fail if mandatory dependant plugins exists dependantsToCheck = Sets.difference(this.getDependants(), this.getOptionalDependants()); } return dependantsToCheck; }

Target:
Why not putting NONE and MANDATORY together?
Source:
public List<Action> getActions() { List<Action> result = new ArrayList<Action>(); result.addAll(getOwner().getViewActions()); synchronized (this) { result.addAll(TransientViewActionFactory.createAllFor(this)); } return result; }

Target:
@agentgonzo I don't think there is a need to keep this `synchronized` anymore is there?
Source:
public CauseOfBlockage getCauseOfBlockage() { long diff = -(System.currentTimeMillis() - timestamp.getTimeInMillis()); if (diff > 100) return CauseOfBlockage.fromMessage(Messages._Queue_InQuietPeriod(Util.getTimeSpanString(diff))); else return CauseOfBlockage.fromMessage(Messages._Queue_FinishedWaiting()); }

Target:
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.
Source:
protected void checkRename(String newName) throws Failure { Jenkins.get().getProjectNamingStrategy().checkName(newName); if (isBuilding()) { throw new Failure(Messages.Job_NoRenameWhileBuilding()); } }

Target:
Should be pulled up to `AbstractItem.doCheckNewName`—it is not specific to `Job`.
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. this(new WriterOutputStream(w), StandardCharsets.UTF_8); }

Target:
The `WriterOutputStream` constructor needs to specify the encoding too, I think, or you will get junk.
Source:
protected ToolDescriptor() { super(); }

Target:
Or can just be omitted: ```java protected ToolDescriptor() ```
Source:
public static void proceedToNextStateFrom(InstallState prior) { InstallState next = getNextInstallState(prior); LOGGER.log(Main.isDevelopmentMode ? Level.INFO : Level.FINE, "Install state transitioning from: " + prior + " to: " + next); if (next != null) { Jenkins.getInstance().setInstallState(next); } }

Target:
NIT: use parameterized logging ```java LOGGER.log(Main.isDevelopmentMode ? Level.INFO : Level.FINE, "Install state transitioning from: {0} to: {1}", new Object[] {from, to}); ```
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 { Files.setPosixFilePermissions(Util.fileToPath(f).toAbsolutePath(), Util.modeToPermissions(mask)); } }

Target:
Why the call `toAbsolutePath`? Should be unnecessary.
Source:
public boolean process(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { Object apiTokenValid = request.getAttribute(BasicHeaderApiTokenAuthenticator.class.getName()); if (apiTokenValid != null && apiTokenValid == Boolean.TRUE) { chain.doFilter(request, response); return true; } return false; }

Target:
i.e., ```java if (Boolean.TRUE.equals(request.getAttribute(BasicHeaderApiTokenAuthenticator.class.getName())) { ```
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); assertEquals(expected, p.getWebResponse().getContentAsString().trim()); }

Target:
BTW `trim` should be unnecessary now that we are using `text` not `plainText`.
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); assertEquals(expectedLogin, p.getWebResponse().getContentAsString().trim()); }

Target:
ditto, could drop `trim`
Source:
public java.util.Calendar getLastModifiedAsCalendar() { final java.util.Calendar cal = new java.util.GregorianCalendar(); cal.setTimeInMillis(lastModified); return cal; }

Target:
Should probably be `@Restricted` when the only reason this exists is the Jelly view.
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 if (EXIT_ON_RESTART == null) { 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); } }

Target:
unrelated change?
Source:
public UserProperty reconfigure(StaplerRequest req, JSONObject form) throws FormException { if (form==null) { return null; } UserPropertyDescriptor descriptor = getDescriptor(); return descriptor==null ? null : descriptor.newInstance(req, form); }

Target:
if the descriptor is null, I think you should just return this (ie keep the property so that it is not lost)
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); parameterDefinition.setChoicesText(choiceText); return parameterDefinition; }

Target:
Why not just use the original constructor?
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 addDisplayNamesToSearchIndex(sib, getItems(false)); return sib; }

Target:
Why is there `false` here?
Source:
protected ChangeLogSet(Run<?,?> run, RepositoryBrowser<?> browser) { this.run = run; build = run instanceof AbstractBuild ? (AbstractBuild) run : null; this.browser = browser; this.scm = null; }

Target:
Use `this(run, browser, null)` to avoid code duplication
Source:
public DeprecatedAgentProtocolMonitor() { super(AgentProtocol.class.getName() + "-deprecated"); }

Target:
delete and use the default ID
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()) { VersionNumber v = new VersionNumber(p.version); if (versionNumber == null || v.isNewerThan(versionNumber)) versionNumber = v; } return versionNumber; }

Target:
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)`.
Source:
public View getView(String name) { for (View v : views) { if (v.getViewName().equals(name)) return v; if (v instanceof ViewGroup) { View nestedView = ((ViewGroup) v).getView(name); if (nestedView != null) { return nestedView; } } } return null; }

Target:
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
Source:
public @Nonnull String getDescription() { Node node = getNode(); return (node != null) ? node.getNodeDescription() : ""; }

Target:
Maybe better to return 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(); } if(token.equals(name)) result.add(i); } }

Target:
Maybe deserves a separate JIRA ticket if it is important enough
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()){ throw new IOException(String.format("Could not delete %s", next.getAbsolutePath())); } fi.renameTo(next); } } }

Target:
Why do you think that this behaviour is right?
Source:
public boolean removeAll(Collection<?> c) { try { boolean removed = false; for (Object o : c) { removed |= removeSync(o); } return removed; } finally { if (extensions != null) { fireOnChangeListeners(); } } }

Target:
I do not see a reason for invoking listeners if nothing has been removed. 🐜
Source:
public List<Descriptor<ListViewColumn>> getColumnsDescriptors() { StaplerRequest request = Stapler.getCurrentRequest(); View view = request.findAncestorObject(clazz); return view == null ? DescriptorVisibilityFilter.applyType(clazz, ListViewColumn.all()) : DescriptorVisibilityFilter.apply(view, ListViewColumn.all()); }

Target:
`request` could be null.
Source:
public void onRollback(@Nonnull NodeProvisioner.PlannedNode plannedNode, @Nonnull Node node, @Nonnull Throwable t) { ; // Noop by default }

Target:
remove redundant `;` it will only cause static analysis to complain
Source:
private 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; }

Target:
Not a final class. Also it's an extension point, which may be potentially doing some migrations in custom implementations from plugins 🐛
Source:
public final Integer getUnstableReturn() { return unstableReturn; }

Target:
Add CheckForNull. 🐜
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", Files.size(afw.getTemporaryPath()) == expectedContent.length()); }

Target:
use `assertEquals`
Source:
public void disable() throws IOException { throw new IllegalStateException("does not support disable/enable"); }

Target:
Maybe IOException since it's supported here?
Source:
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; }

Target:
NIT: would be great to have brackets in the new code
Source:
UrlFactory getUrlFactory() { if (urlFactory != null) { return urlFactory; } else { return DEFAULT_URL_FACTORY; } }

Target:
should be able to make this private.
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?) ? return null; } catch (Exception x) { throw (IOException) new IOException(x.toString()).initCause(x); } }

Target:
need to catch IOException and rethrow to avoid wrapping it in another IOException below.
Source:
static void move(File src, File dest) throws IOException { try { Files.move(src.toPath(), dest.toPath()); } catch (Exception x) { throw new IOException(x); } }

Target:
catch IOException and rethrow to avoid wrapping an IOException with an IOException
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")); } ; }); return sorted; }

Target:
NIT: strange formatting glitches
Source:
public void onLoaded() { wa.contextDestroyed(null); // make the Jenkins.<init> thread abort throw new Error(); }

Target:
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.
Source:
/*package*/ void resolvePluginDependencies() throws IOException { List<Dependency> missingDependencies = new ArrayList<Dependency>(); // 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); } }

Target:
Source is on 1.7 level, see diamond operator.
Source:
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, true); }

Target:
@deprecated unless you are going to use a `DataBoundSetter` as suggested by @KostyaSha
Source:
private boolean isEmpty() { for (JDKFamily f : data) { if (f.releases.length>0) return false; } return true; }

Target:
:bug: Binary compatibility
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); } save(); ItemListener.fireOnUpdated(this); }

Target:
`disabledSince` is never reset.
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) { final String errorMsg = String.format("Unexpected exception occurred during performing clear-queue command: %s", e.getMessage()); stderr.println(errorMsg); LOGGER.warning(errorMsg); errorOccurred = true; } return errorOccurred ? 1 : 0; }

Target:
`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?
Source:
public void addAction(Action a) { super.addAction(a); }

Target:
I mean such changes, this is special @jglick coding style.
Source:
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; }

Target:
I think LOGGER was legitimate in this case, because it is not related to slave logs
Source:
public 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(); } }

Target:
The new method implementation should be synchronized
Source:
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); } }); } }

Target:
Gratuitous whitespace-only changes should be avoided to minimize work with cherry-picking etc.
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(); assertTrue("Running mklink failed (cmd=" + cmd + ")", p.waitFor() == 0); return junc; }

Target:
NIT, the error code may be usefull. `assertEquals(""Running mklink failed (cmd=" + cmd + ")", 0, p.waitFor());`
Source:
@Override 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; }

Target:
:ant: for not follow the convention in this file.
Source:
public void setJDKs(Collection<? extends JDK> jdks) { this.jdks = new ArrayList<JDK>(jdks); }

Target:
Definitely restricted, especially if we consider moving JDK installer into plugin.
Source:
public static List<ProcessKillingVeto> all() { Jenkins jenkins = Jenkins.getInstance(); if ( null == jenkins ) return Collections.emptyList(); return jenkins.getExtensionList(ProcessKillingVeto.class); }

Target:
Commonly in Jenkins we use another order of parameters in comparisons. I'm not sure if it's defined somewhere in code conventions
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"); assert url != null; assertTrue("expected to find the class from foo1 plugin", url.toString().contains("plugins/foo1")); }

Target:
Minor: Its better to use JUnit assertions
Source:
public TerminationRequest(String message) { super(message); }

Target:
would be helpful to record the date/time here as well.
Source:
public boolean isInRange(int idx) { return find(idx)>-1; }

Target:
This should be trivial to unittest.
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(); LOGGER.log(Level.SEVERE, "Failed to build dependency graph for " + projectName,e); } } } }

Target:
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.
Source:
public static boolean isDefaultName(String name) { 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; }

Target:
Consider `@Restricted(NoExternalUse.class)`, I see no reason to make this public API.
Source:
public CloudProvisioningRequest(Label label, int workloadToProvision, Collection<? extends Actionable> queue) { this.label = label; this.workloadToProvision = workloadToProvision; this.queue = new ArrayList<Actionable>(queue); }

Target:
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.
Source:
public int size() { return permissions.size(); }

Target:
IMO it should be synchronized as well
Source:
public Shell(String command) { this(command, 0); }

Target:
Not actually backwards compatible: Existing shell steps will report UNSTABLE instead of SUCCESS.
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); } }

Target:
`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); } ```
Source:
public ArtifactArchiver(String artifacts, String excludes, boolean latestOnly) { this(artifacts, excludes, latestOnly, false, false, true); }

Target:
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.
Source:
public byte[] get() { try { FileInputStream inputStream = null; try { inputStream = new FileInputStream(file); return IOUtils.toByteArray(inputStream); } finally { if (inputStream != null) { inputStream.close(); } } } catch (IOException e) { throw new Error(e); } }

Target:
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(); } ```
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{ fileExclusionManager = new FileExclusionManager(); } ChangedList.getInstance() .setFileExclusionManager(this.fileExclusionManager); }

Target:
would be more consistent to use this.fileExclusionManager here
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(); System.exit(1); } }

Target:
Also, don't use System.exit. Just throw a RuntimeException or something
Source:
public Iterable<IClasspathEntry> load(IJavaProject project) throws FileNotFoundException, CoreException { Iterable<IClasspathEntry> classpath = super.load(project); if(configuration.isDownloadJavaDoc()) { return attacher.attach(project, classpath); } return classpath; }

Target:
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.
Source:
public void canRetrieveUsers() throws Exception { MatcherAssert.assertThat( "Retrieved inexistent user", new User.Smart( new MkGithub().users().get("other") ).exists(), new IsEqual<>(true) ); }

Target:
@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
Source:
private Long createdAt(final Release release) { 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; }

Target:
@weisebrazil `long` should be enough (lower case `l`)
Source:
public void connectsToAnotherGithubServer() throws Exception { final RtGithub github = new RtGithub(URI.create("http://localhost:12345")); MatcherAssert.assertThat( github.entry().uri().toString(), Matchers.equalTo( "http://localhost:12345/" ) ); }

Target:
@perfa we can inline this variable.
Source:
public void fetchesCommit() throws IOException { final Commit cmmt = StatusTest.commit(); MatcherAssert.assertThat( new Status.Smart( new RtStatus(cmmt, Json.createObjectBuilder().build()) ).commit(), Matchers.equalTo(cmmt) ); }

Target:
@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).
Source:
private static long now() { final long sinceepoch = new Date().getTime(); return sinceepoch - (sinceepoch % Tv.THOUSAND); }

Target:
@cvrebert why not use integer division instead of subtracting the remainder?
Source:
public String xpath() { return String.format( "/github/repos/repo[@coords='%s']/milestones[number='%d']", this.coords, this.code ); }

Target:
I don't think it's a good idea to make it public. What for?
Source:
public void canSearchForCodes() throws Exception { final MkGithub github = new MkGithub("jeff"); github.repos().create( Json.createObjectBuilder().add("name", "TestCode").build() ); github.users().self(); MatcherAssert.assertThat( github.search().codes("jeff", "repositories", "desc"), Matchers.not(Matchers.emptyIterable()) ); }

Target:
what this line is for? I didn't get it
Source:
public final void canBeRendered() throws Exception { MatcherAssert.assertThat( new MkMarkdown().render( Json.createObjectBuilder() .add("text", "Hello, **world**!") .build() ), Matchers.equalTo("{\"text\":\"Hello, **world**!\"}") ); }

Target:
brr.. this doesn't look like a real implementation. would be much better to return `Hello, **world**!`.
Source:
public final String raw( @NotNull(message = "Markdown can't be NULL") final String text ) throws IOException { throw new NotImplementedException("MkMarkdown#raw()"); }

Target:
I think this implementation is exactly the same as `render()`, no need to make a puzzle of it - just copy the line from above.
Source:
public void returnIterator() throws IOException { final String user = "testuser1"; final RepoCommits commits = new MkRepoCommits( new MkStorage.InFile(), user, new Coordinates.Simple(user, "testrepo1") ); MatcherAssert.assertThat( commits.iterate( Collections.<String, String>emptyMap() ), Matchers.notNullValue() ); }

Target:
looks like wrong indentation, maybe you forgot to run build with `qulice` profile enabled?
Source:
public Tags tags() { return new RtTags(this.entry, this.entry, this.owner); }

Target:
Why pass `this.entry` twice? Better just use one parameter if they're going to have the same value.
Source:
public static Repo repo() { final String key = System.getProperty("failsafe.github.key"); Assume.assumeThat(key, Matchers.notNullValue()); final String keyrepo = System.getProperty("failsafe.github.repo"); Assume.assumeThat(keyrepo, Matchers.notNullValue()); return new RtGithub(key).repos().get(new Coordinates.Simple(keyrepo)); }

Target:
This method should be `private` in visibility.
Source:
public RtCollaborators(final Request req, final Repo repo) { this.entry = req; final Coordinates coords = repo.coordinates(); this.request = this.entry.uri() .path("/repos") .path(coords.user()) .path(coords.repo()) .path("/collaborators") .back(); this.owner = repo; }

Target:
don't make it public, see how it's done in `RtIssue`
Source:
public Iterable<PullComment> iterate(final Map<String, String> params) { return new RtPagination<PullComment>( this.request.uri().queryParams(params).back(), new RtPagination.Mapping<PullComment, JsonObject>() { @Override public PullComment map(final JsonObject value) { return new RtPullComment( RtPullComments.this.request, RtPullComments.this.owner, value.getInt("id") ); } } ); }

Target:
I think it's better to use `RtPullComments.this.get(value.getInt("id"))`
Source:
private static JsonObject fork( final String organization) throws Exception { return Json.createObjectBuilder() .add("id", 1) .add(ORGANIZATION, organization) .build(); }

Target:
I don't think that `Exception` can ever be thrown by this method
Source:
public void canFetchReadmeFileFromSpecifiedBranch() throws IOException { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple(HttpURLConnection.HTTP_OK, "{\"name\": \"README.md\"}") ).start(); final Contents contents = new RtContents( new ApacheRequest(container.home()), RtContentsTest.repo()); MatcherAssert.assertThat( contents.readme("somebranch"), Matchers.notNullValue() ); container.stop(); }

Target:
I test fails than container will remain started and port is busy. So, good practice is to enclose tested code in `try` block and stop container in `finally`
Source:
public void retrievesForks() throws Exception { final RtForks forks = new RtForks(new FakeRequest(), this.repo()); MatcherAssert.assertThat( forks.iterate("newest"), Matchers.notNullValue() ); }

Target:
the test checks nothing, because `iterate()` method always return nonNull object. It's worth to use `forks.iterate("newest").next()` and check for some attribute
Source:
public void getOrganization() throws Exception { final String login = "github"; final Github github = RtOrganizationsITCase.github(); final Organizations orgs = github.users().self().organizations(); final Organization org = orgs.get(login); MatcherAssert.assertThat(org.login(), Matchers.equalTo(login)); }

Target:
A lot of one-time variables are created. Please, use this manual to fix https://github.com/tpc2/qulice/wiki/mistakes#wiki-one-time-variables
Source:
RtRepos(final Github github, final Request req) { this.ghub = github; this.entry = req; this.createRequest = this.entry.uri().path("user/repos").back(); this.removeRequest = this.entry.uri().path("/repos").back(); }

Target:
What is the point of saving them in class variables, if they are used only once?
Source:
public void throwsWhenResourceIsAbsent() throws Exception { final Limit limit = Mockito.mock(Limit.class); final Throttled throttled = new Throttled(limit, 23); Mockito.when(limit.json()).thenReturn( Json.createObjectBuilder().add("absent", "absentValue").build() ); throttled.json(); MatcherAssert.assertThat( limit.json().toString(), Matchers.equalTo("{}") ); }

Target:
Hm.. you are testing Mockito here, instead of our `Throttled` class :) Are you familiar with TDD, Mockito and JUnit? Can you explain the logic of this test method?
Source:
public boolean starred() throws IOException { final List<String> xpath = this.storage.xml().xpath(String .format("%s/@starred", this.xpath()) ); return !xpath.isEmpty() && StringUtils.equalsIgnoreCase( MkGist.STARRED_VALUE, xpath.get(0) ); }

Target:
Why did you leave String on a previous line?? See https://github.com/tpc2/qulice/wiki/mistakes#indentation
Source:
public void star() throws IOException { final Directives gistlocation = new Directives().xpath( this.xpath() ); final Directives attributelocation = gistlocation.attr( "starred", MkGist.STARRED_VALUE ); this.storage.apply( attributelocation ); }

Target:
This is how it should look: ``` this.storage.apply( new Directives() .xpath(this.xpath()) .attr("starred", Boolean.toString(true)) ); ``` Looks good, huh?
Source:
public void getCashPointsByLocation_shouldReturnAnEmptyListIfTheLocationHasNoCashpoints() throws Exception { Location location = Context.getLocationService().getLocation(1); List<CashPoint> results = service.getCashPointsByLocation(location,false); Assert.assertNotNull(results); Assert.assertEquals(1,results.size()); }

Target:
This does not test what it says it is going to test. This should test that a location with no cash points returns a non-null list with zero items.
Source:
public void findCashPoints_shouldThrowIllegalArgumentExceptionIfTheNameIsEmpty() throws Exception { service.findCashPoints(Context.getLocationService().getLocation(1),"Test 1 Cash Point",false); }

Target:
This test does not expect the exception nor pass in an empty string.
Source:
public static Headers of(StringMap headers) { final Builder builder = new Builder(); if (headers == null) { return builder.build(); } ; headers.forEach(new StringMap.Consumer() { @Override public void accept(String key, Object value) { if (null != value) { builder.add(key, value.toString()); } } }); return builder.build(); }

Target:
@sxci 这个分号？
Source:
public static String userAgent() { String javaVersion = "Java/" + System.getProperty("java.version"); String os = System.getProperty("os.name") + " " + System.getProperty("os.arch") + " " + System.getProperty("os.version"); String sdk = "QiniuJava/" + Constants.VERSION; return sdk + " (" + os + ") " + javaVersion; }

Target:
这个没有必要变更private属性？
Source:
public String deleteApp(String appId) throws Exception { String urlStr = String.format("%s%s%s", host + "/v3/apps/", appId); StringMap headers = auth.authorizationV2(urlStr, "DELETE", null, null); Response response = client.delete(urlStr, headers); String[] resJson = response.getInfo().split("\n"); return response.statusCode + "\n" + resJson[2]; }

Target:
这里写错了，是 host, "/v3/apps/"
Source:
private String getLink(String appId, String roomName, String param) { StringBuilder builder = new StringBuilder(); builder.append(host); builder.append("/v3/apps/" + appId + "/rooms"); if (roomName != null) { builder.append("/" + roomName + "/"); } builder.append(param); return builder.toString(); }

Target:
如果用StringBuilder了，那仍然应该用append方法，不用再用 +，额外创建很多String对象
Source:
private static void setKey(MultipartEntity requestEntity, String key) throws UnsupportedEncodingException{ if(key != null && key.trim().length() > 0){ requestEntity.addPart("key", new StringBody(key,Charset.forName("utf-8"))); } }

Target:
调用 key.trim() 干什么？ 另外，key.length() = 0 并不代表是非法的 key！
Source:
public PutPolicy(String scope, long expiry) { if (expiry <= 0) { throw new IllegalArgumentException("expiry can't be negative or zero!"); } if (scope == null || scope.trim().length() == 0) { throw new IllegalArgumentException("scope can't be null or an empty value!"); } this.scope = scope; this.expiry = System.currentTimeMillis() / 1000 + expiry; }

Target:
PutPolicy.scope 是允许为空字符串的。
Source:
public GetPolicy(String scope, long expiry) { if (scope == null || scope.trim().length() == 0) { throw new IllegalArgumentException("scope can't be null or an empty value!"); } if (expiry <= 0) { throw new IllegalArgumentException("expiry can't be negative or zero!"); } this.expiry = System.currentTimeMillis() / 1000 + expiry; this.scope = scope; }

Target:
scope.trim() 是何意？
Source:
public String makeRequest(String url) { return url + "?exif"; }

Target:
因为没有成员，这个可以声明为 static 了。
Source:
public String getImageMogrURL(String url, String params) { return url + "?imageMogr/" + params ; }

Target:
这一系列方法都是无状态的，考虑声明成static。
Source:
public CallRet saveAs(String targetBucketName, String targetKey, String srcUrl, String opWirthParams) { String entryUrl = targetBucketName + ":" + targetKey ; String encodedUrl = Client.urlsafeEncode(entryUrl) ; String url = srcUrl + "?" + opWirthParams + "/save-as/" + encodedUrl ; CallRet callRet = conn.call(url) ; return callRet ; }

Target:
目前只支持imageMogrify的saveas，这个方法不应该是public的
Source:
protected void configure() { install(new SingularityServiceModule()); }

Target:
side note to bringing in this dep, installing this module would also likely start up a number of pollers/db connections/zk connections/etc which we don't want
Source:
public SingularityWebhookSender(SingularityConfiguration configuration, AsyncHttpClient http, ObjectMapper objectMapper, TaskHistoryHelper taskHistoryHelper, WebhookManager webhookManager) { this.configuration = configuration; this.http = http; this.webhookManager = webhookManager; this.taskHistoryHelper = taskHistoryHelper; this.objectMapper = objectMapper; this.webhookSemaphore = AsyncSemaphore.newBuilder(configuration::getMaxConcurrentWebhooks).build(); this.webhookExecutorService = Executors.newCachedThreadPool(new ThreadFactoryBuilder().setNameFormat("webhooks-%d").build()); }

Target:
Doesn't look like this guy is used anywhere after being created.
Source:
private double getSystemLoadMetric() { switch (systemLoadMetric) { case LOAD_1: return slaveUsage.getSystemLoad1Min(); case LOAD_15: return slaveUsage.getSystemLoad5Min(); case LOAD_5: default: return slaveUsage.getSystemLoad15Min(); } }

Target:
Fat-finger switcheroo here
Source:
public long lock(String requestId, String name) { final long start = System.currentTimeMillis(); LOG.trace("{} - Locking {}", name, requestId); ReentrantLock lock = requestLocks.computeIfAbsent(requestId, (r) -> new ReentrantLock()); lock.lock(); LOG.trace("{} - Acquired lock on ({})", name, requestId, JavaUtils.duration(start)); return System.currentTimeMillis(); }

Target:
Could it be a good idea to accept the calling class here instead of a name, and then log out the class name in the trace logs below? Just to ensure that the names we pass when locking aren't arbitrary and are useful for tracing the flow of the scheduler.
Source:
public void unlock(String requestId, String name, long start) { LOG.trace("{} - Unlocking ({})", name, requestId, JavaUtils.duration(start)); ReentrantLock lock = requestLocks.computeIfAbsent(requestId, (r) -> new ReentrantLock()); lock.unlock(); }

Target:
Should be safe to make `lock()` and `unlock()` private now, and only allow the rest of the scheduler to interact via `runWithRequestLock()`.