auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START public boolean isExpired() { END if (mIsExtendedLifeTimeToken) { return TokenCacheItem.isTokenExpired(getExtendedExpiresOn()); } else { return TokenCacheItem.isTokenExpired(getExpiresOn()); } } 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?

Target:
public boolean isExpired() { if (mIsExtendedLifeTimeToken) { return TokenCacheItem.isTokenExpired(getExtendedExpiresOn()); } return TokenCacheItem.isTokenExpired(getExpiresOn()); }
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; START if (extendedExpires != null) { END mExtendedExpiresOn = extendedExpires; } } i don't see this if check adding any value. is there a reason why we prefer unassigned over null value?

Target:
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; mExtendedExpiresOn = extendedExpires; }
Source:
final void setIsExtendedLifeTimeToken(final boolean isExtendedLifeTimeToken) { START this.mIsExtendedLifeTimeToken = isExtendedLifeTimeToken; END } 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)

Target:
final void setIsExtendedLifeTimeToken(final boolean isExtendedLifeTimeToken) { mIsExtendedLifeTimeToken = isExtendedLifeTimeToken; }
Source:
final void setExtendedExpiresOn(final Date extendedExpiresOn) { START this.mExtendedExpiresOn = extendedExpiresOn; END } > this [](start = 8, length = 4) we should not do this. makes no sense unless the local variable and class variable have the same name.

Target:
final void setExtendedExpiresOn(final Date extendedExpiresOn) { mExtendedExpiresOn = extendedExpiresOn; }
Source:
START final public boolean isExtendedLifeTimeToken() { END return mIsExtendedLifeTimeToken; } If you run checkstyle, it will complain you the access modifier order. You should do public final instead of final public.

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

Target:
final Date getExtendedExpiresOn() { return mExtendedExpiresOn; }
Source:
final Date getExtendedExpiresOn() { START return this.mExtendedExpiresOn; END } > this [](start = 15, length = 4) remove the this. #Closed

Target:
final Date getExtendedExpiresOn() { return mExtendedExpiresOn; }
Source:
public ServerRespondingWithRetryableException(String msg, Throwable throwable) { super(ADALError.SERVER_RESPONDING_WITH_RETRYABLE_ERROR, msg, throwable); START } END > ``` > [](start = 5, length = 4) > ``` trailing space

Target:
public ServerRespondingWithRetryableException(String msg, Throwable throwable) { super(null, msg, throwable); }
Source:
protected void setUp() throws Exception { super.setUp(); getContext().getCacheDir(); System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath()); getContext().getCacheDir(); START System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath()); END } why are you setting the same property twice? #Closed

Target:
protected void setUp() throws Exception { super.setUp(); getContext().getCacheDir(); System.setProperty("dexmaker.dexcache", getContext().getCacheDir().getPath()); }
Source:
private boolean resolveIntent(Intent intent) { ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(intent, 0); START return (resolveInfo != null); END } we don't need the bracket

Target:
private boolean resolveIntent(Intent intent) { final ResolveInfo resolveInfo = mContext.getPackageManager().resolveActivity(intent, 0); return resolveInfo != null; }
Source:
private boolean isWorkplaceJoined() { @SuppressWarnings("unchecked") Class<IDeviceCertificate> certClass = (Class<IDeviceCertificate>)AuthenticationSettings.INSTANCE.getDeviceCertificateProxy(); START return (certClass != null); END } remove the bracket.

Target:
private boolean isWorkplaceJoined() { @SuppressWarnings("unchecked") Class<IDeviceCertificate> certClass = (Class<IDeviceCertificate>)AuthenticationSettings.INSTANCE.getDeviceCertificateProxy(); return certClass != null; }
Source:
private IDeviceCertificate getWPJAPIInstance(Class<IDeviceCertificate> certClazz) throws AuthenticationException { START IDeviceCertificate deviceCertProxy; END 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; } final

Target:
private IDeviceCertificate getWPJAPIInstance(Class<IDeviceCertificate> certClazz) throws AuthenticationException { final IDeviceCertificate deviceCertProxy; final 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; }
Source:
public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); START List<TokenCacheItem> tokenItems = new ArrayList<>(); END 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; } final

Target:
public List<TokenCacheItem> getTokensForResource(String resource) { Iterator<TokenCacheItem> results = this.getAll(); final 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; }
Source:
public List<TokenCacheItem> getTokensForUser(String userId) { Iterator<TokenCacheItem> results = this.getAll(); START List<TokenCacheItem> tokenItems = new ArrayList<>(); END while (results.hasNext()) { final TokenCacheItem tokenCacheItem = results.next(); if (tokenCacheItem.getUserInfo() != null && tokenCacheItem.getUserInfo().getUserId().equalsIgnoreCase(userId)) { tokenItems.add(tokenCacheItem); } } return tokenItems; } final

Target:
public List<TokenCacheItem> getTokensForUser(String userId) { Iterator<TokenCacheItem> results = this.getAll(); final 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; }
Source:
private boolean isAboutToExpire(Date expires) { Date validity = getTokenValidityTime().getTime(); START return (expires != null && expires.before(validity)); END } do we need the bracket?

Target:
private boolean isAboutToExpire(Date expires) { Date validity = getTokenValidityTime().getTime(); return expires != null && expires.before(validity); }
Source:
private static HashMap<String, String> extractJsonObjects(final String jsonStr) throws JSONException { final JSONObject jsonObject = new JSONObject(jsonStr); START final HashMap<String, String> responseItems = new HashMap<>(); END final Iterator<?> i = jsonObject.keys(); while (i.hasNext()) { final String key = (String) i.next(); responseItems.put(key, jsonObject.getString(key)); } return responseItems; } Map

Target:
private static Map<String, String> extractJsonObjects(final String jsonStr) throws JSONException { final JSONObject jsonObject = new JSONObject(jsonStr); final Map<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; }
Source:
public AuthenticationResult getTokenForCode(String code) throws IOException, AuthenticationException { START String requestMessage; END 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); } final

Target:
public AuthenticationResult getTokenForCode(String code) throws IOException, AuthenticationException { final 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; } final Map<String, String> headers = getRequestHeaders(); return postMessage(requestMessage, headers); }
Source:
private HashMap<String, String> getRequestHeaders() { START HashMap<String, String> headers = new HashMap<>(); END headers.put("Accept", "application/json"); return headers; } Map

Target:
private Map<String, String> getRequestHeaders() { final Map<String, String> headers = new HashMap<>(); headers.put("Accept", "application/json"); return headers; }
Source:
private AuthenticationResult parseJsonResponse(final String responseBody) throws JSONException, AuthenticationException { START HashMap<String, String> responseItems = new HashMap<>(); END extractJsonObjects(responseItems, responseBody); return processUIResponseParams(responseItems); } Map

Target:
private AuthenticationResult parseJsonResponse(final String responseBody) throws JSONException, AuthenticationException { final Map<String, String> responseItems = new HashMap<>(); extractJsonObjects(responseItems, responseBody); return processUIResponseParams(responseItems); }
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)) { START return !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getDisplayableId()) END && !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getUserId()); } return false; } tokenCacheItem.getUserInfo was checked for null earlier. you should add it back

Target:
private boolean isUserMisMatch(final String user, final TokenCacheItem tokenCacheItem) { // If user is not passed in the request or userInfo does not exist in the token cache item, // it's a match case. We do wildcard find, return whatever match with cache key. if (StringExtensions.IsNullOrBlank(user) || tokenCacheItem.getUserInfo() == null) { return false; } // If user if provided, it needs to match either displayId or userId. return !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getDisplayableId()) && !user.equalsIgnoreCase(tokenCacheItem.getUserInfo().getUserId()); }
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) START && AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion); END } NIT: I wonder if we still need to check for brokerVersion being null or empty?

Target:
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 AuthenticationConstants.Broker.BROKER_PROTOCOL_VERSION.equalsIgnoreCase(brokerVersion); }
Source:
private boolean promptUser(PromptBehavior prompt) { return prompt == PromptBehavior.Always || prompt == PromptBehavior.REFRESH_SESSION // Force broker with PRT support to prompt user. START || PromptBehavior.FORCE_PROMPT == prompt; END } nit: can you flip the comparison to prompt == ...

Target:
private boolean promptUser(PromptBehavior prompt) { return prompt == PromptBehavior.Always || prompt == PromptBehavior.REFRESH_SESSION || prompt == PromptBehavior.FORCE_PROMPT; }
Source:
public boolean isConnectionAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager)mConnectionContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting(); START return isConnected; END } you can collapse these 2 lines

Target:
public boolean isConnectionAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager)mConnectionContext .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); }
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 : START if (Build.VERSION.SDK_INT >= 18) { END // 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."); } } @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.

Target:
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 : // 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."); } }
Source:
START private String encrypt(String value) { END try { return getStorageHelper().encrypt(mContext, value); } catch (GeneralSecurityException | IOException e) { Logger.e(TAG, "Encryption failure", "", ADALError.ENCRYPTION_FAILED, e); } return null; } nit: space

Target:
private String encrypt(String value) { try { return getStorageHelper().encrypt(value); } catch (GeneralSecurityException | IOException e) { Logger.e(TAG, "Encryption failure", "", ADALError.ENCRYPTION_FAILED, e); } return null; }
Source:
START protected StorageHelper getStorageHelper() { END 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; } nit: just make it syncronized?

Target:
protected synchronized StorageHelper getStorageHelper() { 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; }
Source:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { if (mBrokerProxy != null) { START return mBrokerProxy.getBrokerUsers(); END } return null; } Does Java have ? operator?

Target:
public UserInfo[] getBrokerUsers() throws OperationCanceledException, AuthenticatorException, IOException { return mBrokerProxy != null ? mBrokerProxy.getBrokerUsers() : null; }
Source:
public boolean canSwitchToBroker() { return verifyBroker() START && verifyAuthenticator(mAcctManager) END && !mContext.getPackageName().equalsIgnoreCase( AuthenticationSettings.INSTANCE.getBrokerPackageName()); } change order

Target:
public boolean canSwitchToBroker() { return !mContext.getPackageName().equalsIgnoreCase( AuthenticationSettings.INSTANCE.getBrokerPackageName()) && verifyBroker() && verifyAuthenticator(mAcctManager); }
Source:
START public void saveAccount(String accountName) { END 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(); } saveAccount seems be adding each time.

Target:
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, ""); if (!accountList.contains(KEY_ACCOUNT_LIST_DELIM + accountName)) { 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(); } }
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) START + "&signature=" + signatureDigest; END } 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; } Why does "signatureDigetst" not need to be encoded?

Target:
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=" + URLEncoder.encode(signatureDigest, AuthenticationConstants.ENCODING_UTF8); } 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; }
Source:
START public int getUIDForPackage(final String packagename) { END 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; } if 'packagename' is null or empty will this cause a problem?

Target:
public int getUIDForPackage(final String packagename) { int callingUID = 0; try { ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(packagename, 0); if (info != null) { callingUID = info.uid; } } catch (NameNotFoundException e) { Logger.e(TAG, "Package " + packagename + " is not found", "", ADALError.PACKAGE_NAME_NOT_FOUND, e); } return callingUID; }
Source:
private Account getAccount(Account[] accounts, String username) { if (accounts != null) { for (Account account : accounts) { START if (account.name.equals(username)) { END return account; } } } return null; } Is username case sensitive?

Target:
private Account getAccount(Account[] accounts, String username) { if (accounts != null && username != null) { for (Account account : accounts) { if (account.name.equalsIgnoreCase(username)) { return account; } } } return null; }
Source:
public static ParameterizedTypeName get( ClassName rawType, Iterable<? extends TypeName> typeArguments) { ArrayList<TypeName> typeArgumentsList = new ArrayList<>(); for (TypeName typeArgument : typeArguments) { typeArgumentsList.add(typeArgument); } START return get(rawType, typeArgumentsList.toArray(new TypeName[0])); END } Why are you calling toArray instead of calling the constructor directly?

Target:
public static ParameterizedTypeName get( ClassName rawType, Iterable<? extends TypeName> typeArguments) { ArrayList<TypeName> typeArgumentsList = new ArrayList<>(); for (TypeName typeArgument : typeArguments) { typeArgumentsList.add(typeArgument); } return new ParameterizedTypeName(null, rawType, typeArgumentsList); }
Source:
public static Builder builder(String packageName, TypeSpec typeSpec) { Objects.requireNonNull(packageName, "packageName == null"); START Objects.requireNonNull(typeSpec, "typeSpec == null"); END return new Builder(packageName, typeSpec); } Static import?

Target:
public static Builder builder(String packageName, TypeSpec typeSpec) { requireNonNull(packageName, "packageName == null"); requireNonNull(typeSpec, "typeSpec == null"); return new Builder(packageName, typeSpec); }
Source:
public static Builder classBuilder(String name) { START return new Builder(Kind.CLASS, Objects.requireNonNull(name, "name == null"), null); END } Static import

Target:
public static Builder classBuilder(String name) { return new Builder(Kind.CLASS, requireNonNull(name, "name == null"), null); }
Source:
@Ignore @Test public void annotatedArrayType() { TypeName type = ArrayTypeName.of(ClassName.get(Object.class)).annotated(TYPE_USE_ANNOTATION); START assertThat(type.toString()).isEqualTo("java.lang.Object @" + TUA + " []"); END } 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)

Target:
@Test public void annotatedArrayType() { TypeName type = ArrayTypeName.of(ClassName.get(Object.class)).annotated(TYPE_USE_ANNOTATION); assertThat(type.toString()).isEqualTo("java.lang.Object @" + TUA + " []"); }
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) { START fail(); END } } Just remove the try/catch. An exception will fail the test.

Target:
@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"); assertThat((ClassName.get(new Object() {}.getClass())).toString()) .isEqualTo("com.squareup.javapoet.ClassNameTest$1"); }
Source:
ParameterizedTypeName(ClassName rawType, List<TypeName> typeArguments, List<AnnotationSpec> annotations) { this( rawType, START rawType.enclosingClassName() != null ? rawType.enclosingClassName() : rawType, END rawType.enclosingClassName() != null ? rawType.simpleName() : null, typeArguments, annotations); } This field definition seems strange. Why are these two interchangeable?

Target:
ParameterizedTypeName(ClassName rawType, List<TypeName> typeArguments, List<AnnotationSpec> annotations) { this(rawType, null, typeArguments, annotations); }
Source:
public Builder addInitializerBlock(CodeBlock block) { START if (!(kind == Kind.CLASS || kind == Kind.ENUM)) { END throw new UnsupportedOperationException(kind + " can't have initializer blocks"); } initializerBlock.add("{\n") .indent() .add(block) .unindent() .add("}\n"); return this; } Mind simplifying this expression? ``` if (kind != Kind.CLASS && kind != Kind.ENUM) { ```

Target:
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; }
Source:
public JavaFile build() { START Collections.sort(staticImports); END return new JavaFile(this); } ah, there it is.

Target:
public JavaFile build() { return new JavaFile(this); }
Source:
private ExecutableElement findFirst(Collection<ExecutableElement> elements, String name) { for (ExecutableElement executableElement : elements) { START if (executableElement.getSimpleName().toString().equals(name)) END return executableElement; } throw new IllegalArgumentException(name + " not found in " + elements); } braces

Target:
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); }
Source:
public Builder visitArray(List<? extends AnnotationValue> values, Entry entry) { START Visitor visitor = new Visitor(builder); END for (AnnotationValue value : values) { value.accept(visitor, new Entry(entry.name, value)); } return builder; } Why not just pass `this`?

Target:
public Builder visitArray(List<? extends AnnotationValue> values, Entry entry) { for (AnnotationValue value : values) { value.accept(this, new Entry(entry.name, value)); } return builder; }
Source:
public Builder toBuilder() { Builder builder = new Builder(type, name); builder.javadoc.add(javadoc); builder.annotations.addAll(annotations); builder.modifiers.addAll(modifiers); START builder.initializer = initializer; END return builder; } 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!)

Target:
public Builder toBuilder() { Builder builder = new Builder(type, name); builder.javadoc.add(javadoc); builder.annotations.addAll(annotations); builder.modifiers.addAll(modifiers); builder.initializer = initializer.isEmpty() ? null : initializer; return builder; }
Source:
START public Builder(String packageName, TypeSpec typeSpec) { END this.packageName = checkNotNull(packageName, "packageName == null"); this.typeSpec = checkNotNull(typeSpec, "typeSpec == null"); } `private`

Target:
private Builder(String packageName, TypeSpec typeSpec) { this.packageName = checkNotNull(packageName, "packageName == null"); this.typeSpec = checkNotNull(typeSpec, "typeSpec == null"); }
Source:
void emit(CodeWriter codeWriter) { codeWriter.emitAnnotations(annotations); START codeWriter.emitModifiers(modifiers); END codeWriter.emit("$T $L", type, name); } I like the builder approach because `.build()` can throw if `modifiers` has inappropriate modifiers like `private`.

Target:
void emit(CodeWriter codeWriter) { codeWriter.emitAnnotations(annotations, true); codeWriter.emitModifiers(modifiers); codeWriter.emit("$T $L", type, name); }
Source:
public void setSupertype(TypeName typeName) { if (supertype.isPresent()) { throw new IllegalStateException("Supertype already set to " + writeToString(supertype.get())); } START checkArgument(!anonymous, "Anonymous classes cannot declare supertypes"); END supertype = Optional.of(typeName); } `checkState`

Target:
public void setSupertype(TypeName typeName) { if (supertype.isPresent()) { throw new IllegalStateException("Supertype already set to " + writeToString(supertype.get())); } supertype = Optional.of(typeName); }
Source:
public void setConstructorArguments(Snippet parameters) { START this.arguments = Optional.of(parameters); END } nit: don't need `this`

Target:
public void setConstructorArguments(Snippet parameters) { arguments = Optional.of(parameters); }
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); } START for (Modifier modifier : modifiers) { END out.append(modifier.toString()).append(' '); } } Actually shouldn't we just surround this with an `if (!modifiers.isEmpty())` for simplicity?

Target:
private void emitModifiers(Set<Modifier> modifiers) throws IOException { // Preserve "natural" ordering of modifiers if (!modifiers.isEmpty()) { modifiers = EnumSet.copyOf(modifiers); } for (Modifier modifier : modifiers) { out.append(modifier.toString()).append(' '); } }
Source:
public void unloadView() { // TODO: Unload the view correctly. this.view.removeAll(); this.view.revalidate(); START this.getParentController().getView().remove(this.view); END this.getParentController().getView().revalidate(); this.getParentController().getView().repaint(); this.popoverView = null; this.welcomeView = null; this.timelineView = null; this.view = null; } Das darf hier nicht sein, der controller räumt nur seine view auf und aendert nicht die vom parent!

Target:
public void unloadView() { this.view.removeAll(); this.view.revalidate(); this.popoverView = null; this.welcomeView = null; this.timelineView = null; this.view = null; }
Source:
public static String getMediaServerHostname(boolean full) throws IOException, InterruptedException { START if (mediaServerHostname != null) END 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; } 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

Target:
public static String getMediaServerHostname(boolean full) throws IOException, InterruptedException { String command = "hostname"; if (full) command = command + " -f"; Process p = Runtime.getRuntime().exec(command); BufferedReader input = new BufferedReader(new InputStreamReader( p.getInputStream())); p.waitFor(); return input.readLine(); }
Source:
public void dispose(IMediaStream stream){ if (amfInjectionListener != null){ START amfInjectionListener.dispose(stream); END } } add amfInjectionListener=null

Target:
public void dispose(IMediaStream stream){ if (amfInjectionListener != null){ amfInjectionListener.dispose(stream); amfInjectionListener = null; } }
Source:
private void outputIOPerformanceInfo( HashMap<String,Object> hashMapInstance, IOPerformanceCounter ioPerformance) { START HashMap<String,Object> IOPerformanceInfoHash = new HashMap<>(); END IOPerformanceInfoHash.put("bitrate", ioPerformance.getMessagesInBytesRate() * 8 / 1000); hashMapInstance.put("IOPerformance", IOPerformanceInfoHash); } new HashMap<String,Object>()

Target:
private void outputIOPerformanceInfo( HashMap<String,Object> hashMapInstance, IOPerformanceCounter ioPerformance) { HashMap<String,Object> IOPerformanceInfoHash = new HashMap<String,Object>(); IOPerformanceInfoHash.put("bitrate", ioPerformance.getMessagesInBytesRate() * 8 / 1000); hashMapInstance.put("IOPerformance", IOPerformanceInfoHash); }
Source:
protected void onStreamReadyForPlayback(String entryId, final KalturaMediaServerIndex serverIndex) { logger.debug("onStreamReadyForPlayback [" + entryId + "]"); START LiveEntryCache liveEntryCache = null; END synchronized (entries) { if (entries.containsKey(entryId)) { liveEntryCache = entries.get(entryId); liveEntryCache.setEntryIsLive(); } else { logger.error("entry [" + entryId + "] not found in entries array"); } } } 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

Target:
protected void onStreamReadyForPlayback(String entryId, final KalturaMediaServerIndex serverIndex) { logger.debug("onStreamReadyForPlayback [" + entryId + "]"); synchronized (entries) { if (entries.containsKey(entryId)) { entries.get(entryId).setEntryIsLive(); } else { logger.error("entry [" + entryId + "] not found in entries array"); } } }
Source:
public static PublicKey loadPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] decodedPublicKey = Base64Encoder.decode(publicKey); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER); ECParameterSpec parameterSpec; START parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE); END ECCurve curve = parameterSpec.getCurve(); ECPoint point = curve.decodePoint(decodedPublicKey); ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec); return keyFactory.generatePublic(pubSpec); } Why splitting this to two rows?

Target:
public static PublicKey loadPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException { byte[] decodedPublicKey = Base64Encoder.decode(publicKey); KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER); ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE); ECCurve curve = parameterSpec.getCurve(); ECPoint point = curve.decodePoint(decodedPublicKey); ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, parameterSpec); return keyFactory.generatePublic(pubSpec); }
Source:
private void startup() { START executor = Executors.newSingleThreadExecutor(); END consumer = new InstallationMetricsKafkaConsumer(metricsService); executor.execute(consumer); logger.debug("Consumer started.", InstallationMetricsKafkaConsumer.class); } let's use JEE's managed executerservice here. lookup via JNDI. only create one when there is no managed one available

Target:
private void startup() { consumer = new InstallationMetricsKafkaConsumer(metricsService); executor.execute(consumer); logger.debug("Consumer started.", InstallationMetricsKafkaConsumer.class); }
Source:
public void warning(String message){ START AeroGearLogger.logger.warn(format(message)); END } just wondering, w/ slf4j do we still need the custom `format()` ? I hope/think that's done by the slf4j logging library

Target:
public void warning(String message){ AeroGearLogger.logger.warn(message); }
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); START updateInstallation(installation); END installationDao.delete(installation); } 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> ```

Target:
public void removeInstallation(Installation installation) { installationDao.delete(installation); }
Source:
START private Comparator<ITestNGMethod> newComparator(boolean needPrioritySort) { END return needPrioritySort ? new TestMethodComparator() : null; } static

Target:
private static Comparator<ITestNGMethod> newComparator(boolean needPrioritySort) { return needPrioritySort ? new TestMethodComparator() : null; }
Source:
START private ITestNGMethod[] clone(ITestNGMethod[] sources) { END return Arrays.stream(sources) .map(ITestNGMethod::clone) .toArray(ITestNGMethod[]::new); } Could be static

Target:
private static ITestNGMethod[] clone(ITestNGMethod[] sources) { return Arrays.stream(sources) .map(ITestNGMethod::clone) .toArray(ITestNGMethod[]::new); }
Source:
default CustomAttribute[] getAttributes() { START return null; END } Maybe instead of null in order to avoid NPE or check?

Target:
default CustomAttribute[] getAttributes() { return new CustomAttribute[]{}; }
Source:
default IRetryAnalyzer getRetryAnalyzer(ITestResult result) { START return null; END } `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)

Target:
default IRetryAnalyzer getRetryAnalyzer(ITestResult result) { return getRetryAnalyzer(); }
Source:
START private long time(ITestResult o1) { END return o1.getEndMillis() - o1.getStartMillis(); } static for the 3 methods

Target:
private static long time(ITestResult o1) { return o1.getEndMillis() - o1.getStartMillis(); }
Source:
private List<XmlPackage> getAllPackages() { final List<XmlPackage> allPackages = Lists.newArrayList(); final List<XmlPackage> suitePackages = this.m_xmlTest.getSuite().getPackages(); START if (suitePackages != null) END allPackages.addAll(suitePackages); final List<XmlPackage> testPackages = this.m_xmlTest.getPackages(); if (testPackages != null) allPackages.addAll(testPackages); return allPackages; } The `null` check is not needed, because `org.testng.xml.XmlSuite#getPackages` returns an empty list always.

Target:
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; }
Source:
public void methodInterceptorShouldBeRunOnceWhenCustomisedListenerImplementsITestListenerAndIMethodInterceptor() { TestNG tng = create(LSampleTest.class); InterceptorInvokeTwiceSimulateListener interceptor = new InterceptorInvokeTwiceSimulateListener(); START tng.addListener((ITestNGListener) interceptor); END tng.run(); Assert.assertEquals(interceptor.getCount(), 1); } The ITestNGListener cast should be useless now. Could you confirm?

Target:
public void methodInterceptorShouldBeRunOnceWhenCustomisedListenerImplementsITestListenerAndIMethodInterceptor() { TestNG tng = create(LSampleTest.class); InterceptorInvokeTwiceSimulateListener interceptor = new InterceptorInvokeTwiceSimulateListener(); tng.addListener(interceptor); tng.run(); Assert.assertEquals(interceptor.getCount(), 1); }
Source:
default void onConfigurationSuccess(ITestResult itr) { START throw new UnsupportedOperationException("Method is not implemented"); END } Same here. I dont think we should be throwing exceptions.We should instead be having empty implementations.

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

Target:
default void onExecutionStart() { // not implemented }
Source:
START public String[] getGroupFilters() { END String[] result = new String[0]; IBeforeMethod before = m_annotationFinder.findAnnotation(getConstructorOrMethod(), IBeforeMethod.class); if (before != null) { result = before.getGroupFilters(); } return result; } 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(); ```

Target:
public String[] getGroupFilters() { 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); START assertThat(graph.getEdges().isEmpty()); END } `assertThat(graph.getEdges()).isEmpty()` looks better

Target:
public void testCreateDynamicGraphAllIndependent() { DynamicGraph<ITestNGMethod> graph = newGraph(IndependentTestClassSample.class); assertThat(graph.getFreeNodes()).hasSize(2); assertThat(graph.getEdges()).isEmpty(); }
Source:
private String[] calculateGroupsTouseConsideringValuesAndGroupValues(Class<? extends ITestOrConfiguration> annotationClass, String[] groups) { START ITestOrConfiguration annotation = getAnnotationFinder().findAnnotation(getConstructorOrMethod(), annotationClass); END if (groups == null || groups.length == 0) { groups = null != annotation ? annotation.getGroups() : null; } return groups; } Move this line into the if statement. We don't need to execute it if groups is null or empty

Target:
private String[] calculateGroupsTouseConsideringValuesAndGroupValues(Class<? extends ITestOrConfiguration> annotationClass, String[] groups) { if (groups == null || groups.length == 0) { ITestOrConfiguration annotation = getAnnotationFinder().findAnnotation(getConstructorOrMethod(), annotationClass); groups = null != annotation ? annotation.getGroups() : null; } return groups; }
Source:
public void retryWithDataProvider() { TestNG testng = create(DataProviderRetryTest.class); TestListenerAdapter tla = new TestListenerAdapter(); DataProviderRerunListener listener = new DataProviderRerunListener(); testng.addListener((ITestNGListener) tla); testng.addListener(listener); START testng.run(); END assertThat(tla.getFailedTests()).size().isEqualTo(1); assertThat(tla.getSkippedTests()).size().isEqualTo(2); } As mentioned above, this listener is not required.

Target:
public void retryWithDataProvider() { TestNG testng = create(DataProviderRetryTest.class); TestListenerAdapter tla = new TestListenerAdapter(); testng.addListener((ITestNGListener) tla); testng.run(); assertThat(tla.getFailedTests()).size().isEqualTo(1); assertThat(tla.getSkippedTests()).size().isEqualTo(2); }
Source:
private Map<String, String> createGroups(List<String> groups) { START return GroupsHelper.createGroups(groups, m_metaGroups); END } If you reverse the parameters order, it will be more like `createListenerFactory`

Target:
private Map<String, String> createGroups(List<String> groups) { return GroupsHelper.createGroups(m_metaGroups, groups); }
Source:
public void testCreateDynamicGraphAllIndependent() { DynamicGraph<ITestNGMethod> graph = newGraph(IndependentTestClassSample.class); assertThat(graph.getFreeNodes()).hasSize(2); START for (Map.Entry<ITestNGMethod, List<DynamicGraph.Edge<ITestNGMethod>>> edge : graph.getEdges().entrySet()) { END assertThat(edge.getValue()).isEmpty(); } } you can use `values()` instead of `entrySet`

Target:
public void testCreateDynamicGraphAllIndependent() { DynamicGraph<ITestNGMethod> graph = newGraph(IndependentTestClassSample.class); assertThat(graph.getFreeNodes()).hasSize(2); for (List<DynamicGraph.Edge<ITestNGMethod>> edge : graph.getEdges().values()) { assertThat(edge).isEmpty(); } }
Source:
public boolean nameMatchesAny(List<String> names) { START for (String name : names) { END if (getName().equals(name)) { return true; } } return false; } Maybe just ```java return names.contains(getName()); ```

Target:
public boolean nameMatchesAny(List<String> names) { return names.contains(getName()); }
Source:
public static boolean hasFileScheme(String uri) { URI constructedURI = constructURI(uri); if (constructedURI == null) { START constructedURI = new File(uri).toURI(); END } 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); } Will always start by "file", so you can directly return true

Target:
public static boolean hasFileScheme(String uri) { URI constructedURI = constructURI(uri); if (constructedURI == null) { //There were difficulties in constructing the URI. Falling back to considering the URI as a file. return true; } 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); }
Source:
START public String getTmpString() { END return this.tmp; } Make it static

Target:
public static String getTmpString() { return tmp; }
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(); } } START return t; END } `t` is no more used. Just return null

Target:
private static Throwable getConfigFailureException(ITestContext context) { for (IInvokedMethod method : context.getSuite().getAllInvokedMethods()) { ITestNGMethod m = method.getTestMethod(); if (m.isBeforeSuiteConfiguration() && (!method.getTestResult().isSuccess())) { return method.getTestResult().getThrowable(); } } return null; }
Source:
public Object[][] getData() { return new Object[][]{ START {TestClassWithConfigFailureSample.class, 6}, END {TestClassWithConfigSkipSample.class, 4}, {TestClassWithConfigSkipAndFailureSample.class, 6} }; } 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?

Target:
public Object[][] getData() { return new Object[][]{ {TestClassWithConfigFailureSample.class, 3}, {TestClassWithConfigSkipSample.class, 2}, {TestClassWithConfigSkipAndFailureSample.class, 3} }; }
Source:
public void exitWithNonzeroOnSkips() { TestNG tng = create(Issue217TestClassSample.class); tng.run(); START assertEquals(tng.getStatus(), 5); END } 5 means HAS_FAILURE and HAS_FSP, right?

Target:
public void exitWithNonzeroOnSkips() { TestNG tng = create(Issue217TestClassSample.class); tng.run(); assertEquals(tng.getStatus(), 2); }
Source:
private static boolean isExcluded(Collection<String> excludedGroups, String... groups) { START boolean noGroups = (groups == null || groups.length == 0); END if (!excludedGroups.isEmpty() && noGroups) { return true; } return isMemberOf(excludedGroups, groups); } groups cannot be null.

Target:
private static boolean isExcluded(Collection<String> excludedGroups, String... groups) { if (!excludedGroups.isEmpty() && groups.length == 0) { return true; } return isMemberOf(excludedGroups, groups); }