auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private AuthenticationRequest getAuthenticationRequest(final String authority, final String resource, final String clientId, final boolean isExtendedLifetimeEnabled) { final AuthenticationRequest authRequest = new AuthenticationRequest(authority, resource, clientId, isExtendedLifetimeEnabled); return authRequest; }

Target:
aren't you getting a warning about collapsing these 2 lines? #Closed
Source:
public void testIsNullOrBlankEmpty() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException, ClassNotFoundException, NoSuchMethodException, InstantiationException { assertTrue("empty", StringExtensions.isNullOrBlank("")); assertTrue("empty", StringExtensions.isNullOrBlank(" ")); assertTrue("empty", StringExtensions.isNullOrBlank(" ")); }

Target:
For line 56 and lien 58, what is the difference between the two? It's all testing the trim, no need to have two. #Closed
Source:
public boolean isExpired() { if (mIsExtendedLifeTimeToken) { return TokenCacheItem.isTokenExpired(getExtendedExpiresOn()); } else { return TokenCacheItem.isTokenExpired(getExpiresOn()); } }

Target:
Sorry I don't quite understand the check. How do you know if the outgage mode is turned on in the AuthenticationResult class iteself? If it's not turned on, why we're checking extended expires on?
Source:
AuthenticationResult(String accessToken, String refreshToken, Date expires, boolean isBroad, UserInfo userInfo, String tenantId, String idToken, Date extendedExpires) { mCode = null; mAccessToken = accessToken; mRefreshToken = refreshToken; mExpiresOn = expires; mIsMultiResourceRefreshToken = isBroad; mStatus = AuthenticationStatus.Succeeded; mUserInfo = userInfo; mTenantId = tenantId; mIdToken = idToken; if (extendedExpires != null) { mExtendedExpiresOn = extendedExpires; } }

Target:
i don't see this if check adding any value. is there a reason why we prefer unassigned over null value?
Source:
final void setIsExtendedLifeTimeToken(final boolean isExtendedLifeTimeToken) { this.mIsExtendedLifeTimeToken = isExtendedLifeTimeToken; }

Target:
I like what she has currently. --- In reply to: [70552948](https://github.com/AzureAD/azure-activedirectory-library-for-android/pull/676#discussion_r70552948) [](ancestors = 70552948)
Source:
final void setExtendedExpiresOn(final Date extendedExpiresOn) { this.mExtendedExpiresOn = extendedExpiresOn; }

Target:
> this [](start = 8, length = 4) we should not do this. makes no sense unless the local variable and class variable have the same name.
Source:
final public boolean isExtendedLifeTimeToken() { return mIsExtendedLifeTimeToken; }

Target:
If you run checkstyle, it will complain you the access modifier order. You should do public final instead of final public.
Source:
final public Date getExtendedExpiresOn() { return this.mExtendedExpiresOn; }

Target:
> this [](start = 15, length = 4) remove all this. (its not needed)
Source:
final Date getExtendedExpiresOn() { return this.mExtendedExpiresOn; }

Target:
> this [](start = 15, length = 4) remove the this. #Closed
Source:
public ServerRespondingWithRetryableException(String msg, Throwable throwable) { super(ADALError.SERVER_RESPONDING_WITH_RETRYABLE_ERROR, msg, throwable); }

Target:
> ``` > [](start = 5, length = 4) > ``` trailing space
Source:
protected void setUp() throws Exception { super.setUp(); getContext().getCacheDir(); System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath()); getContext().getCacheDir(); System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath()); }

Target:
why are you setting the same property twice? #Closed
Source:
private boolean resolveIntent(Intent intent) { ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(intent, 0); return (resolveInfo != null); }

Target:
we don't need the bracket
Source:
private boolean isWorkplaceJoined() { @SuppressWarnings("unchecked") Class<IDeviceCertificate> certClass = (Class<IDeviceCertificate>)AuthenticationSettings.INSTANCE.getDeviceCertificateProxy(); return (certClass != null); }

Target:
remove the bracket.
Source:
private IDeviceCertificate getWPJAPIInstance(Class<IDeviceCertificate> certClazz) throws AuthenticationException { IDeviceCertificate deviceCertProxy; Constructor<?> constructor; try { constructor = certClazz.getDeclaredConstructor(); deviceCertProxy = (IDeviceCertificate)constructor.newInstance((Object[])null); } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new AuthenticationException(ADALError.DEVICE_CERTIFICATE_API_EXCEPTION, "WPJ Api constructor is not defined", e); } return deviceCertProxy; }

Target:
final
Source:
public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); List<TokenCacheItem> tokenItems = new ArrayList<>(); while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); // MRRT and FRT don't store resource in the token cache item. if (resource.equals(tokenCacheItem.getResource())) { tokenItems.add(tokenCacheItem); } } return tokenItems; }

Target:
final
Source:
public List<TokenCacheItem> getTokensForUser(String userId) { Iterator<TokenCacheItem> results = this.getAll(); List<TokenCacheItem> tokenItems = new ArrayList<>(); while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); if (tokenCacheItem.getUserInfo() != null && tokenCacheItem.getUserInfo().getUserId().equalsIgnoreCase(userId)) { tokenItems.add(tokenCacheItem); } } return tokenItems; }

Target:
final
Source:
private boolean isAboutToExpire(Date expires) { Date validity = getTokenValidityTime().getTime(); return (expires != null && expires.before(validity)); }

Target:
do we need the bracket?
Source:
private static HashMap<String, String> extractJsonObjects(final String jsonStr) throws JSONException { final JSONObject jsonObject = new JSONObject(jsonStr); final HashMap<String, String> responseItems = new HashMap<>(); final Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { final String key = (String) i.next(); responseItems.put(key, jsonObject.getString(key)); } return responseItems; }

Target:
Map
Source:
public AuthenticationResult getTokenForCode(String code) throws IOException, AuthenticationException { String requestMessage; if (mWebRequestHandler == null) { throw new IllegalArgumentException("webRequestHandler"); } // Token request message try { requestMessage = buildTokenRequestMessage(code); } catch (UnsupportedEncodingException encoding) { Logger.e(TAG, encoding.getMessage(), "", ADALError.ENCODING_IS_NOT_SUPPORTED, encoding); return null; } HashMap<String, String> headers = getRequestHeaders(); return postMessage(requestMessage, headers); }

Target:
final
Source:
private HashMap<String, String> getRequestHeaders() { HashMap<String, String> headers = new HashMap<>(); headers.put("Accept", "application/json"); return headers; }

Target:
Map
Source:
private AuthenticationResult parseJsonResponse(final String responseBody) throws JSONException, AuthenticationException { HashMap<String, String> responseItems = new HashMap<>(); extractJsonObjects(responseItems, responseBody); return processUIResponseParams(responseItems); }

Target:
Map
Source:
private boolean isUserMisMatch(final String user, final TokenCacheItem tokenCacheItem) { // If user if provided, it needs to match either displayId or userId. if (!StringExtensions.IsNullOrBlank(user)) { return !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getDisplayableId()) && !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getUserId()); } return false; }

Target:
tokenCacheItem.getUserInfo was checked for null earlier. you should add it back
Source:
private boolean isBrokerWithPRTSupport(final Intent intent) { if (intent == null) { throw new IllegalArgumentException("intent"); } // Only new broker with PRT support will send down the value and the version will be v2 final String brokerVersion = intent.getStringExtra(AuthenticationConstants.Broker.BROKER_VERSION); return !StringExtensions.IsNullOrBlank(brokerVersion) && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion); }

Target:
NIT: I wonder if we still need to check for brokerVersion being null or empty?
Source:
private boolean promptUser(PromptBehavior prompt) { return prompt == PromptBehavior.Always || prompt == PromptBehavior.REFRESH_SESSION // Force broker with PRT support to prompt user. || PromptBehavior.FORCE_PROMPT == prompt; }

Target:
nit: can you flip the comparison to prompt == ...
Source:
public boolean isConnectionAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager)mConnectionContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); return isConnected; }

Target:
you can collapse these 2 lines
Source:
private synchronized SecretKey getKey(final String keyVersion) throws GeneralSecurityException, IOException { switch (keyVersion) { case VERSION_USER_DEFINED : return getSecretKey(AuthenticationSettings.INSTANCE.getSecretKeyData()); case VERSION_ANDROID_KEY_STORE : if (Build.VERSION.SDK_INT >= 18) { // androidKeyStore can store app specific self signed cert. // Asymmetric cryptography is used to protect the session key // used for Encryption and HMac mKeyPair = readKeyPair(); mSecretKeyFromAndroidKeyStore = getUnwrappedSecretKey(); return mSecretKeyFromAndroidKeyStore; } default : throw new IOException("Unknown keyVersion."); } }

Target:
@weijjia I thought that we decided we didn't need this check. We should never have a case where there is a key in the key store on a device with an OS below 18.
Source:
private String encrypt(String value) { try { return getStorageHelper().encrypt(mContext, value); } catch (GeneralSecurityException | IOException e) { Logger.e(TAG, "Encryption failure", "", ADALError.ENCRYPTION_FAILED, e); } return null; }

Target:
nit: space
Source:
protected StorageHelper getStorageHelper() { synchronized (sLock) { if (sHelper == null) { Logger.v(TAG, "Started to initialize storage helper"); sHelper = new StorageHelper(mContext); Logger.v(TAG, "Finished to initialize storage helper"); } } return sHelper; }

Target:
nit: just make it syncronized?
Source:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { if (mBrokerProxy != null) { return mBrokerProxy.getBrokerUsers(); } return null; }

Target:
Does Java have ? operator?
Source:
public boolean canSwitchToBroker() { return verifyBroker() && verifyAuthenticator(mAcctManager) && !mContext.getPackageName().equalsIgnoreCase( AuthenticationSettings.INSTANCE.getBrokerPackageName()); }

Target:
change order
Source:
public void saveAccount(String accountName) { if (accountName == null || accountName.isEmpty()) return; SharedPreferences prefs = mContext.getSharedPreferences(KEY_SHARED_PREF_ACCOUNT_LIST, Activity.MODE_PRIVATE); String accountList = prefs.getString(KEY_APP_ACCOUNTS_FOR_TOKEN_REMOVAL, ""); accountList += KEY_ACCOUNT_LIST_DELIM + accountName; Editor prefsEditor = prefs.edit(); prefsEditor.putString(KEY_APP_ACCOUNTS_FOR_TOKEN_REMOVAL, accountList); // apply will do Async disk write operation. prefsEditor.apply(); }

Target:
saveAccount seems be adding each time.
Source:
private String getBrokerUrl(String loadUrl, String packageName, String signatureDigest) { if (!StringExtensions.IsNullOrBlank(packageName) && !StringExtensions.IsNullOrBlank(signatureDigest)) { try { return loadUrl + "&package_name=" + URLEncoder.encode(packageName, AuthenticationConstants.ENCODING_UTF8) + "&signature=" + signatureDigest; } catch (UnsupportedEncodingException e) { // This encoding issue will happen at the beginning of API call, // if it is not supported on this device. ADAL uses one encoding // type. Log.e(TAG, "Encoding", e); } } return loadUrl; }

Target:
Why does "signatureDigetst" not need to be encoded?
Source:
public int getUIDForPackage(final String packagename) { int callingUID = 0; try { ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packagename, 0); callingUID = info.uid; } catch (NameNotFoundException e) { Logger.e(TAG, "Package " + packagename + " is not found", "", ADALError.PACKAGE_NAME_NOT_FOUND, e); } return callingUID; }

Target:
if 'packagename' is null or empty will this cause a problem?
Source:
private Account getAccount(Account[] accounts, String username) { if (accounts != null) { for (Account account : accounts) { if (account.name.equals(username)) { return account; } } } return null; }

Target:
Is username case sensitive?
Source:
public static ParameterizedTypeName get( ClassName rawType, Iterable<? extends TypeName> typeArguments) { ArrayList<TypeName> typeArgumentsList = new ArrayList<>(); for (TypeName typeArgument : typeArguments) { typeArgumentsList.add(typeArgument); } return get(rawType, typeArgumentsList.toArray(new TypeName[0])); }

Target:
Why are you calling toArray instead of calling the constructor directly?
Source:
public static Builder builder(String packageName, TypeSpec typeSpec) { Objects.requireNonNull(packageName, "packageName == null"); Objects.requireNonNull(typeSpec, "typeSpec == null"); return new Builder(packageName, typeSpec); }

Target:
Static import?
Source:
public static Builder classBuilder(String name) { return new Builder(Kind.CLASS, Objects.requireNonNull(name, "name == null"), null); }

Target:
Static import
Source:
@Ignore @Test public void annotatedArrayType() { TypeName type = ArrayTypeName.of(ClassName.get(Object.class)).annotated(TYPE_USE_ANNOTATION); assertThat(type.toString()).isEqualTo("java.lang.Object @" + TUA + " []"); }

Target:
this one seems counterintuitive to me. The annotation is on the outermost type, but it’s printed here? (not saying it’s incorrect, but wow, this feature is weird)
Source:
@Test public void classNameFromClass() { assertThat(ClassName.get(Object.class).toString()) .isEqualTo("java.lang.Object"); assertThat(ClassName.get(OuterClass.InnerClass.class).toString()) .isEqualTo("com.squareup.javapoet.ClassNameTest.OuterClass.InnerClass"); try { assertThat((ClassName.get(new Object() {}.getClass())).toString()) .isEqualTo("com.squareup.javapoet.ClassNameTest$1"); } catch (IllegalArgumentException e) { fail(); } }

Target:
Just remove the try/catch. An exception will fail the test.
Source:
ParameterizedTypeName(ClassName rawType, List<TypeName> typeArguments, List<AnnotationSpec> annotations) { this( rawType, rawType.enclosingClassName() != null ? rawType.enclosingClassName() : rawType, rawType.enclosingClassName() != null ? rawType.simpleName() : null, typeArguments, annotations); }

Target:
This field definition seems strange. Why are these two interchangeable?
Source:
public Builder addInitializerBlock(CodeBlock block) { if (!(kind == Kind.CLASS || kind == Kind.ENUM)) { throw new UnsupportedOperationException(kind + " can't have initializer blocks"); } initializerBlock.add("{\n") .indent() .add(block) .unindent() .add("}\n"); return this; }

Target:
Mind simplifying this expression? ``` if (kind != Kind.CLASS && kind != Kind.ENUM) { ```
Source:
public JavaFile build() { Collections.sort(staticImports); return new JavaFile(this); }

Target:
ah, there it is.
Source:
private ExecutableElement findFirst(Collection<ExecutableElement> elements, String name) { for (ExecutableElement executableElement : elements) { if (executableElement.getSimpleName().toString().equals(name)) return executableElement; } throw new IllegalArgumentException(name + " not found in " + elements); }

Target:
braces
Source:
public Builder visitArray(List<? extends AnnotationValue> values, Entry entry) { Visitor visitor = new Visitor(builder); for (AnnotationValue value : values) { value.accept(visitor, new Entry(entry.name, value)); } return builder; }

Target:
Why not just pass `this`?
Source:
public Builder toBuilder() { Builder builder = new Builder(type, name); builder.javadoc.add(javadoc); builder.annotations.addAll(annotations); builder.modifiers.addAll(modifiers); builder.initializer = initializer; return builder; }

Target:
nit: check if this is empty, and if it is pass `null`? Otherwise you can't add an initializer on the copied instance. (I'm looking at the constructor and trying to figure out what the opposite assignment is!)
Source:
public Builder(String packageName, TypeSpec typeSpec) { this.packageName = checkNotNull(packageName, "packageName == null"); this.typeSpec = checkNotNull(typeSpec, "typeSpec == null"); }

Target:
`private`
Source:
void emit(CodeWriter codeWriter) { codeWriter.emitAnnotations(annotations); codeWriter.emitModifiers(modifiers); codeWriter.emit("$T $L", type, name); }

Target:
I like the builder approach because `.build()` can throw if `modifiers` has inappropriate modifiers like `private`.
Source:
public void setSupertype(TypeName typeName) { if (supertype.isPresent()) { throw new IllegalStateException("Supertype already set to " + writeToString(supertype.get())); } checkArgument(!anonymous, "Anonymous classes cannot declare supertypes"); supertype = Optional.of(typeName); }

Target:
`checkState`
Source:
public void setConstructorArguments(Snippet parameters) { this.arguments = Optional.of(parameters); }

Target:
nit: don't need `this`
Source:
private void emitModifiers(Set<Modifier> modifiers) throws IOException { // Use an EnumSet to ensure the proper ordering if (!(modifiers instanceof EnumSet)) { // This branch avoids an IllegalArgumentException within copyOf if(modifiers.isEmpty()) modifiers = EnumSet.noneOf(Modifier.class); else modifiers = EnumSet.copyOf(modifiers); } for (Modifier modifier : modifiers) { out.append(modifier.toString()).append(' '); } }

Target:
Actually shouldn't we just surround this with an `if (!modifiers.isEmpty())` for simplicity?
Source:
public void unloadView() { // TODO: Unload the view correctly. this.view.removeAll(); this.view.revalidate(); this.getParentController().getView().remove(this.view); this.getParentController().getView().revalidate(); this.getParentController().getView().repaint(); this.popoverView = null; this.welcomeView = null; this.timelineView = null; this.view = null; }

Target:
Das darf hier nicht sein, der controller räumt nur seine view auf und aendert nicht die vom parent!
Source:
public static String getMediaServerHostname(boolean full) throws IOException, InterruptedException { if (mediaServerHostname != null) return mediaServerHostname; String command = "hostname"; if (full) command = command + " -f"; Process p = Runtime.getRuntime().exec(command); BufferedReader input = new BufferedReader(new InputStreamReader( p.getInputStream())); p.waitFor(); mediaServerHostname = input.readLine(); return mediaServerHostname; }

Target:
1.if the first one will request full=true and the next will request full=false, then he will still get old one... 2.i think it's better to do it when loading the and not per request, since i rather not block the wowza thread for too long
Source:
public void dispose(IMediaStream stream){ if (amfInjectionListener != null){ amfInjectionListener.dispose(stream); } }

Target:
add amfInjectionListener=null
Source:
private void outputIOPerformanceInfo( HashMap<String,Object> hashMapInstance, IOPerformanceCounter ioPerformance) { HashMap<String,Object> IOPerformanceInfoHash = new HashMap<>(); IOPerformanceInfoHash.put("bitrate", ioPerformance.getMessagesInBytesRate() * 8 / 1000); hashMapInstance.put("IOPerformance", IOPerformanceInfoHash); }

Target:
new HashMap<String,Object>()
Source:
protected void onStreamReadyForPlayback(String entryId, final KalturaMediaServerIndex serverIndex) { logger.debug("onStreamReadyForPlayback [" + entryId + "]"); LiveEntryCache liveEntryCache = null; synchronized (entries) { if (entries.containsKey(entryId)) { liveEntryCache = entries.get(entryId); liveEntryCache.setEntryIsLive(); } else { logger.error("entry [" + entryId + "] not found in entries array"); } } }

Target:
u add this var here, but onlu use it inside. u can just do entries.get(entryId).setEntryIsLive(); in line 515 instead this line and instead of 515-516
Source:
public static PublicKey loadPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] decodedPublicKey = Base64Encoder.decode(publicKey); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER); ECParameterSpec parameterSpec; parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE); ECCurve curve = parameterSpec.getCurve(); ECPoint point = curve.decodePoint(decodedPublicKey); ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec); return keyFactory.generatePublic(pubSpec); }

Target:
Why splitting this to two rows?
Source:
private void startup() { executor = Executors.newSingleThreadExecutor(); consumer = new InstallationMetricsKafkaConsumer(metricsService); executor.execute(consumer); logger.debug("Consumer started.", InstallationMetricsKafkaConsumer.class); }

Target:
let's use JEE's managed executerservice here. lookup via JNDI. only create one when there is no managed one available
Source:
public void warning(String message){ AeroGearLogger.logger.warn(format(message)); }

Target:
just wondering, w/ slf4j do we still need the custom `format()` ? I hope/think that's done by the slf4j logging library
Source:
public void removeInstallation(Installation installation) { //Let manually remove the categories and update the installations before deleting //check AGPUSH-1295 for more information installation.setCategories(null); updateInstallation(installation); installationDao.delete(installation); }

Target:
Instead of manually updating the categories before deleting couldn't we change the cascade setting? https://github.com/aerogear/aerogear-unifiedpush-server/blob/159c119c6ef1564846b847e6b418335c2ce01dc0/model/jpa/src/main/resources/META-INF/orm.xml#L51 to ``` xml <cascade> <cascade-persist/> </cascade> ```
Source:
private Comparator<ITestNGMethod> newComparator(boolean needPrioritySort) { return needPrioritySort ? new TestMethodComparator() : null; }

Target:
static
Source:
private ITestNGMethod[] clone(ITestNGMethod[] sources) { return Arrays.stream(sources) .map(ITestNGMethod::clone) .toArray(ITestNGMethod[]::new); }

Target:
Could be static
Source:
default CustomAttribute[] getAttributes() { return null; }

Target:
Maybe instead of null in order to avoid NPE or check?
Source:
default IRetryAnalyzer getRetryAnalyzer(ITestResult result) { return null; }

Target:
`return getRetryAnalyzer()` otherwise you'll have to check null value from here and then call previous getRetryAnalyzer in the business code (where we expect to call the new method only)
Source:
private long time(ITestResult o1) { return o1.getEndMillis() - o1.getStartMillis(); }

Target:
static for the 3 methods
Source:
private List<XmlPackage> getAllPackages() { final List<XmlPackage> allPackages = Lists.newArrayList(); final List<XmlPackage> suitePackages = this.m_xmlTest.getSuite().getPackages(); if (suitePackages != null) allPackages.addAll(suitePackages); final List<XmlPackage> testPackages = this.m_xmlTest.getPackages(); if (testPackages != null) allPackages.addAll(testPackages); return allPackages; }

Target:
The `null` check is not needed, because `org.testng.xml.XmlSuite#getPackages` returns an empty list always.
Source:
public void methodInterceptorShouldBeRunOnceWhenCustomisedListenerImplementsITestListenerAndIMethodInterceptor() { TestNG tng = create(LSampleTest.class); InterceptorInvokeTwiceSimulateListener interceptor = new InterceptorInvokeTwiceSimulateListener(); tng.addListener((ITestNGListener) interceptor); tng.run(); Assert.assertEquals(interceptor.getCount(), 1); }

Target:
The ITestNGListener cast should be useless now. Could you confirm?
Source:
default void onConfigurationSuccess(ITestResult itr) { throw new UnsupportedOperationException("Method is not implemented"); }

Target:
Same here. I dont think we should be throwing exceptions.We should instead be having empty implementations.
Source:
default void onExecutionStart() { throw new UnsupportedOperationException("Method is not implemented"); }

Target:
Same here. I dont think we should be throwing exceptions.We should instead be having empty implementations.
Source:
public String[] getGroupFilters() { String[] result = new String[0]; IBeforeMethod before = m_annotationFinder.findAnnotation(getConstructorOrMethod(), IBeforeMethod.class); if (before != null) { result = before.getGroupFilters(); } return result; }

Target:
Again a detail and it's just a personal taste but I prefer to see the business code at the root level of the method ```java IBeforeMethod before = m_annotationFinder.findAnnotation(getConstructorOrMethod(), IBeforeMethod.class); if (before == null) { return new String[0]; } return before.getGroupFilters(); ```
Source:
public void testCreateDynamicGraphAllIndependent() { DynamicGraph<ITestNGMethod> graph = newGraph(IndependentTestClassSample.class); assertThat(graph.getFreeNodes()).hasSize(2); assertThat(graph.getEdges().isEmpty()); }

Target:
`assertThat(graph.getEdges()).isEmpty()` looks better
Source:
private String[] calculateGroupsTouseConsideringValuesAndGroupValues(Class<? extends ITestOrConfiguration> annotationClass, String[] groups) { ITestOrConfiguration annotation = getAnnotationFinder().findAnnotation(getConstructorOrMethod(), annotationClass); if (groups == null || groups.length == 0) { groups = null != annotation ? annotation.getGroups() : null; } return groups; }

Target:
Move this line into the if statement. We don't need to execute it if groups is null or empty
Source:
public void retryWithDataProvider() { TestNG testng = create(DataProviderRetryTest.class); TestListenerAdapter tla = new TestListenerAdapter(); DataProviderRerunListener listener = new DataProviderRerunListener(); testng.addListener((ITestNGListener) tla); testng.addListener(listener); testng.run(); assertThat(tla.getFailedTests()).size().isEqualTo(1); assertThat(tla.getSkippedTests()).size().isEqualTo(2); }

Target:
As mentioned above, this listener is not required.
Source:
private Map<String, String> createGroups(List<String> groups) { return GroupsHelper.createGroups(groups, m_metaGroups); }

Target:
If you reverse the parameters order, it will be more like `createListenerFactory`
Source:
public void testCreateDynamicGraphAllIndependent() { DynamicGraph<ITestNGMethod> graph = newGraph(IndependentTestClassSample.class); assertThat(graph.getFreeNodes()).hasSize(2); for (Map.Entry<ITestNGMethod, List<DynamicGraph.Edge<ITestNGMethod>>> edge : graph.getEdges().entrySet()) { assertThat(edge.getValue()).isEmpty(); } }

Target:
you can use `values()` instead of `entrySet`
Source:
public boolean nameMatchesAny(List<String> names) { for (String name : names) { if (getName().equals(name)) { return true; } } return false; }

Target:
Maybe just ```java return names.contains(getName()); ```
Source:
public static boolean hasFileScheme(String uri) { URI constructedURI = constructURI(uri); if (constructedURI == null) { constructedURI = new File(uri).toURI(); } String scheme = constructedURI.getScheme(); //A URI is regarded as having a file scheme if it either has its scheme as "file" //(or) if the scheme is null (which is true when uri's represent local file system path.) return scheme == null || "file".equalsIgnoreCase(scheme); }

Target:
Will always start by "file", so you can directly return true
Source:
public String getTmpString() { return this.tmp; }

Target:
Make it static
Source:
private static Throwable getConfigFailureException(ITestContext context) { Throwable t = null; for (IInvokedMethod method : context.getSuite().getAllInvokedMethods()) { ITestNGMethod m = method.getTestMethod(); if (m.isBeforeSuiteConfiguration() && (!method.getTestResult().isSuccess())) { return method.getTestResult().getThrowable(); } } return t; }

Target:
`t` is no more used. Just return null
Source:
public Object[][] getData() { return new Object[][]{ {TestClassWithConfigFailureSample.class, 6}, {TestClassWithConfigSkipSample.class, 4}, {TestClassWithConfigSkipAndFailureSample.class, 6} }; }

Target:
Why do you need to change the values? `TestClassWithConfigSkipAndFailureSample` was 3 => `HAS_SKIPPED + HAS_FAILURE` and is now 6 => `HAS_SKIPPED + HAS_FSP`. Is it expected?
Source:
public void exitWithNonzeroOnSkips() { TestNG tng = create(Issue217TestClassSample.class); tng.run(); assertEquals(tng.getStatus(), 5); }

Target:
5 means HAS_FAILURE and HAS_FSP, right?
Source:
private static boolean isExcluded(Collection<String> excludedGroups, String... groups) { boolean noGroups = (groups == null || groups.length == 0); if (!excludedGroups.isEmpty() && noGroups) { return true; } return isMemberOf(excludedGroups, groups); }

Target:
groups cannot be null.
Source:
public void testIfRetryIsInvokedBeforeListener() { TestNG tng = create(TestClassSample.class); tng.addListener((ITestNGListener)new MyListener()); tng.run(); Assertions.assertThat(TestClassSample.messages).containsExactly("afterInvocation", "retry","afterInvocation"); }

Target:
Typo: missing space after ","
Source:
private static boolean isIncluded(String[] groups, Collection<String> includedGroups, boolean noGroupsSpecified) { if (noGroupsSpecified) { return isMemberOf(groups, includedGroups); } if (includedGroups.size() == 0) { return true; } else { return isMemberOf(groups, includedGroups); } }

Target:
What if we have only `private static boolean isIncluded(String[] groups, Collection<String> includedGroups, Collection<String> excludedGroups)` instead of 2 methods?
Source:
static public void assertEquals(byte[] actual, byte[] expected) { assertEquals(actual, expected, ""); }

Target:
`public static` otherwise sonar will complain.
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); } return pruned.toArray(new Method[0]); }

Target:
Use `size` of `pruned` for the array.
Source:
public void testMainMethodExclusionForJunit() { XmlSuite xmlSuite = createXmlSuite("suite"); xmlSuite.setJunit(true); createXmlTest(xmlSuite, "test", JUnitTestClassSample.class); TestNG tng = create(); tng.setXmlSuites(Collections.singletonList(xmlSuite)); tng.run(); Assert.assertEquals(tng.getStatus(), 0); }

Target:
Use `create(xmlSuite)`
Source:
private static Map<String, String> getParameters(IMethodInstance im) { XmlTest xmlTest = im.getMethod().getXmlTest(); Map<String, String> params = xmlTest.getAllParameters(); params.putAll(im.getMethod().findMethodParameters(xmlTest)); return params; }

Target:
findMethodParameters is already doing it: https://github.com/cbeust/testng/blob/8d1c11bc267ea52157e20ebf6781d1ca9fe7ed1c/src/main/java/org/testng/internal/BaseTestMethod.java#L780
Source:
private String constructName(ITestNGMethod method) { return method.getConstructorOrMethod().getDeclaringClass().getSimpleName() + "." + method.getMethodName(); }

Target:
`static` is missing
Source:
private void setClassInvocationFailure(Class<?> clazz, Object instance) { synchronized(this){ Set<Object> instances = m_classInvocationResults.get( clazz ); if (instances == null) { instances = Sets.newHashSet(); m_classInvocationResults.put(clazz, instances); } instances.add(instance); } }

Target:
As I know, `synchronized(this)` is not a good practice, and in your case, you just want a synchronization on `m_classInvocationResults`.
Source:
public String toString() { return name().toLowerCase(); }

Target:
Maybe specify the names in the constructor (`SKIP("skip")`) so that someone modifying `toString()` by accident won't break the parsing.
Source:
private void initializeCommandLineSuitesParams() { if(null == m_cmdlineSuites) { return; } for (XmlSuite s : m_cmdlineSuites) { if(m_useThreadCount) { s.setThreadCount(m_threadCount); } s.setParallel(m_parallelMode); if(m_configFailurePolicy != null) { s.setConfigFailurePolicy(m_configFailurePolicy.toString()); } } }

Target:
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.
Source:
private static List<Method> getDefaultMethods(Class<?> clazz) { List<Method> result = null; 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; }

Target:
I prefer an empty list instead of `null`
Source:
public Object[] next() { if (m_count < m_objects.length) { return m_objects[m_count++]; } else { throw new NoSuchElementException(); } }

Target:
It's a personal taste, but I prefer: ``` java if (m_count >= m_objects.length) { throw new NoSuchElementException(); } return m_objects[m_count++]; ```
Source:
public static void setVerbose(int n) { m_verbose = n; }

Target:
As each <test> node may have its own verbose value, `m_verbose` has to be non-static.
Source:
public static 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(); }

Target:
Why is this needed?
Source:
public synchronized long getMaxSize() { return maxSize; }

Target:
For Max + Min Size, I think synchronized should be removed from the setter methods and just make the variables volatile instead.
Source:
public void rollback() throws IOException { if( writeTransactionId!=-1 ) { if (tmpFile != null) { getTempFile().delete(); 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; }

Target:
Shouldn't this temp file delete come after the close of the RandomAccessFile?
Source:
public void onDestroy() { StatisticsService.sessionPause(); StatisticsService.sessionStop(this); super.onDestroy(); }

Target:
sessionPause and sessionStop together?
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 { if (fis != null) { IOUtils.closeQuietly(fis); } } }

Target:
IOUtils already checks for null...
Source:
public String getDisplayName() { return "SetEnvBuildWrapper"; }

Target:
If you put a name, these wrappers will start appearing in the lists IIRC
Source:
private 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; }

Target:
Won't work correctly with: ``` FOO=something $FOOBAR ```
Source:
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 null; }

Target:
`} else`
Source:
private static String getUserId(Cause cause) { if (cause instanceof UserIdCause) { Cause.UserIdCause userIdCause = (UserIdCause) cause; return userIdCause.getUserId(); } return null; }

Target:
![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)
Source:
public void reset() { service = null; messageBusProxy = new MessageBusProxy(); requestDispatcherProxy = new RequestDispatcherProxy(); }

Target:
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.
Source:
public void testIterator() { final DependentInstanceTestBean testBean = getBeanManager().lookupBean(DependentInstanceTestBean.class).getInstance(); final Instance<DependentBeanA> injectedBean = testBean.getInjectDependentBeanA(); assertTrue(injectedBean.iterator().hasNext()); }

Target:
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.
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) { throw new InvalidReportException(String.format("'%s' is not a valid date.", dateString), e); } unpackFinalCounts(documentElement); totalRunTimeInMillis = getTotalRunTimeInMillisOrZeroIfNotPresent(documentElement); }

Target:
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?
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); } if (isTuningError && jobTryCount <= maxJobRetry) { throw new RuntimeException("Pig job failed."); } PigUtil.selfKill(); }

Target:
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.
Source:
private static String[] removeNullsFromArgArray(String[] argArray) { List<String> argList = new ArrayList(Arrays.asList(argArray)); argList.removeAll(Collections.singleton(null)); return argList.toArray(new String[0]); }

Target:
Why not "return argList.toArray(new String[argList.size()]);" so the String array with the appropriate length is preallocated?
Source:
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; }

Target:
seems we can shortcut when variables == null, no need to OR regex conditions.
Source:
public static void cancelHadoopTokens(HadoopSecurityManager hadoopSecurityManager, 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()); } }

Target:
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.
Source:
public ClientConfiguration getClientConfiguration() { return clientConfiguration; }

Target:
Can we return a copy here?
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"); return readResource(endpoint, CredentialsEndpointRetryPolicy.NO_RETRY, new HashMap<String, String>()); }

Target:
Should the third parameter be headers variable created above?
Source:
public static final Builder v1Builder(String name) { return new Builder(name, V1MarshallerSet.marshallers(), V1MarshallerSet.setMarshallers(), StandardUnmarshallerSet.unmarshallers(), StandardUnmarshallerSet.setUnmarshallers()); }

Target:
Is it possible to define the constants above via the builder? Also final is redundant for static methods.
Source:
public String getProxyHost() { if (proxyHost != null) { return proxyHost; } else { return getProxyHostProperty(); } }

Target:
Minor: Can you use the ternary operator here.
Source:
public int getProxyPort() { if (proxyPort > 0) { return proxyPort; } else { return getProxyPortProperty(); } }

Target:
proxyPort >= 0 ?
Source:
protected void processRequestPayload(SignableRequest<?> request, byte[] signature, byte[] signingKey, AWS4SignerRequestParams signerRequestParams) { if (useChunkEncoding(request) && this.isChunkedEncoding) { AwsChunkedEncodingInputStream chunkEncodededStream = new AwsChunkedEncodingInputStream( request.getContent(), signingKey, signerRequestParams.getFormattedSigningDateTime(), signerRequestParams.getScope(), BinaryUtils.toHex(signature), this); request.setContent(chunkEncodededStream); } }

Target:
Can you move the second part of the conditional into useChunkEncoding?
Source:
private static void speedUpDcoumentBuilderFactory() { String className = System.getProperty(DOCUMENT_BUILDER_FACTORY_PROP_NAME); 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); } } }

Target:
Inline
Source:
public AWSCredentials getCredentials() { if (profilesConfigFile == null) { synchronized (this) { if (profilesConfigFile == null) { profilesConfigFile = new ProfilesConfigFile(); } } } if (ProfilesConfigFile.DEFAULT_PROFILE_NAME.equals(profileName)) { // 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); }

Target:
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.
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') { value += (int) Math.pow(2.0, (double) i); } } return value; }

Target:
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 :)
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)); } catch (IOException e) { error(e); } catch (InterruptedException e) { error(e); } }

Target:
```suggestion } catch (IOException | InterruptedException e) { ```
Source:
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; } }

Target:
```suggestion if (jenkins == null || jenkins.getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED) < 0) ```
Source:
public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors){ this.disabledAdministrativeMonitors = disabledAdministrativeMonitors; }

Target:
Probably should be cloned here instead of taking a reference to an external object
Source:
public Set<String> getDisabledAdministrativeMonitors(){ return disabledAdministrativeMonitors; }

Target:
So what's buggy about the `CopyOnWriteArraySet`?
Source:
public Set<String> getDisabledAdministrativeMonitors(){ synchronized (disabledAdministrativeMonitors) { return disabledAdministrativeMonitors; } }

Target:
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.
Source:
public synchronized void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) { synchronized (this.disabledAdministrativeMonitors) { this.disabledAdministrativeMonitors.clear(); this.disabledAdministrativeMonitors.addAll(disabledAdministrativeMonitors); } }

Target:
Is it really needed to have `synchronized` method as well as inside the method?
Source:
private Object readResolve() { if (loggers == null) { loggers = new ArrayList<>(); } if (!targets.isEmpty()) { loggers.addAll(targets.getView()); } if (!loggers.isEmpty()) { targets.addAll(loggers); } return this; }

Target:
the same is true for targets, this could also be null and would cause a null point exception. ```suggestion if (targets != null && !targets.isEmpty()) { ```
Source:
public void doRss( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException { Jenkins.get().checkPermission(Jenkins.SYSTEM_READ); LogRecorderManager.doRss(req,rsp,getLogRecords()); }

Target:
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 ?
Source:
public void setSummary(@CheckForNull String summary) throws IOException { checkPermission(UPDATE); this.description = description; save(); }

Target:
Bug, you're setting description instead of summary.
Source:
public Api getApi() { if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) return null; return new Api(this); }

Target:
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.
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"); } Locale.setDefault(loc); }

Target:
Why here? `after()` will run anyways right?
Source:
public int compareTo(HealthReport o) { return (Integer.compare(this.score, o.score)); }

Target:
```suggestion return Integer.compare(this.score, o.score); ```