auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testIfRetryIsInvokedBeforeListener() { TestNG tng = create(TestClassSample.class); tng.addListener((ITestNGListener)new MyListener()); tng.run(); START Assertions.assertThat(TestClassSample.messages).containsExactly("afterInvocation", "retry","afterInvocation"); END } Typo: missing space after ","

Target:
public void testIfRetryIsInvokedBeforeListener() { TestNG tng = create(TestClassSample.class); tng.addListener((ITestNGListener)new MyListener()); tng.run(); assertThat(TestClassSample.messages).containsExactly("afterInvocation", "retry", "afterInvocation"); }
Source:
START private static boolean isIncluded(String[] groups, Collection<String> includedGroups, boolean noGroupsSpecified) { END if (noGroupsSpecified) { return isMemberOf(groups, includedGroups); } if (includedGroups.size() == 0) { return true; } else { return isMemberOf(groups, includedGroups); } } What if we have only `private static boolean isIncluded(String[] groups, Collection<String> includedGroups, Collection<String> excludedGroups)` instead of 2 methods?

Target:
private static boolean isIncluded(String[] groups, Collection<String> includedGroups, boolean noGroupsSpecified) { if (noGroupsSpecified) { return isMemberOf(groups, includedGroups); } return (includedGroups.isEmpty() || isMemberOf(groups, includedGroups)); }
Source:
START static public void assertEquals(byte[] actual, byte[] expected) { END assertEquals(actual, expected, ""); } `public static` otherwise sonar will complain.

Target:
public static void assertEquals(byte[] actual, byte[] expected) { assertEquals(actual, expected, ""); }
Source:
public static Method[] excludingMain(Class<?> clazz) { Method[] declaredMethods = clazz.getDeclaredMethods(); List<Method> pruned = new LinkedList<>(); for (Method declaredMethod :declaredMethods) { if ("main".equals(declaredMethod.getName()) && isStaticVoid(declaredMethod) && acceptsStringArray(declaredMethod)) { continue; } pruned.add(declaredMethod); } START return pruned.toArray(new Method[0]); END } Use `size` of `pruned` for the array.

Target:
public static Method[] excludingMain(Class<?> clazz) { Method[] declaredMethods = clazz.getDeclaredMethods(); List<Method> pruned = new LinkedList<>(); for (Method declaredMethod :declaredMethods) { if ("main".equals(declaredMethod.getName()) && isStaticVoid(declaredMethod) && acceptsStringArray(declaredMethod)) { continue; } pruned.add(declaredMethod); } return pruned.toArray(new Method[pruned.size()]); }
Source:
public void testMainMethodExclusionForJunit() { XmlSuite xmlSuite = createXmlSuite("suite"); xmlSuite.setJunit(true); createXmlTest(xmlSuite, "test", JUnitTestClassSample.class); START TestNG tng = create(); END tng.setXmlSuites(Collections.singletonList(xmlSuite)); tng.run(); Assert.assertEquals(tng.getStatus(), 0); } Use `create(xmlSuite)`

Target:
public void testMainMethodExclusionForJunit() { XmlSuite xmlSuite = createXmlSuite("suite"); xmlSuite.setJunit(true); createXmlTest(xmlSuite, "test", JUnitTestClassSample.class); TestNG tng = create(xmlSuite); tng.run(); Assert.assertEquals(tng.getStatus(), 0); }
Source:
private static Map<String, String> getParameters(IMethodInstance im) { XmlTest xmlTest = im.getMethod().getXmlTest(); START Map<String, String> params = xmlTest.getAllParameters(); END params.putAll(im.getMethod().findMethodParameters(xmlTest)); return params; } findMethodParameters is already doing it: https://github.com/cbeust/testng/blob/8d1c11bc267ea52157e20ebf6781d1ca9fe7ed1c/src/main/java/org/testng/internal/BaseTestMethod.java#L780

Target:
private static Map<String, String> getParameters(IMethodInstance im) { XmlTest xmlTest = im.getMethod().getXmlTest(); return im.getMethod().findMethodParameters(xmlTest); }
Source:
START private String constructName(ITestNGMethod method) { END return method.getConstructorOrMethod().getDeclaringClass().getSimpleName() + "." + method.getMethodName(); } `static` is missing

Target:
private static String constructName(ITestNGMethod method) { return method.getConstructorOrMethod().getDeclaringClass().getSimpleName() + "." + method.getMethodName(); }
Source:
private void setClassInvocationFailure(Class<?> clazz, Object instance) { START synchronized(this){ END Set<Object> instances = m_classInvocationResults.get( clazz ); if (instances == null) { instances = Sets.newHashSet(); m_classInvocationResults.put(clazz, instances); } instances.add(instance); } } As I know, `synchronized(this)` is not a good practice, and in your case, you just want a synchronization on `m_classInvocationResults`.

Target:
private void setClassInvocationFailure(Class<?> clazz, Object instance) { synchronized(m_classInvocationResults){ Set<Object> instances = m_classInvocationResults.get( clazz ); if (instances == null) { instances = Sets.newHashSet(); m_classInvocationResults.put(clazz, instances); } instances.add(instance); } }
Source:
public String toString() { START return name().toLowerCase(); END } Maybe specify the names in the constructor (`SKIP("skip")`) so that someone modifying `toString()` by accident won't break the parsing.

Target:
public String toString() { return name; }
Source:
private void initializeCommandLineSuitesParams() { if(null == m_cmdlineSuites) { return; } for (XmlSuite s : m_cmdlineSuites) { if(m_useThreadCount) { START s.setThreadCount(m_threadCount); END } s.setParallel(m_parallelMode); if(m_configFailurePolicy != null) { s.setConfigFailurePolicy(m_configFailurePolicy.toString()); } } } FYI and for future pull requests, it's better to remove this kind of syntactic changes before you send your pull request since they are distracting and add noise. Keep your pull requests to 100% semantic changes so that reviewers can review them more easily and move refactoring and other changes that don't modify the meaning of the code to separate pull requests.

Target:
private void initializeCommandLineSuitesParams() { if(null == m_cmdlineSuites) { return; } for (XmlSuite s : m_cmdlineSuites) { if (m_threadCount != -1) { s.setThreadCount(m_threadCount); } if (m_parallelMode != null) { s.setParallel(m_parallelMode); } if(m_configFailurePolicy != null) { s.setConfigFailurePolicy(m_configFailurePolicy.toString()); } } }
Source:
private static List<Method> getDefaultMethods(Class<?> clazz) { START List<Method> result = null; END for (Class<?> ifc : clazz.getInterfaces()) { for (Method ifcMethod : ifc.getMethods()) { if (!Modifier.isAbstract(ifcMethod.getModifiers())) { if (result == null) { result = new LinkedList<Method>(); } result.add(ifcMethod); } } } return result; } I prefer an empty list instead of `null`

Target:
private static List<Method> getDefaultMethods(Class<?> clazz) { List<Method> result = new LinkedList<Method>(); for (Class<?> ifc : clazz.getInterfaces()) { for (Method ifcMethod : ifc.getMethods()) { if (!Modifier.isAbstract(ifcMethod.getModifiers())) { result.add(ifcMethod); } } } return result; }
Source:
public Object[] next() { START if (m_count < m_objects.length) { END return m_objects[m_count++]; } else { throw new NoSuchElementException(); } } It's a personal taste, but I prefer: ``` java if (m_count >= m_objects.length) { throw new NoSuchElementException(); } return m_objects[m_count++]; ```

Target:
public Object[] next() { if (m_count >= m_objects.length) { throw new NoSuchElementException(); } return m_objects[m_count++]; }
Source:
START public static void setVerbose(int n) { END m_verbose = n; } As each <test> node may have its own verbose value, `m_verbose` has to be non-static.

Target:
public void setVerbose(int n) { m_verbose = n; }
Source:
START public static int runTasksOnce(List<VirtualFSInterface> vfss) { END log.debug("Starting DiskUsageService runTasksOnce ..."); ExecutorService executor = Executors.newSingleThreadExecutor(); vfss.forEach(vfs -> { DiskUsageTask task = new DiskUsageTask(vfs); log.debug("Run task {}", task); executor.submit(task); }); log.debug("Submitted tasks", vfss.size()); executor.shutdown(); return vfss.size(); } Why is this needed?

Target:
public static synchronized int runTasksOnce(List<VirtualFSInterface> vfss) { log.debug("Starting DiskUsageService runTasksOnce ..."); ExecutorService executor = Executors.newSingleThreadExecutor(); vfss.forEach(vfs -> { DiskUsageTask task = new DiskUsageTask(vfs); log.debug("Run task {}", task); executor.submit(task); }); log.debug("Submitted tasks", vfss.size()); executor.shutdown(); return vfss.size(); }
Source:
START public synchronized long getMaxSize() { END return maxSize; } For Max + Min Size, I think synchronized should be removed from the setter methods and just make the variables volatile instead.

Target:
public long getMaxSize() { return maxSize; }
Source:
public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { START getTempFile().delete(); END tmpFile.close(); tmpFile = null; txFile = null; } // Release the pages that were allocated in the transaction... freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; } else { freePages(allocateList); } size = 0; } Shouldn't this temp file delete come after the close of the RandomAccessFile?

Target:
public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { tmpFile.close(); getTempFile().delete(); tmpFile = null; txFile = null; } // Release the pages that were allocated in the transaction... freePages(allocateList); freeList.clear(); allocateList.clear(); writes.clear(); writeTransactionId = -1; } else { freePages(allocateList); } size = 0; }
Source:
public void onDestroy() { StatisticsService.sessionPause(); START StatisticsService.sessionStop(this); END super.onDestroy(); } sessionPause and sessionStop together?

Target:
public void onDestroy() { StatisticsService.sessionStop(this); super.onDestroy(); }
Source:
public EffectiveBuildSettings(String directory, String configuration, String platform) { File file = XCodeAppendBuildPhaseMojo.getBuildEnvironmentFile(directory, configuration, platform); Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); properties = p; } catch (IOException e) { throw new IllegalStateException("Could not read build properties file", e); } finally { START if (fis != null) { END IOUtils.closeQuietly(fis); } } } IOUtils already checks for null...

Target:
public EffectiveBuildSettings(String directory, String configuration, String platform) { File file = XCodeAppendBuildPhaseMojo.getBuildEnvironmentFile(directory, configuration, platform); Properties p = new Properties(); FileInputStream fis = null; try { fis = new FileInputStream(file); p.load(fis); properties = p; } catch (IOException e) { throw new IllegalStateException("Could not read build properties file", e); } finally { IOUtils.closeQuietly(fis); } }
Source:
public String getDisplayName() { START return "SetEnvBuildWrapper"; END } If you put a name, these wrappers will start appearing in the lists IIRC

Target:
public String getDisplayName() { return ""; }
Source:
private boolean isSelfRef(Map.Entry<String, String> env) { if (env.getValue().contains("${".concat(env.getKey()).concat("}"))) { return true; } START if (env.getValue().contains("$".concat(env.getKey()))) { END return true; } return false; } Won't work correctly with: ``` FOO=something $FOOBAR ```

Target:
private static boolean isSelfRef(Map.Entry<String, String> env) { if (env.getValue().contains("${".concat(env.getKey()).concat("}"))) { return true; } if (env.getValue().contains("$".concat(env.getKey()))) { return true; } return false; }
Source:
private static String getUserName(Cause cause) { if (cause instanceof UserIdCause) { Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserName(); START }else if (cause instanceof UserCause) { END Cause.UserCause userCause = (UserCause) cause; return userCause.getUserName(); } return null; } `} else`

Target:
private static String getUserName(Cause cause) { if (cause instanceof UserIdCause) { Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserName(); } else if (cause instanceof UserCause) { Cause.UserCause userCause = (UserCause) cause; return userCause.getUserName(); } return ""; }
Source:
private static String getUserId(Cause cause) { START if (cause instanceof UserIdCause) { END Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserId(); } return null; } ![MINOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-minor.png) Make this line start at column 9. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](http://nemo.sonarqube.org/coding_rules#rule_key=squid%3AIndentationCheck)

Target:
private static String getUserId(Cause cause) { if (cause instanceof UserIdCause) { Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserId(); } return ""; }
Source:
public void reset() { service = null; START messageBusProxy = new MessageBusProxy(); END requestDispatcherProxy = new RequestDispatcherProxy(); } I don't think replacing the bus and dispatcher proxies is a good idea. There could be references to the old proxies that are held by other classes. Like this proxy, you will probably want to reset these bus/dispatcher proxies and close the same instances again.

Target:
public void reset() { service = null; messageBusProxy.reset(); requestDispatcherProxy.reset(); }
Source:
public void testIterator() { final DependentInstanceTestBean testBean = getBeanManager().lookupBean(DependentInstanceTestBean.class).getInstance(); final Instance<DependentBeanA> injectedBean = testBean.getInjectDependentBeanA(); START assertTrue(injectedBean.iterator().hasNext()); END } Glad to see test coverage, but this test is missing some assertions that would make it much more robust. In particular, it should call `Iterator#next()` and verify that the returned value is a `DependentBeanA`. This would be sufficient to reproduce the issue I described above.

Target:
public void testIterator() { final DependentInstanceTestBean testBean = getBeanManager().lookupBean(DependentInstanceTestBean.class).getInstance(); final Instance<DependentBeanA> injectedBean = testBean.getInjectDependentBeanA(); assertTrue(injectedBean.iterator().hasNext()); assertEquals(DependentBeanA.class, injectedBean.iterator().next().getClass()); }
Source:
protected void unpackCommonFields(Element documentElement) throws InvalidReportException { version = XmlUtil.getTextValue(documentElement, "FitNesseVersion"); rootPath = XmlUtil.getTextValue(documentElement, "rootPath"); String dateString = XmlUtil.getTextValue(documentElement, "date"); if (dateString != null) try { date = DateTimeUtil.getDateFromString(dateString); } catch (ParseException e) { START throw new InvalidReportException(String.format("'%s' is not a valid date.", dateString), e); END } unpackFinalCounts(documentElement); totalRunTimeInMillis = getTotalRunTimeInMillisOrZeroIfNotPresent(documentElement); } If you will be replacing %s more often in the message of exceptions of this type, maybe the String.format() can be part of (an extra) constructor for the exception?

Target:
protected void unpackCommonFields(Element documentElement) throws InvalidReportException { version = XmlUtil.getTextValue(documentElement, "FitNesseVersion"); rootPath = XmlUtil.getTextValue(documentElement, "rootPath"); String dateString = XmlUtil.getTextValue(documentElement, "date"); if (dateString != null) try { date = DateTimeUtil.getDateFromString(dateString); } catch (ParseException e) { throw new InvalidReportException(format("'%s' is not a valid date.", dateString), e); } unpackFinalCounts(documentElement); totalRunTimeInMillis = getTotalRunTimeInMillisOrZeroIfNotPresent(documentElement); }
Source:
public static void runPigJob(String[] args) throws Exception { PigStats stats = PigUtil.runPigJob(args, props); PigUtil.dumpHadoopCounters(stats, props); if (stats.isSuccessful()) { return; } if (pigLogFile != null) { handleError(pigLogFile); } START if (isTuningError && jobTryCount <= maxJobRetry) { END throw new RuntimeException("Pig job failed."); } PigUtil.selfKill(); } I don't really like the use of a static `isTuningError` here. I think it would be cleaner to have `handleError` and `runPigJob` return boolean values indicating whether or not there was a tuning error, or to create a new exception type `TuningException` which is thrown to indicate tuning-specific errors.

Target:
public static void runPigJob(String[] args) throws Exception { PigStats stats = PigUtil.runPigJob(args, props); PigUtil.dumpHadoopCounters(stats, props); if (stats.isSuccessful()) { return; } if (pigLogFile != null) { handleError(pigLogFile); } PigUtil.selfKill(); }
Source:
private static String[] removeNullsFromArgArray(String[] argArray) { List<String> argList = new ArrayList(Arrays.asList(argArray)); argList.removeAll(Collections.singleton(null)); START return argList.toArray(new String[0]); END } Why not "return argList.toArray(new String[argList.size()]);" so the String array with the appropriate length is preallocated?

Target:
private static String[] removeNullsFromArgArray(String[] argArray) { List<String> argList = new ArrayList(Arrays.asList(argArray)); argList.removeAll(Collections.singleton(null)); return argList.toArray(new String[argList.size()]); }
Source:
public static List<Variable> getVariablesByRegex( Collection<Variable> variables, String regex) { List<Variable> shortlistedVariables = new ArrayList<Variable>(); START if (variables != null || regex == null) { END for (Variable var : variables) { if (var.getTitle().matches(regex)) { shortlistedVariables.add(var); } } } return shortlistedVariables; } seems we can shortcut when variables == null, no need to OR regex conditions.

Target:
public static List<Variable> getVariablesByRegex( Collection<Variable> variables, String regex) { List<Variable> shortlistedVariables = new ArrayList<Variable>(); if (variables != null && regex != null) { for (Variable var : variables) { if (var.getTitle().matches(regex)) { shortlistedVariables.add(var); } } } return shortlistedVariables; }
Source:
START public static void cancelHadoopTokens(HadoopSecurityManager hadoopSecurityManager, END String userToProxy, File tokenFile, Logger log) { try { hadoopSecurityManager.cancelTokens(tokenFile, userToProxy, log); } catch (HadoopSecurityManagerException e) { e.printStackTrace(); log.error(e.getCause() + e.getMessage()); } catch (Exception e) { e.printStackTrace(); log.error(e.getCause() + e.getMessage()); } } This method can just throw an exception back to caller to decide what to do with the exception. It is not necessary to take in the Logger.

Target:
public static void cancelHadoopTokens(HadoopSecurityManager hadoopSecurityManager, String userToProxy, File tokenFile, Logger log) { try { hadoopSecurityManager.cancelTokens(tokenFile, userToProxy, log); } catch (HadoopSecurityManagerException e) { log.error(e.getCause() + e.getMessage()); } catch (Exception e) { log.error(e.getCause() + e.getMessage()); } }
Source:
public ClientConfiguration getClientConfiguration() { START return clientConfiguration; END } Can we return a copy here?

Target:
public ClientConfiguration getClientConfiguration() { return new ClientConfiguration(clientConfiguration); }
Source:
public String readResource(URI endpoint) throws IOException { Map<String, String> headers = new HashMap<String, String>(); headers.put("User-Agent", USER_AGENT); headers.put("Accept", "*/*"); headers.put("Connection", "keep-alive"); START return readResource(endpoint, CredentialsEndpointRetryPolicy.NO_RETRY, new HashMap<String, String>()); END } Should the third parameter be headers variable created above?

Target:
public String readResource(URI endpoint) throws IOException { Map<String, String> headers = new HashMap<String, String>(); headers.put("User-Agent", USER_AGENT); headers.put("Accept", "*/*"); headers.put("Connection", "keep-alive"); return readResource(endpoint, CredentialsEndpointRetryPolicy.NO_RETRY, headers); }
Source:
START public static final Builder v1Builder(String name) { END return new Builder(name, V1MarshallerSet.marshallers(), V1MarshallerSet.setMarshallers(), StandardUnmarshallerSet.unmarshallers(), StandardUnmarshallerSet.setUnmarshallers()); } Is it possible to define the constants above via the builder? Also final is redundant for static methods.

Target:
public static Builder v1Builder(String name) { return new Builder(name, V1MarshallerSet.marshallers(), V1MarshallerSet.setMarshallers(), StandardUnmarshallerSet.unmarshallers(), StandardUnmarshallerSet.setUnmarshallers()); }
Source:
public String getProxyHost() { START if (proxyHost != null) { END return proxyHost; } else { return getProxyHostProperty(); } } Minor: Can you use the ternary operator here.

Target:
public String getProxyHost() { return (proxyHost != null) ? proxyHost : getProxyHostProperty(); }
Source:
public int getProxyPort() { START if (proxyPort > 0) { END return proxyPort; } else { return getProxyPortProperty(); } } proxyPort >= 0 ?

Target:
public int getProxyPort() { return (proxyPort >= 0) ? proxyPort : getProxyPortProperty(); }
Source:
protected void processRequestPayload(SignableRequest<?> request, byte[] signature, byte[] signingKey, AWS4SignerRequestParams signerRequestParams) { START if (useChunkEncoding(request) && this.isChunkedEncoding) { END AwsChunkedEncodingInputStream chunkEncodededStream = new AwsChunkedEncodingInputStream( request.getContent(), signingKey, signerRequestParams.getFormattedSigningDateTime(), signerRequestParams.getScope(), BinaryUtils.toHex(signature), this); request.setContent(chunkEncodededStream); } } Can you move the second part of the conditional into useChunkEncoding?

Target:
protected void processRequestPayload(SignableRequest<?> request, byte[] signature, byte[] signingKey, AWS4SignerRequestParams signerRequestParams) { if (useChunkEncoding(request)) { AwsChunkedEncodingInputStream chunkEncodededStream = new AwsChunkedEncodingInputStream( request.getContent(), signingKey, signerRequestParams.getFormattedSigningDateTime(), signerRequestParams.getScope(), BinaryUtils.toHex(signature), this); request.setContent(chunkEncodededStream); } }
Source:
private static void speedUpDcoumentBuilderFactory() { START String className = System.getProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME); END if (className == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME.equals(factory.getClass().getName())) { // This would avoid the file system to be accessed every time // the internal DocumentBuilderFactory is instantiated. System.setProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME, DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME); } } } Inline

Target:
private static void speedUpDcoumentBuilderFactory() { if (System.getProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME) == null) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); if (DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME.equals(factory.getClass().getName())) { // This would avoid the file system to be accessed every time // the internal DocumentBuilderFactory is instantiated. System.setProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME, DOCUMENT_BUILDER_FACTORY_IMPL_CLASS_NAME); } } }
Source:
public AWSCredentials getCredentials() { if (profilesConfigFile == null) { synchronized (this) { if (profilesConfigFile == null) { profilesConfigFile = new ProfilesConfigFile(); } } } START if (ProfilesConfigFile.DEFAULT_PROFILE_NAME.equals(profileName)) { END // only override profileName if current profileName is the default one String profileOverride = System.getenv(ProfilesConfigFile.AWS_PROFILE_ENVIRONMENT_VARIABLE); profileOverride = StringUtils.trim(profileOverride); if (!StringUtils.isNullOrEmpty(profileOverride)) { return profilesConfigFile.getCredentials(profileOverride); } } return profilesConfigFile.getCredentials(profileName); } I like the idea of only using the AWS_PROFILE env var if a user hasn't explicitly specified one in the constructor. This change seems pretty close to that behavior, except for the edge case where a user has explicitly passed "default" into the constructor. Could you tweak the code to account for that case? I don't think we'd want the AWS_PROFILE env var to be used in any case where a user did pass in an explicit profile name. This behavior would also keep the handling of the AWS_PROFILE env var consistent with the other AWS SDKs.

Target:
public AWSCredentials getCredentials() { if (profilesConfigFile == null) { synchronized (this) { if (profilesConfigFile == null) { profilesConfigFile = new ProfilesConfigFile(); } } } return profilesConfigFile.getCredentials(profileName); }
Source:
private static int getUnsignedIntValue(String bits){ int value = 0; int i = 0; for (int j = bits.length() - 1; j >= 0; j--, i++) { if (bits.charAt(j) == '1') { START value += (int) Math.pow(2.0, (double) i); END } } return value; } It's better to use shift operators here. Instead of ```java value += (int) Math.pow(2.0, (double) i); ``` it's better to have ```java value += 1 << i; ``` The left-shift operator is equivalent to 2 to the n-th power (`2 ^ i == 1 << i`), and has the advantage of not requiring conversions to floating-point and back, and also avoids any expensive operations that happen inside `Math.pow`. The left-shift operator is a single assembly instruction :)

Target:
private static int getUnsignedIntValue(String bits){ int value = 0; int i = 0; for (int j = bits.length() - 1; j >= 0; j--, i++) { if (bits.charAt(j) == '1') { value += 1 << i; } } return value; }
Source:
protected void binary(byte[] payload, int offset, int len) { LOGGER.finest(() -> "reading block of length " + len + " from " + agent); try { transport.receive(ByteBuffer.wrap(payload, offset, len)); START } catch (IOException e) { error(e); } catch (InterruptedException e) { END error(e); } } ```suggestion } catch (IOException | InterruptedException e) { ```

Target:
protected void binary(byte[] payload, int offset, int len) { LOGGER.finest(() -> "reading block of length " + len + " from " + agent); try { transport.receive(ByteBuffer.wrap(payload, offset, len)); } catch (IOException | InterruptedException e) { error(e); } }
Source:
private List<ExtensionComponent<T>> ensureLoaded() { if(extensions!=null) return extensions; // already loaded START if (jenkins != null && jenkins.getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED) < 0) END return legacyInstances; // can't perform the auto discovery until all plugins are loaded, so just make the legacy instances visible synchronized (getLoadLock()) { if(extensions==null) { List<ExtensionComponent<T>> r = load(); r.addAll(legacyInstances); extensions = sort(r); } return extensions; } } ```suggestion if (jenkins == null || jenkins.getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED) < 0) ```

Target:
private List<ExtensionComponent<T>> ensureLoaded() { if(extensions!=null) return extensions; // already loaded if (jenkins == null || jenkins.getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED) < 0) return legacyInstances; // can't perform the auto discovery until all plugins are loaded, so just make the legacy instances visible synchronized (getLoadLock()) { if(extensions==null) { List<ExtensionComponent<T>> r = load(); r.addAll(legacyInstances); extensions = sort(r); } return extensions; } }
Source:
public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors){ START this.disabledAdministrativeMonitors = disabledAdministrativeMonitors; END } Probably should be cloned here instead of taking a reference to an external object

Target:
public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { synchronized (this.disabledAdministrativeMonitors) { this.disabledAdministrativeMonitors.clear(); this.disabledAdministrativeMonitors.addAll(disabledAdministrativeMonitors); } }
Source:
START public Set<String> getDisabledAdministrativeMonitors(){ END return disabledAdministrativeMonitors; } So what's buggy about the `CopyOnWriteArraySet`?

Target:
public Set<String> getDisabledAdministrativeMonitors(){ synchronized (this.disabledAdministrativeMonitors) { return new HashSet<>(disabledAdministrativeMonitors); } }
Source:
public Set<String> getDisabledAdministrativeMonitors(){ START synchronized (disabledAdministrativeMonitors) { END return disabledAdministrativeMonitors; } } This can just return the object. The synchronization will happen either implicitly through calls to the `Set` methods or when we synchronize on the object explicitly in the setter.

Target:
public Set<String> getDisabledAdministrativeMonitors(){ synchronized (this.disabledAdministrativeMonitors) { return new HashSet<>(disabledAdministrativeMonitors); } }
Source:
START public synchronized void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { synchronized (this.disabledAdministrativeMonitors) { END this.disabledAdministrativeMonitors.clear(); this.disabledAdministrativeMonitors.addAll(disabledAdministrativeMonitors); } } Is it really needed to have `synchronized` method as well as inside the method?

Target:
public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { synchronized (this.disabledAdministrativeMonitors) { this.disabledAdministrativeMonitors.clear(); this.disabledAdministrativeMonitors.addAll(disabledAdministrativeMonitors); } }
Source:
private Object readResolve() { if (loggers == null) { loggers = new ArrayList<>(); } START if (!targets.isEmpty()) { END loggers.addAll(targets.getView()); } if (!loggers.isEmpty()) { targets.addAll(loggers); } return this; } the same is true for targets, this could also be null and would cause a null point exception. ```suggestion if (targets != null && !targets.isEmpty()) { ```

Target:
private Object readResolve() { if (loggers == null) { loggers = new ArrayList<>(); } if (targets != null && !targets.isEmpty()) { loggers.addAll(targets.getView()); } if (!loggers.isEmpty()) { targets.addAll(loggers); } return this; }
Source:
public void doRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { START Jenkins.get().checkPermission(Jenkins.SYSTEM_READ); END LogRecorderManager.doRss(req,rsp,getLogRecords()); } Redundant given https://github.com/jenkinsci/jenkins/pull/4530/files#diff-cb8b7584e7a539c988ae99e9951f7b65R213 and https://github.com/jenkinsci/jenkins/pull/4530/files?w=1#diff-fcc5c10b76c1e25e4ac9caae4fa96acfR71 ?

Target:
public void doRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { LogRecorderManager.doRss(req,rsp,getLogRecords()); }
Source:
public void setSummary(@CheckForNull String summary) throws IOException { checkPermission(UPDATE); START this.description = description; END save(); } Bug, you're setting description instead of summary.

Target:
public void setSummary(@CheckForNull String summary) throws IOException { checkPermission(UPDATE); this.summary = summary; save(); }
Source:
public Api getApi() { START if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) return null; END return new Api(this); } The problem here is that `thirdPartyLicenses` (linked from `/about`) is served by `PluginWrapper`, but `layout.jelly` calls `getApi()` to determine whether to show a link in the footer. Without this change, that would show an exception stack trace at least in the log, possibly on the page, for Overall/Manage users.

Target:
public Api getApi() { if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) { return null; } return new Api(this); }
Source:
public void jenkinsCoreTooOld() throws Exception { PluginWrapper pw = pluginWrapper("fake").requiredCoreVersion("3.0").buildLoaded(); try { pw.resolvePluginDependencies(); fail(); } catch (IOException ex) { assertContains(ex, "Failed to load: fake (42)", "Jenkins (3.0) or higher required"); } START Locale.setDefault(loc); END } Why here? `after()` will run anyways right?

Target:
public void jenkinsCoreTooOld() throws Exception { PluginWrapper pw = pluginWrapper("fake").requiredCoreVersion("3.0").buildLoaded(); try { pw.resolvePluginDependencies(); fail(); } catch (IOException ex) { assertContains(ex, "Failed to load: fake (42)", "Jenkins (3.0) or higher required"); } }
Source:
public int compareTo(HealthReport o) { START return (Integer.compare(this.score, o.score)); END } ```suggestion return Integer.compare(this.score, o.score); ```

Target:
public int compareTo(HealthReport o) { return Integer.compare(this.score, o.score); }
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; } } START END LOGGER.log( FINE, Messages.LogRotatorPeriodicTask_noGlobalMatch( job.getFullName() ) ); } ```suggestion LOGGER.log( FINE, () -> Messages.LogRotatorPeriodicTask_noGlobalMatch( job.getFullName() ) ); ```

Target:
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() ) ); }
Source:
public int getClassLoadingCount() throws IOException, InterruptedException { if (getChannel() == null) { START return -1; END } return channel.call(new LoadingCount(false)); } 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.

Target:
public int getClassLoadingCount() throws IOException, InterruptedException { if (channel == null) { return -1; } return channel.call(new LoadingCount(false)); }
Source:
public void cancelQuietDownShouldSuccessOnQuietDownedJenkins() throws Exception { START j.jenkins.get().doQuietDown(); END QuietDownCommandTest.assertJenkinsInQuietMode(j); final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER) .invoke(); assertThat(result, succeededSilently()); QuietDownCommandTest.assertJenkinsNotInQuietMode(j); } ```suggestion j.jenkins.doQuietDown(); ```

Target:
public void cancelQuietDownShouldSuccessOnQuietDownedJenkins() throws Exception { j.jenkins.doQuietDown(); QuietDownCommandTest.assertJenkinsInQuietMode(j); final CLICommandInvoker.Result result = command .authorizedTo(Jenkins.READ, Jenkins.ADMINISTER) .invoke(); assertThat(result, succeededSilently()); QuietDownCommandTest.assertJenkinsNotInQuietMode(j); }
Source:
public static final void assertJenkinsInQuietMode(final JenkinsRule j) { await().pollInterval(250, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) START .until(() -> j.jenkins.get().getQueue().isBlockedByShutdown(task)); END } ```suggestion .until(() -> j.jenkins.getQueue().isBlockedByShutdown(task)); ```

Target:
public static final void assertJenkinsInQuietMode(final JenkinsRule j) { await().pollInterval(250, TimeUnit.MILLISECONDS) .atMost(10, TimeUnit.SECONDS) .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()) { START resourceToken = ExtensionList.lookupSingleton(ResourceDomainRootAction.class).getToken(this, req); END } try { serveFile(req,rsp,base,icon,serveDirIndex); } catch (InterruptedException e) { throw new IOException("interrupted",e); } } More legible to introduce a `ResourceDomainRootAction.get()`.

Target:
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { if (!ResourceDomainConfiguration.isResourceRequest(req) && ResourceDomainConfiguration.isResourceDomainConfigured()) { resourceToken = ResourceDomainRootAction.get().getToken(this, req); } try { serveFile(req,rsp,base,icon,serveDirIndex); } catch (InterruptedException e) { throw new IOException("interrupted",e); } }
Source:
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException { START Jenkins.get().checkPermission(Jenkins.ADMINISTER); END if(dismiss!=null) { disable(true); return HttpResponses.redirectViaContextPath("/manage"); } else { return HttpResponses.redirectTo("rule/"); } } 👎 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.

Target:
public HttpResponse doAct(@QueryParameter String dismiss) throws IOException { if(dismiss!=null) { disable(true); return HttpResponses.redirectViaContextPath("/manage"); } else { return HttpResponses.redirectTo("rule/"); } }
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); } } START Messages.TimeZoneProperty_DisplayName(); END return items; } Is this line doing something?

Target:
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); } } return items; }
Source:
START public FormValidation doCheckURIEncoding(StaplerRequest request) { END 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(); } unrelated

Target:
public FormValidation doCheckURIEncoding(StaplerRequest request) throws IOException { 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(); }
Source:
public void startupShouldNotFailOnIOExceptionOnlineListener() { // We do nothing, IOExceptionOnOnlineListener & JenkinsRule should cause the // boot failure if the issue is not fixed. START Assert.assertEquals(1, IOExceptionOnOnlineListener.onOnlineCount); END } ```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.

Target:
public void startupShouldNotFailOnIOExceptionOnlineListener() { // We do nothing, IOExceptionOnOnlineListener & JenkinsRule should cause the // boot failure if the issue is not fixed. assertEquals(1, IOExceptionOnOnlineListener.onOnlineCount); }
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(); START if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Cleaned events for missing classes"); END return formatEvents(toReport); } I think we tend to use brackets here.

Target:
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); }
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(); START assertNotNull(r.jenkins.getNode(oldNode.getNodeName())); END } ```suggestion assertNotNull(r.jenkins.getNode("foo")); ```

Target:
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("foo")); }
Source:
START protected Object readResolve() { END if(defaultExcludes == null) { defaultExcludes = true; } if(caseSensitive == null) { caseSensitive = true; } return this; } Better `private`.

Target:
private Object readResolve() { if(defaultExcludes == null) { defaultExcludes = true; } if(caseSensitive == null) { caseSensitive = true; } return this; }
Source:
public boolean isActivePeriod() { LocalDate now = LocalDate.now(); START if (getStart().isAfter(now)) { return false; } if (getEnd().isBefore(now)) { return false; } return true; END } I at least would find this easier to read as ```suggestion return now.isAfter(getStart()) && now.isBefore(getEnd()); ```

Target:
public boolean isActivePeriod() { LocalDate now = LocalDate.now(); 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; } START } catch (SignatureException ignore) { END // ignore } return false; } Should it be also IllegalStateException here?

Target:
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|IllegalArgumentException ignore) { // ignore } return false; }
Source:
public boolean isEnabled() { START return !(Jenkins.get()).getDisabledAdministrativeMonitors().contains(id); END } ```suggestion return !Jenkins.get().getDisabledAdministrativeMonitors().contains(id); ```

Target:
public boolean isEnabled() { 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); } START zos.closeEntry(); END } add it to `finally`? Otherwise ZIP stream may be corrupted if `cf.open()` or copy fail

Target:
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); } finally { zos.closeEntry(); } }
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(); START String relativePath; END // JENKINS-19947: traditional behavior is to prepend the directory name relativePath = dir.getName() + '/' + n; VirtualFile f = entry.getValue(); sendOneZipEntry(zos, f, relativePath); } } Why not join declaration and assignment?

Target:
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(); // JENKINS-19947: traditional behavior is to prepend the directory name String relativePath = dir.getName() + '/' + n; VirtualFile f = entry.getValue(); sendOneZipEntry(zos, f, relativePath); } }
Source:
public HttpResponse doClear() throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); START LOGGER.info("Called clearing..."); END clear(); return HttpResponses.redirectViaContextPath("/manage"); } ```suggestion ```

Target:
public HttpResponse doClear() throws IOException { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); clear(); return HttpResponses.redirectViaContextPath("/manage"); }
Source:
protected void printUsageSummary(PrintStream stderr) { START stderr.println(Messages.DisablePluginCommand_PrintUsageSummary()); END } For `printUsageSummary` if you could follow the same format as in `LoginCommand` and `LogoutCommand` for consistency.

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