auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public EntityManager createEntityManager() { START return new OgmEntityManager( this, hibernateEmf.createEntityManager().unwrap( EntityManagerImpl.class ) ); END } There is no handling for the specific implementation _EntityManagerImpl.class_ in the unwrap() implementation of our EntityManager. This happens to work as unwrap() is able to cast it to _EntityManager_ (the interface), but this only works if the actual implementation happens to be an _EntityManagerImpl_. So.. shouldn't you rather cast explicitly?

Target:
public EntityManager createEntityManager() { return new OgmEntityManager( this, (EntityManagerImpl) hibernateEmf.createEntityManager() ); }
Source:
public static PersistenceStrategy<?, ?, ?> getPerTableStrategy(EmbeddedCacheManager externalCacheManager, URL configUrl, JtaPlatform platform, Set<EntityKeyMetadata> entityTypes, START Set<AssociationKeyMetadata> associationTypes, END Set<IdSourceKeyMetadata> idSourceTypes) { PerTableKeyProvider keyProvider = new PerTableKeyProvider(); PerTableCacheManager cacheManager = externalCacheManager != null ? new PerTableCacheManager( externalCacheManager, entityTypes, associationTypes, idSourceTypes ) : new PerTableCacheManager( configUrl, platform, entityTypes, associationTypes, idSourceTypes ); return new PersistenceStrategy<PersistentEntityKey, PersistentAssociationKey, PersistentIdSourceKey>( cacheManager, keyProvider ); } Strange indentation for this method parameters, what happend? :)

Target:
private static PersistenceStrategy<?, ?, ?> getPerTableStrategy( EmbeddedCacheManager externalCacheManager, URL configUrl, JtaPlatform platform, Set<EntityKeyMetadata> entityTypes, Set<AssociationKeyMetadata> associationTypes, Set<IdSourceKeyMetadata> idSourceTypes) { PerTableKeyProvider keyProvider = new PerTableKeyProvider(); PerTableCacheManager cacheManager = externalCacheManager != null ? new PerTableCacheManager( externalCacheManager, entityTypes, associationTypes, idSourceTypes ) : new PerTableCacheManager( configUrl, platform, entityTypes, associationTypes, idSourceTypes ); return new PersistenceStrategy<PersistentEntityKey, PersistentAssociationKey, PersistentIdSourceKey>( cacheManager, keyProvider ); }
Source:
public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) { SessionFactoryImplementor sessionFactoryImplementor = factory; ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry(); Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class ); createSequences( sessionFactoryImplementor, provider ); createEntityConstraints( provider.getDataBase(), configuration ); START initializeQueries( sessionFactoryImplementor, registry ); END } I'm wondering why this is triggered by the schema initializer. Couldn't it be done within the dialect itself during construction? The schema initializer really should only create/update persistent structures in the datastore. This would also avoid the need for that `injectQueries()` method.

Target:
public void initializeSchema(Configuration configuration, SessionFactoryImplementor factory) { SessionFactoryImplementor sessionFactoryImplementor = factory; ServiceRegistryImplementor registry = sessionFactoryImplementor.getServiceRegistry(); Neo4jDatastoreProvider provider = (Neo4jDatastoreProvider) registry.getService( DatastoreProvider.class ); createSequences( sessionFactoryImplementor, provider ); createEntityConstraints( provider.getDataBase(), configuration ); }
Source:
public void testGetResultListSizeWithTypedQuery() throws Exception { START List<Helicopter> helicopters = em.createQuery( "FROM Helicopter", Helicopter.class ) END .getResultList(); Assertions.assertThat( helicopters.size() ).isEqualTo( 2 ); } Is there a test for passing the wrong type when creating a typed query?

Target:
public void testGetResultListSizeWithTypedQuery() throws Exception { List<Helicopter> helicopters = em.createQuery( "FROM Helicopter", Helicopter.class ) .getResultList(); assertThat( helicopters.size() ).isEqualTo( 2 ); }
Source:
public List<Tuple> getTuples() { START ArrayList<Tuple> tuples = new ArrayList<Tuple>(); END if ( rows.size() > 0 ) { for ( Row row : rows ) { tuples.add( new Tuple( new CouchDBTupleSnapshot( row.getValue().getProperties() ) ) ); } } return tuples; } I would use `List<Tuple>` here

Target:
public List<Tuple> getTuples() { List<Tuple> tuples = new ArrayList<Tuple>( rows.size() ); if ( rows.size() > 0 ) { for ( Row row : rows ) { tuples.add( new Tuple( new CouchDBTupleSnapshot( row.getValue().getProperties() ) ) ); } } return tuples; }
Source:
public <R extends Service> void startService(ServiceBinding<R> serviceBinding) { START if ( StartStoppable.class.isInstance( serviceBinding.getService() ) ) { END ( (StartStoppable) serviceBinding.getService() ).start( configuration, sessionFactory ); } else { super.startService( serviceBinding ); } } That's a interesting debate. Should `StartStoppable` be mutually exclusive with `Startable`? It seems to make sense. But then you lose the call in `super` of `Manageable`. Since in the end `Startable` and `StartStoppable` don't make much sense, we could simply always call `super. super.startService`

Target:
public <R extends Service> void startService(ServiceBinding<R> serviceBinding) { super.startService( serviceBinding ); if ( StartStoppable.class.isInstance( serviceBinding.getService() ) ) { ( (StartStoppable) serviceBinding.getService() ).start( configuration, sessionFactory ); } }
Source:
public CassandraDatastoreProvider() { try { Class.forName( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } catch (ClassNotFoundException e) { START log.unableToLoadDriver("org.apache.cassandra.cql.jdbc.CassandraDriver") ; END } } this should be thrown, as it generates an exception

Target:
public CassandraDatastoreProvider() { try { Class.forName( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } catch (ClassNotFoundException e) { throw log.unableToLoadDriver( "org.apache.cassandra.cql.jdbc.CassandraDriver" ); } }
Source:
public Object get(String column) { TupleOperation result = currentState.get( column ); if ( result == null ) { return snapshot.get( column ); } else if ( result.getType() == PUT_NULL || result.getType() == REMOVE ) { START return result; END } else { return result.getValue(); } } shouldn't this return null ? If not, I don't like this API which might return "Object" and with quite a different meaning :)

Target:
public Object get(String column) { TupleOperation result = currentState.get( column ); if ( result == null ) { return snapshot.get( column ); } else if ( result.getType() == PUT_NULL || result.getType() == REMOVE ) { return null; } else { return result.getValue(); } }
Source:
public void addDownloadedRecord(ServerReadingListRecord down) { final Boolean deleted = down.fields.getBoolean("deleted"); if (deleted == null || !deleted.booleanValue()) { additionsOrChanges.add(down); } START addDeletion(down.getGUID()); END } Do you want an `else`? (I'll keep reading.)

Target:
public void addDownloadedRecord(ServerReadingListRecord down) { final Boolean deleted = down.fields.getBoolean("deleted"); if (deleted != null && deleted.booleanValue()) { addDeletion(down.getGUID()); } else { additionsOrChanges.add(down); } }
Source:
START protected final AlarmManager getAlarmManager() { END return getAlarmManager(this.getApplicationContext()); } I would suggest that this, its sibling, and perhaps `createPendingIntent` not be `final`.

Target:
protected AlarmManager getAlarmManager() { return getAlarmManager(this.getApplicationContext()); }
Source:
public EngineSettings(ExtendedJSONObject object) throws NumberFormatException { this.syncID = object.getString("syncID"); START this.version = object.getIntegerSafely("version").intValue(); END } Careful. You can also throw a `ClassCastException` in `getString`, and a `NullPointerException` by calling `intValue` on the result of `getIntegerSafely`. I'd be inclined to wrap this whole thing: ``` try { … } catch (Exception e) { throw new IllegalArgumentException(…); // Rethrow with cause. } ``` or a suitable "bad JSON" input. Sure beats having a random NPE if you get a missing version!

Target:
public EngineSettings(ExtendedJSONObject object) { try { this.syncID = object.getString("syncID"); this.version = object.getIntegerSafely("version").intValue(); } catch (Exception e ) { throw new IllegalArgumentException(e); } }
Source:
protected void insert(Record record) throws NoGuidForIdException, NullCursorException, ParentNotFoundException { HistoryRecord toStore = (HistoryRecord) prepareRecord(record); START enqueueNewRecord(toStore); END } Again, inline `toStore`.

Target:
protected void insert(Record record) throws NoGuidForIdException, NullCursorException, ParentNotFoundException { enqueueNewRecord((HistoryRecord) prepareRecord(record)); }
Source:
public String read(Record record) { UserIdReader userIdReader = new UserIdReader(); ClientSummaryReader clientReader = new ClientSummaryReader(); String timestamp = record.getTimestamp().toString(); String userId = userIdReader.read(record); String client = clientReader.read(record); START return timestamp + ":" + userId + ":" + client; END } Please use Key.SEPARATOR for ":".

Target:
public String read(Record record) { Long timestamp = record.getTimestamp(); String userId = (new UserIdReader()).read(record); String client = (new ClientSummaryReader()).read(record); return Long.toString(timestamp) + ":" + userId + ":" + client; }
Source:
private void onNext() { if (mClientCertificateCheckBox.isChecked()) { // Auto-setup doesn't support client certificates. onManualSetup(); return; } String email = mEmailView.getText().toString(); ConnectionSettings connectionSettings = providersXmlDiscovery.discover(email); START if (connectionSettings == null) { END connectionSettings = srvServiceDiscovery.discover(email); } if (connectionSettings != null) { finishAutoSetup(connectionSettings); } else { // We don't have default settings for this account, start the manual setup process. onManualSetup(); } } Same as `ThunderbirdDiscovery`, I don't want to actually use this just yet. Please leave `AccountSetupBasics` unchanged.

Target:
private void onNext() { if (mClientCertificateCheckBox.isChecked()) { // Auto-setup doesn't support client certificates. onManualSetup(); return; } String email = mEmailView.getText().toString(); ConnectionSettings connectionSettings = providersXmlDiscovery.discover(email); if (connectionSettings != null) { finishAutoSetup(connectionSettings); } else { // We don't have default settings for this account, start the manual setup process. onManualSetup(); } }
Source:
private NotificationHelper createFakeNotificationHelper(NotificationManagerCompat notificationManager, NotificationCompat.Builder builder) { NotificationHelper notificationHelper = mock(NotificationHelper.class); when(notificationHelper.getContext()).thenReturn(RuntimeEnvironment.application); when(notificationHelper.getNotificationManager()).thenReturn(notificationManager); when(notificationHelper.createNotificationBuilder(any(Account.class), START any(NotificationChannelUtils.ChannelType.MISCELLANEOUS.getClass()))) END .thenReturn(builder); return notificationHelper; } If you want to match on a specific value you can use `ArgumentMatchers.eq()`: ```suggestion eq(NotificationChannelUtils.ChannelType.MISCELLANEOUS))) ``` If any value will do, there's no need to call `getClass()` on an instance. You can write it as: ```suggestion any(NotificationChannelUtils.ChannelType.class))) ```

Target:
private NotificationHelper createFakeNotificationHelper(NotificationManagerCompat notificationManager, NotificationCompat.Builder builder) { NotificationHelper notificationHelper = mock(NotificationHelper.class); when(notificationHelper.getContext()).thenReturn(RuntimeEnvironment.application); when(notificationHelper.getNotificationManager()).thenReturn(notificationManager); when(notificationHelper.createNotificationBuilder(any(Account.class), any(NotificationChannelUtils.ChannelType.class))) .thenReturn(builder); return notificationHelper; }
Source:
public void shouldKeepDirAttribute() { String html = "<html><body>" + "<table><tbody><tr><td dir=\"rtl\"></td></tr></tbody></table>" + "</body></html>"; Document result = htmlSanitizer.sanitize(html); START assertEquals("<html><head></head><body>" + END "<table><tbody><tr><td dir=\"rtl\"></td></tr></tbody></table>" + "</body></html>", toCompactString(result)); } Wouldn't `assertEquals(html, toCompactString(result))` better communicate our expectation? (I realize the input needs to be changed then)

Target:
public void shouldKeepDirAttribute() { String html = "<html><head></head><body>" + "<table><tbody><tr><td dir=\"rtl\"></td></tr></tbody></table>" + "</body></html>"; Document result = htmlSanitizer.sanitize(html); assertEquals(html, toCompactString(result)); }
Source:
public abstract void setFlags(List<? extends Message> messages, Set<Flag> flags, boolean value) throws MessagingException; public abstract void setFlags(Set<Flag> flags, boolean value) throws MessagingException; public abstract String getUidFromMessageId(Message message) throws MessagingException; START public void expunge(List<Long> knownDeletedUids) throws MessagingException END With the `Folder` abstraction UIDs are opaque strings. UIDs being numbers is an implementation detail of `ImapFolder`. So until we can replace this interface with something more flexible let's keep this interface clean. Also, sometimes (e.g. when emptying the Trash folder) an unconstrained EXPUNGE makes sense. So I'd keep the original method and add a new one that better describes what it is about. My suggestion: ```java public void expungeUids(List<String> uids) throws MessagingException ```

Target:
public abstract void setFlags(List<? extends Message> messages, Set<Flag> flags, boolean value) throws MessagingException; public abstract void setFlags(Set<Flag> flags, boolean value) throws MessagingException; public abstract String getUidFromMessageId(Message message) throws MessagingException; public void expunge() throws MessagingException
Source:
public synchronized boolean setFolderSyncMode(FolderMode syncMode) { FolderMode oldSyncMode = folderSyncMode; folderSyncMode = syncMode; if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE) { return true; } START return syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE; END } If you combine the last two `return` statements you might as well only have one. However, I think the old way makes the code easier to read/understand.

Target:
public synchronized boolean setFolderSyncMode(FolderMode syncMode) { FolderMode oldSyncMode = folderSyncMode; folderSyncMode = syncMode; if (syncMode == FolderMode.NONE && oldSyncMode != FolderMode.NONE) { return true; } if (syncMode != FolderMode.NONE && oldSyncMode == FolderMode.NONE) { return true; } return false; }
Source:
START ImapStore getStore() { END return store; } Why is this necessary?

Target:
private ImapStore getStore() { return store; }
Source:
START public Builder queryString(String queryString) { END command.queryString = queryString; return builder; } so much boilerplate :\ would this be easier to do with [AutoValue](https://github.com/google/auto/blob/master/value/userguide/index.md)?

Target:
public Builder queryString(String queryString) { command.queryString = queryString; return this; }
Source:
public void copy_to_ClipBoard(Context context,String address){ START com.fsck.k9.helper.ClipboardManager clipboardManager = com.fsck.k9.helper.ClipboardManager.getInstance(context); END clipboardManager.setText(address,address); } Import the class rather than fully-qualifying.

Target:
public void copy_to_ClipBoard(Context context,String address){ ClipboardManager clipboardManager = ClipboardManager.getInstance(context); clipboardManager.setText(address,address); }
Source:
public void open_withCompressDeflateCapability_shouldEnableCompression() throws Exception { settings.setUseCompression(true); MockImapServer server = new MockImapServer(); START simplePreAuthAndLoginDialog(server, "", "COMPRESS=DEFLATE"); END server.expect("3 COMPRESS DEFLATE"); server.output("3 OK"); server.enableCompression(); simplePostAuthenticationDialog(server, false, 4); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } Please introduce a new method rather than adding a new argument that is the same non-obvious value almost everywhere.

Target:
public void open_withCompressDeflateCapability_shouldEnableCompression() throws Exception { settings.setUseCompression(true); MockImapServer server = new MockImapServer(); simplePreAuthAndLoginDialog(server, "COMPRESS=DEFLATE"); server.expect("3 COMPRESS DEFLATE"); server.output("3 OK"); server.enableCompression(); simplePostAuthenticationDialog(server, 4); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); }
Source:
private void performSaveAfterChecks() { currentMessageBuilder = createMessageBuilder(true); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); START currentMessageBuilder.setHighPriority(isHighPriority); END currentMessageBuilder.buildAsync(this); } } this doesn't belong here

Target:
private void performSaveAfterChecks() { currentMessageBuilder = createMessageBuilder(true); if (currentMessageBuilder != null) { setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } }
Source:
public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; START currentMessageBuilder.setHighPriority(isHighPriority); END setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } } this should be in createMessageBuilder

Target:
public void performSendAfterChecks() { currentMessageBuilder = createMessageBuilder(false); if (currentMessageBuilder != null) { changesMadeSinceLastSave = false; setProgressBarIndeterminateVisibility(true); currentMessageBuilder.buildAsync(this); } }
Source:
private String getSpecialFoldersList() { START String builder = "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + END "<propfind xmlns=\"DAV:\">" + "<prop>" + "<" + WebDavConstants.DAV_MAIL_INBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_DRAFTS_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_OUTBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SENT_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_TRASH_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SPAM_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "</prop>" + "</propfind>"; // This should always be ##DavMailSubmissionURI## for which we already have a constant // buffer.append("<sendmsg xmlns=\"urn:schemas:httpmail:\"/>"); return builder; } The variable name should now probably be something like `specialFoldersListRequest`.

Target:
private String getSpecialFoldersList() { return "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>" + "<propfind xmlns=\"DAV:\">" + "<prop>" + "<" + WebDavConstants.DAV_MAIL_INBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_DRAFTS_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_OUTBOX_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SENT_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_TRASH_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + "<" + WebDavConstants.DAV_MAIL_SPAM_FOLDER + " xmlns=\"urn:schemas:httpmail:\"/>" + // This should always be ##DavMailSubmissionURI## for which we already have a constant // "<sendmsg xmlns=\"urn:schemas:httpmail:\"/>" + "</prop>" + "</propfind>"; }
Source:
public int hashCode() { if(getName().equalsIgnoreCase("INBOX")){ String inbox = new String("INBOX") ; START return inbox.hashCode(); END } return getName().hashCode(); } Just do `return "INBOX".hashCode();` Nice approach though 👍 Should be good to push once you've tidied that.

Target:
public int hashCode() { if (getName().equalsIgnoreCase("INBOX")) { return "INBOX".hashCode(); } return getName().hashCode(); }
Source:
public void setBccVisibility(boolean visible) { boolean bccAlreadyVisible = isBccVisible(); bccWrapper.setVisibility(visible ? View.VISIBLE : View.GONE); START if(visible && !bccAlreadyVisible){ END List<Recipient> bccRecipients = getBccRecipients(); bccView.clear(); bccView.addRecipients(bccRecipients.toArray(new Recipient[0])); } bccDivider.setVisibility(visible ? View.VISIBLE : View.GONE); } This removes all recipients and re-adds them, fixing the symptom but not the cause. Do you know what causes the underlying problem? Also, this is more logic than an MvpView class should have

Target:
public void setBccVisibility(boolean visible) { bccWrapper.setVisibility(visible ? View.VISIBLE : View.GONE); bccDivider.setVisibility(visible ? View.VISIBLE : View.GONE); }
Source:
void onClickRecipientExpander() { recipientMvpView.setCcVisibility(true); recipientMvpView.setBccVisibility(true); START if(defaultBccAddress != null) addBccAddresses(defaultBccAddress); END updateRecipientExpanderVisibility(); } Code style - add a space after the `if` and always use a new line and `{}`'s.

Target:
void onClickRecipientExpander() { recipientMvpView.setCcVisibility(true); recipientMvpView.setBccVisibility(true); if ( defaultBccAddress != null ) { addBccAddresses(defaultBccAddress); } updateRecipientExpanderVisibility(); }
Source:
public void updateAttachmentsList(Attachment attachment){ Attachment originalAttachment = attachments.get(attachment.uri); originalAttachment.updateResizeInfo(attachment.resizeFactor, attachment.overrideDefault); START Log.d("ATTACH","Yes : " + attachments.size()); END } Stick to K9.LOG_TAG and change the logging to be more useful. Also, you'll need to rebase this code to use `Timber` sooner or later.

Target:
public void updateAttachmentsList(Attachment attachment){ Attachment originalAttachment = attachments.get(attachment.uri); originalAttachment.updateResizeInfo(attachment.resizeFactor, attachment.overrideDefault); }
Source:
public static void clearTemporaryAttachmentsCache(Context context){ File cacheDir = context.getCacheDir(); File tempAttachmentsDirectory = new File(cacheDir.getPath() + RESIZED_ATTACHMENTS_TEMPORARY_DIRECTORY); if(tempAttachmentsDirectory.exists()){ try { FileUtils.cleanDirectory(tempAttachmentsDirectory); } catch (IOException e) { Timber.e("Error occurred while cleaning temporary directory for resized attachments"); START e.printStackTrace(); END } } } Pass the exception into Timber and there's no need to print the stack trace.

Target:
public static void clearTemporaryAttachmentsCache(Context context) { File cacheDir = context.getCacheDir(); File tempAttachmentsDirectory = new File(cacheDir.getPath() + RESIZED_ATTACHMENTS_TEMPORARY_DIRECTORY); if (tempAttachmentsDirectory.exists()) { try { FileUtils.cleanDirectory(tempAttachmentsDirectory); } catch (IOException e) { Timber.e(e, "Error occurred while cleaning temporary directory for resized attachments"); } } }
Source:
private void resetVisibleLimits() { try { getLocalStore().resetVisibleLimits(getDisplayCount()); } catch (MessagingException e) { START Timber.e("Unable to reset visible limits", e); END } } With Timber exceptions are the first argument. Format string arguments go at the end.

Target:
private void resetVisibleLimits() { try { getLocalStore().resetVisibleLimits(getDisplayCount()); } catch (MessagingException e) { Timber.e(e, "Unable to reset visible limits"); } }
Source:
public void updateDownloadProgress(int newProgress) { progress = newProgress; for (int i = progress; i <= newProgress; i++) { START dialog.setProgress(i); END } } Calling `setProgress()` with intermediate values shouldn't be necessary.

Target:
public void updateDownloadProgress(int newProgress) { progress = newProgress; dialog.setProgress(newProgress); }
Source:
private void initializeActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowCustomEnabled(true); START actionBar.setCustomView(R.layout.actionbar_custom); END actionBar.setDisplayHomeAsUpEnabled(true); } We didn't use the custom action bar before. No need to use it now.

Target:
private void initializeActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayHomeAsUpEnabled(true); }
Source:
public RemoteViewsFactory onGetViewFactory(Intent intent) { START return new MessageListRemoteViewFactory(this.getApplicationContext()); END } `this.` seems unnecessary

Target:
public RemoteViewsFactory onGetViewFactory(Intent intent) { return new MessageListRemoteViewFactory(getApplicationContext()); }
Source:
public static boolean isApgInstalled(Context context) { Intent intent = new Intent("org.openintents.openpgp.IOpenPgpService"); intent.setPackage(PACKAGE_NAME_APG); START List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(intent, 0); END return !resInfo.isEmpty(); } `queryIntentServices()` might return `null`

Target:
public static boolean isApgInstalled(Context context) { Intent intent = new Intent("org.openintents.openpgp.IOpenPgpService"); intent.setPackage(PACKAGE_NAME_APG); List<ResolveInfo> resInfo = context.getPackageManager().queryIntentServices(intent, 0); return resInfo != null && !resInfo.isEmpty(); }
Source:
public void getTextFromPart_withUnknownEncoding_shouldReturnNull() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); BinaryMemoryBody body = new BinaryMemoryBody("Sample text body".getBytes(), "unknown encoding"); part.setBody(body); START assertNull(MessageExtractor.getTextFromPart(part)); END } Arrange, act, assert. ```java … String textFromPart = MessageExtractor.getTextFromPart(part) ; assertNull(textFromPart); ```

Target:
public void getTextFromPart_withUnknownEncoding_shouldReturnNull() throws Exception { part.setHeader(MimeHeader.HEADER_CONTENT_TYPE, "text/plain"); BinaryMemoryBody body = new BinaryMemoryBody("Sample text body".getBytes(), "unknown encoding"); part.setBody(body); String result = MessageExtractor.getTextFromPart(part); assertNull(result); }
Source:
public void delete_notImplemented() throws MessagingException { ImapFolder folder = createFolder("Folder"); try { folder.delete(false); START fail("Error expected"); END } catch (Error e) { } } `@Test(expectedException = Error.class)`

Target:
public void delete_notImplemented() throws MessagingException { ImapFolder folder = createFolder("Folder"); folder.delete(false); }
Source:
public void areMoreMessagesAvailable_withIndexOf1_shouldReturnFalseWithoutPerformingSearch() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); boolean result = folder.areMoreMessagesAvailable(1, null); //SELECT during OPEN verify(imapConnection, times(1)).executeSimpleCommand(anyString()); START assertFalse(result); END } `assertFalse(folder.areMoreMessagesAvailable(1, null))`

Target:
public void areMoreMessagesAvailable_withIndexOf1_shouldReturnFalseWithoutPerformingSearch() throws Exception { ImapFolder folder = createFolder("Folder"); prepareImapFolderForOpen(OPEN_MODE_RW); folder.open(OPEN_MODE_RW); assertFalse(folder.areMoreMessagesAvailable(1, null)); //SELECT during OPEN and no more verify(imapConnection, times(1)).executeSimpleCommand(anyString()); }
Source:
public boolean isForceTextMessageFormat() { if (!cryptoEnablePgpInline) { return false; START } END ComposeCryptoStatus cryptoStatus = getCurrentCryptoStatus(); return cryptoStatus.isEncryptionEnabled() || cryptoStatus.isSigningEnabled(); } This is a bit double negativey Wouldn't ``` if (cryptoEnablePgpInline) { ComposeCryptoStatus .... } else { return false; } ``` be more readable.

Target:
public boolean isForceTextMessageFormat() { if (cryptoEnablePgpInline) { ComposeCryptoStatus cryptoStatus = getCurrentCryptoStatus(); return cryptoStatus.isEncryptionEnabled() || cryptoStatus.isSigningEnabled(); } else { return false; } }
Source:
private static String cssStyleTheme() { START if (K9.getK9MessageViewTheme() == K9.Theme.DARK) { END return "<style type=\"text/css\">" + "* { background: black ! important; color: #F3F3F3 !important }" + ":link, :link * { color: #CCFF33 !important }" + ":visited, :visited * { color: #551A8B !important }</style> "; } return ""; } If you want to use the exit-early "pattern", invert the `if` condition. Otherwise please use an `else` statement.

Target:
private static String cssStyleTheme() { if (K9.getK9MessageViewTheme() == K9.Theme.DARK) { return "<style type=\"text/css\">" + "* { background: black ! important; color: #F3F3F3 !important }" + ":link, :link * { color: #CCFF33 !important }" + ":visited, :visited * { color: #551A8B !important }</style> "; } else { return ""; } }
Source:
public static MessageViewInfo createWithErrorState(Message message) { START return new MessageViewInfo(message, null, null, null, null, null, null); END } Looks ugly and potentially a source of future NPEs.

Target:
public static MessageViewInfo createWithErrorState(Message message) { return new MessageViewInfo(message, null, null, null, null, null, null, null); }
Source:
MimeBodyPart multipart(String type, BodyPart... subParts) throws MessagingException { MimeMultipart multiPart = new MimeMultipart(); multiPart.setSubType(type); for (BodyPart subPart : subParts) { multiPart.addBodyPart(subPart); } MimeBodyPart resultPart = new MimeBodyPart(multiPart); START createdMultiparts.add(resultPart); END return resultPart; } Instead of using `createdMultiparts` I think tests would be easier to read if `message` were used to retrieve a reference to the desired child part. Maybe with a helper method that makes addressing parts easier, e.g. ``` java Part signaturePart = getPart(message, "1.1"); ``` to get the `application/pgp-signature` from ``` java Message message = messageFromBody( multipart("mixed", bodypart("text/plain"), multipart("signed", bodypart("text/plain"), bodypart("application/pgp-signature") ) ) ); ``` (Not that we need a reference to the signed part. Just makes for a better example.)

Target:
MimeBodyPart multipart(String type, BodyPart... subParts) throws MessagingException { MimeMultipart multiPart = new MimeMultipart(); multiPart.setSubType(type); for (BodyPart subPart : subParts) { multiPart.addBodyPart(subPart); } return new MimeBodyPart(multiPart); }
Source:
private Message buildLargeNewMessage() { Message message = mock(Message.class); when(message.olderThan(any(Date.class))).thenReturn(false); START when(message.getSize()).thenReturn(MAXIMUM_SMALL_MESSAGE_SIZE+1); END return message; } Code style issue: spaces missing in expression; should be `MAXIMUM_SMALL_MESSAGE_SIZE + 1`

Target:
private Message buildLargeNewMessage() { Message message = mock(Message.class); when(message.olderThan(any(Date.class))).thenReturn(false); when(message.getSize()).thenReturn(MAXIMUM_SMALL_MESSAGE_SIZE + 1); return message; }
Source:
public abstract void setSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException; public abstract Address[] getRecipients(RecipientType type) throws MessagingException; START public abstract Address[] getListPost(); END public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; public void setRecipient(RecipientType type, Address address) throws MessagingException { setRecipients(type, new Address[] { address }); } Please don't add more utility methods to `Message`. Instead you could create a method `ListHeaders.getListPostAddress(Message)` that gets the appropriate header from the message.

Target:
public abstract void setSentDate(Date sentDate, boolean hideTimeZone) throws MessagingException; public abstract Address[] getRecipients(RecipientType type) throws MessagingException; public abstract void setRecipients(RecipientType type, Address[] addresses) throws MessagingException; public void setRecipient(RecipientType type, Address address) throws MessagingException { setRecipients(type, new Address[] { address }); }
Source:
START MimeBodyPart(MimeHeader header, Body body) throws MessagingException { END this(body); mHeader = header; } If you make the other constructors call this one, you can keep `mHeader` as `final`

Target:
MimeBodyPart(MimeHeader header, Body body) throws MessagingException { this(body, null, header); }
Source:
private String combineFlags(Iterable<Flag> flags) { List<String> flagNames = new ArrayList<String>(); for (Flag flag : flags) { // client's can't add the RECENT flag! START if( !flag.equals(Flag.RECENT) ) END flagNames.add(flag.realName()); } return combine(flagNames.toArray(new String[flagNames.size()]), ' '); } curly brackets avoid goto fail :-)

Target:
private String combineFlags(Iterable<Flag> flags) { List<String> flagNames = new ArrayList<String>(); for (Flag flag : flags) { // client's can't add the RECENT flag! if (!flag.equals(Flag.RECENT)) { flagNames.add(flag.realName()); } } return combine(flagNames.toArray(new String[flagNames.size()]), ' '); }
Source:
public void splitCompleteUserIdShouldReturnAll3Components() throws Exception { OpenPgpUtils.UserInfo info = OpenPgpUtils.splitUserId("Max Mustermann (this is a comment) <max@example.com>"); START assertEquals(info.name, "Max Mustermann"); END assertEquals(info.comment, "this is a comment"); assertEquals(info.email, "max@example.com"); } the `assertEquals` param order is `expected, actual`, so this (and all other assertions) should be written as ``` java assertEquals("Max Mustermann", info.name); ```

Target:
public void splitCompleteUserIdShouldReturnAll3Components() throws Exception { OpenPgpUtils.UserInfo info = OpenPgpUtils.splitUserId("Max Mustermann (this is a comment) <max@example.com>"); assertEquals("Max Mustermann", info.name); assertEquals("this is a comment", info.comment); assertEquals("max@example.com", info.email); }
Source:
START public boolean equals(Object o) { END if (!(o instanceof ObjectProperty)) { return false; } ObjectProperty that = (ObjectProperty) o; if (properties != null ? !properties.equals(that.properties) : that.properties != null) { return false; } return super.equals(o); } can you possibly just add ``` if (this == o) { return true; } ```

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ObjectProperty)) { return false; } ObjectProperty that = (ObjectProperty) o; if (properties != null ? !properties.equals(that.properties) : that.properties != null) { return false; } return super.equals(o); }
Source:
public Operation response(int key, Response response) { START this.addResponse(String.valueOf(key),response); END this.addResponseObject(String.valueOf(key),response); return this; } only add to responseObject

Target:
public Operation response(int key, Response response) { this.addResponseObject(String.valueOf(key),response); return this; }
Source:
public Operation defaultResponse(Response response) { START this.addResponse("default",response); END this.addResponseObject("default",response); return this; } only add to responseObject

Target:
public Operation defaultResponse(Response response) { this.addResponseObject("default",response); return this; }
Source:
public void setResponses(Map<String, Response> responses) { this.responses = responses; START if (this.responsesObject == null && responses != null) { END this.responsesObject = new Responses(); for (String key : responses.keySet()) { this.responsesObject.put(key, responses.get(key)); } } } remove all added logic, as such logic is handled in the getter

Target:
public void setResponses(Map<String, Response> responses) { this.responses = responses; }
Source:
public void setResponsesObject(Responses responsesObject) { this.responsesObject = responsesObject; START if (responses == null && responsesObject != null) { END responses = new LinkedHashMap<String, Response>(); for (String key : this.responsesObject.keySet()) { responses.put(key, responsesObject.get(key)); } } } remove all added logic, as such logic is handled in the getter

Target:
public void setResponsesObject(Responses responsesObject) { this.responsesObject = responsesObject; }
Source:
public static void main(String[] args) { try { new StartMain(args).go(); System.exit(0); } catch (Throwable t) { START StreamSupport.stream(exceptionHandlerLoader.spliterator(), false) END .filter(eh -> eh.supports(t)) .findFirst() .orElse(new DefaultExceptionHandler()) .handle(t); System.exit(1); } } I think there is no need to use streams here...

Target:
public static void main(String[] args) { try { new StartMain(args).go(); } catch (Throwable t) { StreamSupport.stream(exceptionHandlerLoader.spliterator(), false) .filter(eh -> eh.supports(t)) .findFirst() .orElse(new DefaultExceptionHandler()) .handle(t); System.exit(1); } }
Source:
public String toString() { START return "Configurator observer method [Bean class = " + getBeanClass().toString() END + ", type = " + getObservedType() + ", qualifiers =" + Formats.formatAnnotations(getObservedQualifiers()) + ", priority =" + getPriority() + ", async =" + isAsync() + ", reception =" + getReception() + ", transaction phase =" + getTransactionPhase() + "]"; } I'm not sure why but we allow to set `null` bean class. If you remove `toString()` here, then this method should not throw NPE and the resulting string should be the same.

Target:
public String toString() { return "Configurator observer method [Bean class = " + getBeanClass() + ", type = " + getObservedType() + ", qualifiers =" + Formats.formatAnnotations(getObservedQualifiers()) + ", priority =" + getPriority() + ", async =" + isAsync() + ", reception =" + getReception() + ", transaction phase =" + getTransactionPhase() + "]"; }
Source:
public <X> WeldInstance<X> select(Type subtype, Annotation... qualifiers) { // verify if this was invoked on WeldInstance<Object> START if (!this.getType().getTypeName().equals(Object.class.getName())) { END throw BeanLogger.LOG.selectByTypeOnlyWorksOnObject(); } // This cast should be safe, we make sure that this method is only invoked on WeldInstance<Object> // and any type X will always extend Object return (WeldInstance<X>)selectInstance(subtype, qualifiers); } `!this.getType().equals(Object.class)` should be fine...

Target:
public <X> WeldInstance<X> select(Type subtype, Annotation... qualifiers) { // verify if this was invoked on WeldInstance<Object> if (!this.getType().equals(Object.class)) { throw BeanLogger.LOG.selectByTypeOnlyWorksOnObject(); } // This cast should be safe, we make sure that this method is only invoked on WeldInstance<Object> // and any type X will always extend Object return (WeldInstance<X>)selectInstance(subtype, qualifiers); }
Source:
public ScheduledExecutorService getTimerExecutor() { if (timerExecutor == null) { START timerExecutor = Executors.newScheduledThreadPool(1, new DaemonThreadFactory(new ThreadGroup("weld-workers"), "weld-timer-")); END } return timerExecutor; } I would extract "weld-workers" to a constant on the `DaemonThreadFactory`.

Target:
public ScheduledExecutorService getTimerExecutor() { return timerExecutor; }
Source:
public static Archive<?> createTestArchive() { START return ClassPath.builder().add(ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(WeldInstanceTest.class)) END .addPackage(ParallelNotificationModeTest.class.getPackage())).build(); } Just noticed the minor here - referencing another test in `Utils.getDeploymentNameAsHash`

Target:
public static Archive<?> createTestArchive() { return ClassPath.builder().add(ShrinkWrap.create(BeanArchive.class, Utils.getDeploymentNameAsHash(ParallelNotificationModeTest.class)) .addPackage(ParallelNotificationModeTest.class.getPackage())).build(); }
Source:
static void processAnnotatedType(@Observes ProcessAnnotatedType<?> pat) { START pat.veto(); END } Please remove this invocation. Right now, the test would pass even without your `ExtensionBeanDeployer` modification. If you remove the invocation, the test would fail without the modification. Otherwise looks good now.

Target:
static void processAnnotatedType(@Observes ProcessAnnotatedType<?> pat) { }
Source:
private void fireContainerInitializedEvent() { beanManager().fireEvent(new ContainerInitialized(id), Initialized.Literal.APPLICATION); START WeldSELogger.LOG.weldContainerInitialized(id); END } Hm, don't move the message - it should be logged before the event, otherwise it will never appear if a `ContainerInitialized` observer blocks...

Target:
private void fireContainerInitializedEvent() { WeldSELogger.LOG.weldContainerInitialized(id); beanManager().fireEvent(new ContainerInitialized(id), Initialized.Literal.APPLICATION); }
Source:
public void vetoedAlternativesShouldBeRejected() { try { deployer.deploy("VetoedAlternativeWithoutPropertyWar"); Assert.fail("A web application deployed successfuly with a vetoed bean defined as an alternative in the beans.xml and the property org.jboss.weld.bootstrap.allowExcludedAlternatives was left as it's default value"); } catch (Exception e) { START Assert.assertTrue(e.getMessage().contains("WELD-001422")); END } } This assertion probably fails because when running in-container Arquillian tests the `DeploymentExceptionTransformer` is used to extract the final exception and message (see also https://github.com/weld/core/blob/master/tests-arquillian/src/test/java/org/jboss/weld/tests/util/WildFly8DeploymentExceptionTransformer.java). I would leave out this assertion completely. Also I would replace the `Deployer` API with `@org.jboss.arquillian.container.test.api.ShouldThrowException`.

Target:
public void vetoedAlternativesShouldBeRejected() throws Exception { // should throw deployment exception }
Source:
public void mockAlternativeIsVetoed() { START Assert.assertEquals(getUniqueBean(PaymentProcessor.class).getName(), "paymentProcessorImpl"); END } You should swap the method arguments I guess. Testng use different order than JUnit. Same for other `assertEquals` mehtods.

Target:
public void mockAlternativeIsVetoed() { Assert.assertEquals("paymentProcessorImpl", getUniqueBean(PaymentProcessor.class).getName()); }
Source:
START private static boolean isAlternativeStereotype(BeanManagerImpl beanManager, Class<? extends Annotation> stereotype) { END final StereotypeModel<? extends Annotation> model = beanManager.getServices().get(MetaAnnotationStore.class).getStereotype(stereotype); if (model.isValid() && model.isAlternative()) { return true; } return false; } Is there a reason to have this `static`? If not, I would remove it.

Target:
private boolean isAlternativeStereotype(BeanManagerImpl beanManager, Class<? extends Annotation> stereotype) { final StereotypeModel<? extends Annotation> model = beanManager.getServices().get(MetaAnnotationStore.class).getStereotype(stereotype); if (model.isValid() && model.isAlternative()) { return true; } return false; }
Source:
FastAnnotatedTypeLoader(BeanManagerImpl manager, ClassTransformer transformer, ClassFileServices classFileServices, ContainerLifecycleEvents events, FastProcessAnnotatedTypeResolver resolver) { super(manager, transformer, events); this.fallback = new AnnotatedTypeLoader(manager, transformer, events); this.classFileServices = classFileServices; this.resolver = resolver; this.checkTypeModifiers = initCheckTypeModifiers(); if (!checkTypeModifiers) { START BootstrapLogger.LOG.usingOldJandexVersion(); END } } I would move the log message inside the catch block on line 139.

Target:
FastAnnotatedTypeLoader(BeanManagerImpl manager, ClassTransformer transformer, ClassFileServices classFileServices, ContainerLifecycleEvents events, FastProcessAnnotatedTypeResolver resolver) { super(manager, transformer, events); this.fallback = new AnnotatedTypeLoader(manager, transformer, events); this.classFileServices = classFileServices; this.resolver = resolver; this.checkTypeModifiers = initCheckTypeModifiers(); }
Source:
public ClassFileInfo getClassFileInfo(String className) { if (!jandexStaticCheckAvailable) { throw new ClassFileInfoException("Using old Jandex version."); START } END return new JandexClassFileInfo(className, index, annotationClassAnnotationsCache, classLoader); } Altough it seems logical to throw exception here, I'd rather throw it in `ClassFileInfo.getModifiers()`. The reason is performance - `FastAnnotatedTypeLoader` can sucessfully "skip" many classes (annotation, `@Vetoed`... see also `FastAnnotatedTypeLoader.loadAnnotatedType()`)

Target:
public ClassFileInfo getClassFileInfo(String className) { return new JandexClassFileInfo(className, index, annotationClassAnnotationsCache, classLoader); }
Source:
public Set<Type> getTypes() { HashSet<Type> types = new HashSet<Type>(); types.add(BuilderInterceptorInstance.class); START types.add(Object.class); END return types; } As I already said - this should be an immutable set cached in a private static final field.

Target:
public Set<Type> getTypes() { return types; }
Source:
public BeanBuilder<T> addInjectionPoints(Set<InjectionPoint> injectionPoints) { checkArgumentNotNull(injectionPoints, ARG_INJECTION_POINTS); START Collections.addAll(this.injectionPoints, injectionPoints.toArray(new InjectionPoint[injectionPoints.size()])); END return this; } `this.injectionPoints.addAll(injectionPoints)`?

Target:
public BeanBuilder<T> addInjectionPoints(Set<InjectionPoint> injectionPoints) { checkArgumentNotNull(injectionPoints, ARG_INJECTION_POINTS); this.injectionPoints.addAll(injectionPoints); return this; }
Source:
START public void close() throws Exception { END shutdown(); } We should make this less restrictive and remove the "throws Exception" clause.

Target:
public void close() { shutdown(); }
Source:
private Map<String, ManagedConversation> getConversationMap() { checkIsAssociated(); checkContextInitialized(); R request = getRequest(); START Object attribute = getRequestAttribute(getRequest(), CONVERSATIONS_ATTRIBUTE_NAME); END if (attribute == null || !(attribute instanceof Map)) { throw ConversationLogger.LOG.unableToLoadConversations(CONVERSATIONS_ATTRIBUTE_NAME, attribute, request); } return cast(attribute); } reduntant `getRequest()` call

Target:
private Map<String, ManagedConversation> getConversationMap() { checkIsAssociated(); checkContextInitialized(); R request = getRequest(); Object attribute = getRequestAttribute(request, CONVERSATIONS_ATTRIBUTE_NAME); if (attribute == null || !(attribute instanceof Map)) { throw ConversationLogger.LOG.unableToLoadConversations(CONVERSATIONS_ATTRIBUTE_NAME, attribute, request); } return cast(attribute); }
Source:
public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) { try { return cast(resourceLoader.classForName(className)); } catch (ResourceLoadingException e) { return null; START } catch (AccessControlException e) { END return null; } catch (SecurityException e) { return null; } } ACE is a subclass of SecurityException

Target:
public static <T> Class<T> loadClass(String className, ResourceLoader resourceLoader) { try { return cast(resourceLoader.classForName(className)); } catch (ResourceLoadingException e) { return null; } catch (SecurityException e) { return null; } }
Source:
public String[] getParameterTypes() { START return parameterTypes.clone(); END } This is not necessary as we have the control, suppress.

Target:
public String[] getParameterTypes() { return parameterTypes; }
Source:
public ParameterizedTypeImpl(Type rawType, Type[] actualTypeArguments, Type ownerType) { START this.actualTypeArguments = actualTypeArguments.clone(); END this.rawType = rawType; this.ownerType = ownerType; } This is not necessary as we have the control, suppress.

Target:
public ParameterizedTypeImpl(Type rawType, Type[] actualTypeArguments, Type ownerType) { this.actualTypeArguments = actualTypeArguments; this.rawType = rawType; this.ownerType = ownerType; }
Source:
public Type[] getActualTypeArguments() { START return actualTypeArguments.clone(); END } This is not really necessary as we have the control. We should suppress the warning here instead.

Target:
public Type[] getActualTypeArguments() { return actualTypeArguments; }