auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Map<String, Integer> getTasksByPriority() { Map<String, Object> tasksByPriority = (Map<String, Object>) getRealtime().get(TASKS_BY_PRIORITY_PROPERTY); Map<String, Integer> tasksByPriorityMap = new HashMap<String, Integer>(); START for (String priorityKey : tasksByPriority.keySet()) { END tasksByPriorityMap.put(priorityKey, (Integer) tasksByPriority.get(priorityKey)); } return tasksByPriorityMap; } you can use `tasksByPriority.entrySet()` here

Target:
public Map<String, Integer> getTasksByPriority() { Map<String, Object> tasksByPriority = (Map<String, Object>) getRealtime().get(TASKS_BY_PRIORITY_PROPERTY); Map<String, Integer> tasksByPriorityMap = new HashMap<String, Integer>(); for (Entry<String, Object> entry : tasksByPriority.entrySet()) { tasksByPriorityMap.put(entry.getKey(), (Integer) entry.getValue()); } return tasksByPriorityMap; }
Source:
private boolean checkPermission(String permission) { START int res = this.ctx.checkCallingOrSelfPermission(permission); END return (res == PackageManager.PERMISSION_GRANTED); } // nitpick-mode-on Can you change `this.ctx` to `ctx`? // nitpick-mode-off

Target:
private boolean checkPermission(String permission) { int res = ctx.checkCallingOrSelfPermission(permission); return (res == PackageManager.PERMISSION_GRANTED); }
Source:
public Map<String, Object> getLocals() { if (locals == null || locals.length == 0) { return Collections.emptyMap(); } Map<String, Object> localsMap = null; for (Frame.LocalVariable localVariable : locals) { if (localVariable != null) { if (localsMap == null) { START localsMap = new HashMap<>(); END } localsMap.put(localVariable.getName(), localVariable.getValue()); } } return localsMap; } Why is this instantiated here rather than on L47?

Target:
public Map<String, Object> getLocals() { if (locals == null || locals.length == 0) { return Collections.emptyMap(); } Map<String, Object> localsMap = new HashMap<>(); for (Frame.LocalVariable localVariable : locals) { if (localVariable != null) { localsMap.put(localVariable.getName(), localVariable.getValue()); } } return localsMap; }
Source:
protected Collection<String> getInAppFrames(Dsn dsn) { if (dsn.getOptions().containsKey(IN_APP_FRAMES_OPTION)) { ArrayList<String> inAppPackages = new ArrayList<>(); for (String inAppPackage : dsn.getOptions().get(IN_APP_FRAMES_OPTION).split(",")) { if (!inAppPackage.trim().equals("")) { inAppPackages.add(inAppPackage); } } return inAppPackages; } START return Collections.emptyList(); END } Stylistic nitpick: usually, in this case, I'd invert the conditional at the top and return the empty value immediately at the top of the function, rather than wrapping the bulk of the "real" code in the conditional block. (Is this not idomatic Java style?)

Target:
protected Collection<String> getInAppFrames(Dsn dsn) { if (!dsn.getOptions().containsKey(IN_APP_FRAMES_OPTION)) { return Collections.emptyList(); } ArrayList<String> inAppPackages = new ArrayList<>(); for (String inAppPackage : dsn.getOptions().get(IN_APP_FRAMES_OPTION).split(",")) { if (!inAppPackage.trim().equals("")) { inAppPackages.add(inAppPackage); } } return inAppPackages; }
Source:
public static int parseInteger(String value, int defaultValue) { if (isNullOrEmpty(value)) { return defaultValue; } try { return Integer.parseInt(value); } catch (NumberFormatException e) { START return defaultValue; END } } It'd probably be worth logging if is an invalid value rather than silently ignoring the input value.

Target:
public static int parseInteger(String value, int defaultValue) { if (isNullOrEmpty(value)) { return defaultValue; } return Integer.parseInt(value); }
Source:
public Raven createRavenInstance(Dsn dsn) { Raven raven = new Raven(); raven.setConnection(createConnection(dsn)); try { // `ServletRequestListener` was added in the Servlet 2.4 API, and // is used as part of the `HttpEventBuilderHelper`, see: // https://tomcat.apache.org/tomcat-5.5-doc/servletapi/ Class.forName("javax.servlet.ServletRequestListener", false, this.getClass().getClassLoader()); raven.addBuilderHelper(new HttpEventBuilderHelper()); START raven.addBuilderHelper(new ContextBuilderHelper(raven)); END } catch (ClassNotFoundException e) { logger.debug("The current environment doesn't provide access to servlets," + "or provides an unsupported version."); } return raven; } I don't think this needs to be in this `try`/`catch` block — shouldn't this be unrelated to the HTTP helper?

Target:
public Raven createRavenInstance(Dsn dsn) { Raven raven = new Raven(); raven.setConnection(createConnection(dsn)); try { // `ServletRequestListener` was added in the Servlet 2.4 API, and // is used as part of the `HttpEventBuilderHelper`, see: // https://tomcat.apache.org/tomcat-5.5-doc/servletapi/ Class.forName("javax.servlet.ServletRequestListener", false, this.getClass().getClassLoader()); raven.addBuilderHelper(new HttpEventBuilderHelper()); } catch (ClassNotFoundException e) { logger.debug("The current environment doesn't provide access to servlets," + "or provides an unsupported version."); } raven.addBuilderHelper(new ContextBuilderHelper(raven)); return raven; }
Source:
IngestJob(Content dataSource, List<AbstractFile> files, IngestJobSettings settings) { this.id = IngestJob.nextId.getAndIncrement(); this.ingestJobPipelines = new ConcurrentHashMap<>(); this.settings = settings; this.files = files; this.dataSources.add(dataSource); this.ingestMode = Mode.BATCH; incompleteJobsCount = new AtomicInteger(1); cancellationReason = CancellationReason.NOT_CANCELLED; START } END The first two constructors have a lot of duplicated code. Perhaps this can be reduced by having one call the other?

Target:
IngestJob(Content dataSource, List<AbstractFile> files, IngestJobSettings settings) { this(Arrays.asList(dataSource), settings); this.files.addAll(files); }
Source:
void addStreamingIngestFiles(List<Long> fileObjIds) { if (stage.equals(Stages.FIRST_STAGE_FILES_ONLY) || stage.equals(Stages.FIRST_STAGE_FILES_AND_DATASOURCE)) { START IngestJobPipeline.taskScheduler.scheduleStreamedFileIngestTasks(this, fileObjIds); END } else { logErrorMessage(Level.SEVERE, "Adding streaming files to job during stage " + stage.toString() + " not supported"); } } Stages.FIRST_STAGE_FILES_AND_DATASOURCE applies here?

Target:
void addStreamingIngestFiles(List<Long> fileObjIds) { if (stage.equals(Stages.FIRST_STAGE_FILES_ONLY)) { IngestJobPipeline.taskScheduler.scheduleStreamedFileIngestTasks(this, fileObjIds); } else { logErrorMessage(Level.SEVERE, "Adding streaming files to job during stage " + stage.toString() + " not supported"); } }
Source:
public void add(GeoLocationParseResult<T> toAdd) { START this.successfullyParsed = (this.successfullyParsed == false) END ? false : toAdd.isSuccessfullyParsed(); this.items.addAll(toAdd.getItems()); } I believed Codacy flagged this. I think this could be replaced with this.successfullyParsed &&= toAdd.isSuccessfullyParsed().

Target:
public void add(GeoLocationParseResult<T> toAdd) { this.successfullyParsed = this.successfullyParsed && toAdd.isSuccessfullyParsed(); this.items.addAll(toAdd.getItems()); }
Source:
void executeSearch() { START Collection<Persona> results = Collections.EMPTY_LIST; END try { results = Persona.getPersonaByName(searchField.getText()); } catch (CentralRepoException ex) { Exceptions.printStackTrace(ex); } updateResultsTable(results); } this method could be private

Target:
private void executeSearch() { Collection<Persona> results = Collections.EMPTY_LIST; try { results = Persona.getPersonaByName(searchField.getText()); } catch (CentralRepoException ex) { Exceptions.printStackTrace(ex); } updateResultsTable(results); }
Source:
List<String> getTypes() { List<String> types = new ArrayList(counts.keySet()); START Collections.sort(types); END return types; } This method causes several build warning.

Target:
List<String> getTypes() { List<String> types = new ArrayList<>(counts.keySet()); Collections.sort(types); return types; }
Source:
public boolean isSupported() { // get the MIME type String mimeType = file.getMIMEType(); // if it is not present, attempt to use the FileTypeDetector to determine if (StringUtils.isEmpty(mimeType)) { FileTypeDetector fileTypeDetector = null; try { fileTypeDetector = new FileTypeDetector(); } catch (FileTypeDetector.FileTypeDetectorInitException ex) { logger.log(Level.SEVERE, "Unable to create file type detector for determining MIME type."); return false; } mimeType = fileTypeDetector.getMIMEType(file); // if able to determine mime type, if (!StringUtils.isEmpty(mimeType)) file.setMIMEType(mimeType); START } END return PLAIN_TEXT_MIME_TYPE.equals(mimeType); } Let's just remove the call, thanks.

Target:
public boolean isSupported() { // get the MIME type String mimeType = file.getMIMEType(); // if it is not present, attempt to use the FileTypeDetector to determine if (StringUtils.isEmpty(mimeType)) { FileTypeDetector fileTypeDetector = null; try { fileTypeDetector = new FileTypeDetector(); } catch (FileTypeDetector.FileTypeDetectorInitException ex) { logger.log(Level.SEVERE, "Unable to create file type detector for determining MIME type."); return false; } mimeType = fileTypeDetector.getMIMEType(file); } return PLAIN_TEXT_MIME_TYPE.equals(mimeType); }
Source:
START public WrapLayoutRow(List<Component> components, List<Component> oppositeAligned, int height, int width) { END this.components = components; this.oppositeAligned = oppositeAligned; this.height = height; this.width = width; } public constructor in private class should be package level constructor.

Target:
WrapLayoutRow(List<Component> components, List<Component> oppositeAligned, int height, int width) { this.components = components; this.oppositeAligned = oppositeAligned; this.height = height; this.width = width; }
Source:
protected void addOriginalNameProp(Sheet.Set properties) { if (TextTranslationService.getInstance().hasProvider() && UserPreferences.displayTranslatedFileNames()) { properties.put(new NodeProperty<>( ORIG_NAME_PROP_NAME, ORIG_NAME_PROP_DISPLAY_NAME, "", START translatedName != null ? translatedName : "")); END if (translatedName == null) { new FileNameTransTask(originalName, this, new NameTranslationListener()).submit(); } } } This is the wrong substitution if translatedName is not null.

Target:
protected void addOriginalNameProp(Sheet.Set properties) { if (TextTranslationService.getInstance().hasProvider() && UserPreferences.displayTranslatedFileNames()) { properties.put(new NodeProperty<>( ORIG_NAME_PROP_NAME, ORIG_NAME_PROP_DISPLAY_NAME, "", translatedName != null ? originalName : "")); if (translatedName == null) { new FileNameTransTask(originalName, this, new NameTranslationListener()).submit(); } } }
Source:
START public void setAccountId(Long accountId) { END this.accountId = accountId; } Is a public setter necessary? Can the abstraction be the CentralRepositoryAccount instance itself, rather than the primitive?

Target:
void setAccountId(Long accountId) { this.accountId = accountId; }
Source:
START public XRYKeyValuePair(String key, String value, String namespace) { END this.key = key.trim(); this.value = value.trim(); this.namespace = namespace.trim(); } public constructor in non-public class

Target:
XRYKeyValuePair(String key, String value, String namespace) { this.key = key.trim(); this.value = value.trim(); this.namespace = namespace.trim(); }
Source:
public String getItemType() { START return DisplayableItemNode.FILE_PARENT_NODE_KEY; END } This node can't be a file parent, so it should have its own key.

Target:
public String getItemType() { return getClass().getName(); }
Source:
START public static XRYFileParser get(String reportType) { END if (reportType == null) { throw new IllegalArgumentException("Report type cannot be null"); } switch (reportType.toLowerCase()) { case "calls": return new XRYCallsFileParser(); case "contacts/contacts": return new XRYContactsFileParser(); case "device/general information": return new XRYDeviceGenInfoFileParser(); case "messages/sms": return new XRYMessagesFileParser(); case "web/bookmarks": return new XRYWebBookmarksFileParser(); default: throw new IllegalArgumentException(reportType + " not recognized."); } } Public methods on package access classes seem a little strange to me.

Target:
static XRYFileParser get(String reportType) { if (reportType == null) { throw new IllegalArgumentException("Report type cannot be null"); } switch (reportType.trim().toLowerCase()) { case "calls": return new XRYCallsFileParser(); case "contacts/contacts": return new XRYContactsFileParser(); case "device/general information": return new XRYDeviceGenInfoFileParser(); case "messages/sms": return new XRYMessagesFileParser(); case "web/bookmarks": return new XRYWebBookmarksFileParser(); default: throw new IllegalArgumentException(reportType + " not recognized."); } }
Source:
static void writeModel(NaiveBayesModel model) throws IOException { ensureTextClassifierFolderExists(); START FileWriter fw = new FileWriter(new File(MODEL_PATH)); END PlainTextNaiveBayesModelWriter modelWriter; modelWriter = new PlainTextNaiveBayesModelWriter(model, new BufferedWriter(fw)); modelWriter.persist(); fw.close(); } When this throws an exception the file writer may not get closed, consider a try with resources.

Target:
static void writeModel(NaiveBayesModel model) throws IOException { ensureTextClassifierFolderExists(); try (FileWriter fw = new FileWriter(new File(MODEL_PATH))) { PlainTextNaiveBayesModelWriter modelWriter; modelWriter = new PlainTextNaiveBayesModelWriter(model, new BufferedWriter(fw)); modelWriter.persist(); } }
Source:
public ResultSet runQuery(String queryStr) throws TskCoreException { ResultSet resultSet = null; try { resultSet = statement.executeQuery(queryStr); //NON-NLS } catch (SQLException ex) { START throw new TskCoreException("Error running app SQLite query. " + ex.getMessage(), ex); END } return resultSet; } Why wrap into a TskCoreException? The query is not run on the case database. Furthermore, the client will need to catch a SQLException anyway in order to interact with the ResultSet.

Target:
public ResultSet runQuery(String queryStr) throws SQLException { ResultSet resultSet = null; if (null != queryStr) { resultSet = statement.executeQuery(queryStr); //NON-NLS } return resultSet; }
Source:
void nextPage() { currentPage++; START DataResultViewerTable.this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); END postPageChangeEvent(); DataResultViewerTable.this.setCursor(null); } But that has nothing to do with logical imager cancellation and shouldn't be in this PR.

Target:
void nextPage() { currentPage++; postPageChangeEvent(); }
Source:
public void cancel() { if (addLogicalImageTask != null) { START thread.interrupt(); END addLogicalImageTask.cancelTask(); } } Is this still necessary? And saving the thread in general?

Target:
public void cancel() { if (addLogicalImageTask != null) { addLogicalImageTask.cancelTask(); } }
Source:
START public int size() { END return items.size(); } does not need to be public in non-public class

Target:
int size() { return items.size(); }
Source:
START public static String getTextClassifierPath() { END return getUserDirectory().getAbsolutePath() + File.separator + TEXT_CLASSIFIERS_SUBDIRECTORY; } does not need to be public in non-public class

Target:
static String getTextClassifierPath() { return getUserDirectory().getAbsolutePath() + File.separator + TEXT_CLASSIFIERS_SUBDIRECTORY; }
Source:
public void updateStatusLabel(String statusMessage) { if (status != ReportStatus.CANCELED) { START logger.log(Level.INFO, "Report Progress Logger status update: {0}", statusMessage); END } } I don't think that "Report Progress Logger status update:" will add anything to the logs, which will tell us the call site of the message. Logging the message from the report module should be sufficient.

Target:
public void updateStatusLabel(String statusMessage) { if (status != ReportStatus.CANCELED) { logger.log(Level.INFO, statusMessage); } }
Source:
START public GetSCOTask(WeakReference<AbstractContentNode<?>> weakContentRef, PropertyChangeListener listener) { END this.weakNodeRef = weakContentRef; this.listener = listener; } public in non-public class, can have public removed

Target:
GetSCOTask(WeakReference<AbstractContentNode<?>> weakContentRef, PropertyChangeListener listener) { this.weakNodeRef = weakContentRef; this.listener = listener; }
Source:
private void deleteDataSource(Long dsObjId) { String dataSourceId = Long.toString(dsObjId); String deleteQuery = "image_id:" + dataSourceId; try { // Get the first result. UpdateResponse updateResponse = solrCore.deleteByQuery(deleteQuery); } catch (SolrServerException | IOException ex) { START logger.log(Level.SEVERE, "Error deleting content from Solr. Solr image id " + dataSourceId, ex); //NON-NLS END } } As above for the DeleteDataSourceAction, low level classes should propagate exceptions for handling by the top level classes. E.g., here, how does the Server know what the performAction needs to do in its context of a menu selection in the UI by a user? These exceptions should propagate to the public deleteDataSource method above, which should propagate all errors, and so on, up the chain. The exceptions can be wrapped in other exceptions as needed.

Target:
private void deleteDataSource(Long dsObjId) throws IOException, SolrServerException { String dataSourceId = Long.toString(dsObjId); String deleteQuery = "image_id:" + dataSourceId; solrCore.deleteByQuery(deleteQuery); }
Source:
START int getZoneId() { END int zoneValue = -1; String value = dataMap.get(ZONE_ID); if (value != null) { zoneValue = Integer.parseInt(value); } return zoneValue; } ZoneIdentifierInfo is a private inner class so this point is debatable, but codacy suggests all the accessor methods of ZoneIdentifierInfo should also be private.

Target:
private int getZoneId() { int zoneValue = -1; String value = properties.getProperty(ZONE_ID); if (value != null) { zoneValue = Integer.parseInt(value); } return zoneValue; }
Source:
public void setFile(AbstractFile file) { WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); START abstractFile = file; END htmlPanel.setHtmlText(getHtmlText(file)); WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } variable named abstractFile does not exist, which prevents pr from building

Target:
public void setFile(AbstractFile file) { WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); htmlPanel.setHtmlText(getHtmlText(file)); WindowManager.getDefault().getMainWindow().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); }
Source:
private void init() { getRootPane().registerKeyboardAction( action -> { setVisible(false); }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), START JComponent.WHEN_IN_FOCUSED_WINDOW); END multiUserCasesPanel = new OpenMultiUserCasePanel(this); add(multiUserCasesPanel); pack(); setResizable(false); } Hitting ESC doesn't seem to do anything for me

Target:
private void init() { multiUserCasesPanel = new OpenMultiUserCasePanel(this); add(multiUserCasesPanel); pack(); setResizable(false); }
Source:
synchronized private void shutDownDBExecutor() { if (dbExecutor != null) { dbExecutor.shutdownNow(); try { dbExecutor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException ex) { logger.log(Level.WARNING, "Image Gallery failed to shutdown DB Task Executor in a timely fashion.", ex); } START dbExecutor = null; END } } is it necessary to null out dbExecutor? Won't it be garbage collected when the enclosing ImageGalleryController is garbage collected?

Target:
synchronized private void shutDownDBExecutor() { dbExecutor.shutdownNow(); try { dbExecutor.awaitTermination(30, TimeUnit.SECONDS); } catch (InterruptedException ex) { logger.log(Level.WARNING, "Image Gallery failed to shutdown DB Task Executor in a timely fashion.", ex); } }
Source:
public EventAddedEvent(org.sleuthkit.datamodel.TimelineManager.EventAddedEvent event) { super(Case.Events.EVENT_ADDED.name(), null, event.getAddedEvent().getEventID()); START addedEvent = event.getAddedEvent(); END addedEventID = addedEvent.getEventID(); } It seems like passing the event id to the super class constructor and also making it a field might be a little confusing. Personally, I prefer the approach used in DataSourceAddedEvent where the id of the object is obtained in getNewValue via long id = (Long) super.getNewValue() and the "extra" field is not required. Thoughts?

Target:
public EventAddedEvent(org.sleuthkit.datamodel.TimelineManager.EventAddedEvent event) { super(Case.Events.EVENT_ADDED.name(), null, event.getAddedEvent().getEventID()); addedEvent = event.getAddedEvent(); }
Source:
private void syncGroupControlsEnabledState(GroupViewState newViewState) { START boolean noGroupSelected = newViewState == null || newViewState.getGroup() == null; END tagGroupMenuButton.setDisable(noGroupSelected); catGroupMenuButton.setDisable(noGroupSelected); } I'd put these booleans into parentheses for easier reading.

Target:
private void syncGroupControlsEnabledState(GroupViewState newViewState) { boolean noGroupSelected = (null == newViewState) || (null == newViewState.getGroup()); tagGroupMenuButton.setDisable(noGroupSelected); catGroupMenuButton.setDisable(noGroupSelected); }
Source:
START void setTaskCompletionStatus(boolean status) { END taskCompletionStatus = status; } I think this should be protected, not package access.

Target:
protected void setTaskCompletionStatus(boolean status) { taskCompletionStatus = status; }
Source:
START boolean isFlaggedAsZipBomb() { END return flaggedAsZipBomb; } Are there any multithreading issues here? Can two threads be accessing the same root Archive object?

Target:
synchronized boolean isFlaggedAsZipBomb() { return flaggedAsZipBomb; }
Source:
START Keyword(String searchTerm, boolean isLiteral, boolean isWholeWord) { END this.searchTerm = Normalizer.normalize(searchTerm, Normalizer.Form.NFKD);; this.isLiteral = isLiteral; this.isWholeWord = isWholeWord; this.listName = ""; this.originalTerm = searchTerm; } Can you have this constructor call the 5 parameter one instead of it assigning the values?

Target:
Keyword(String searchTerm, boolean isLiteral, boolean isWholeWord) { this(searchTerm, isLiteral, isWholeWord, "", searchTerm); }
Source:
START private AddEditCentralRepoCommentAction(AbstractFile file, String title) throws EamDbException, NoCurrentCaseException, TskCoreException { END super(title); this.title = title; correlationAttribute = EamArtifactUtil.getCorrelationAttributeFromContent(file); if (correlationAttribute == null) { addToDatabase = true; correlationAttribute = EamArtifactUtil.makeCorrelationAttributeFromContent(file); } } Looking at this again, I don't think anything in here actually throws an exception and you can get rid of the entire "throws" part. This should allow you to remove the exception handling from createAddEditCentralRepoCommentAction, and possibly get rid of the new exception class if it isn't used anywhere else.

Target:
private AddEditCentralRepoCommentAction(AbstractFile file, String title) { super(title); this.title = title; correlationAttribute = EamArtifactUtil.getCorrelationAttributeFromContent(file); if (correlationAttribute == null) { addToDatabase = true; correlationAttribute = EamArtifactUtil.makeCorrelationAttributeFromContent(file); } }
Source:
} catch (UnsatisfiedLinkError e) { tempOpenCvLoaded = false; START System.out.println("OpenCV native library failed to load " + e.toString()); END } Leftover debug line - edit not leftover, it's just that the logger is not available. Suggested saving the error string to display when creating the exception a few lines down.

Target:
} catch (UnsatisfiedLinkError e) { tempOpenCvLoaded = false; exception = e; //save relevant error for throwing at appropriate time }
Source:
public void tearDown() { try { Case.closeCurrentCase(); //Seems like we need some time to close the case. try { Thread.sleep(2000); } catch (InterruptedException ex) { } START FileUtils.deleteDirectory(CASE_DIR); END } catch (CaseActionException | IOException ex) { Exceptions.printStackTrace(ex); } assertFalse(CASE_DIR.exists()); } This delete frequently fails (it worked a few times but is failing consistantly now for me) to delete the case dir in User\AppData\Local\Temp causing the test to fail.

Target:
public void tearDown() { try { Case.closeCurrentCase(); } catch (CaseActionException ex) { Exceptions.printStackTrace(ex); } }
Source:
CommonFilesSearchNode(CommonFilesMetaData metaData) { super(Children.create(new CommonFilesChildren(metaData), true), Lookups.singleton(metaData)); START children = this.getChildren(); END } We don't need it.

Target:
CommonFilesSearchNode(CommonFilesMetaData metaData) { super(Children.create(new CommonFilesChildren(metaData), true), Lookups.singleton(metaData)); }
Source:
public static Case getOpenCase() throws NoCurrentCaseException { try { Case openCase = new Case(currentCase.getCaseType(), currentCase.getCacheDirectory(), new CaseDetails(currentCase.getDisplayName(), currentCase.getNumber(), currentCase.getExaminer(), currentCase.getExaminerPhone(), currentCase.getExaminerEmail(), currentCase.getCaseNotes())); START return openCase; END } catch (NullPointerException ex) { throw new NoCurrentCaseException(); } } For this fix, we should be making a local copy of the reference in currentCase, checking the local reference for null, and finally returning the local reference. This does not prevent another thread from closing the case, but it does make things a bit better because we will at least not risk returning null and violating the contract of the method. Dealing with the possibility of the current case being closed while other objects have a reference to it is a much bigger problem for another story.

Target:
public static Case getOpenCase() throws NoCurrentCaseException { Case openCase = currentCase; if (null != openCase) { return openCase; } else { throw new NoCurrentCaseException(); } }
Source:
public PListViewer() { // Create an Outlineview and add to the panel outlineView = new org.openide.explorer.view.OutlineView(); initComponents(); outline = outlineView.getOutline(); ((DefaultOutlineModel) outline.getOutlineModel()).setNodesColumnLabel("Key"); Bundle.PListNode_KeyCol(); START outlineView.setPropertyColumns( END "Type", Bundle.PListNode_TypeCol(), "Value", Bundle.PListNode_ValueCol()); customize(); } Looks for me this line is an extra: Bundle.PListNode_KeyCol();

Target:
public PListViewer() { // Create an Outlineview and add to the panel outlineView = new org.openide.explorer.view.OutlineView(); initComponents(); outline = outlineView.getOutline(); ((DefaultOutlineModel) outline.getOutlineModel()).setNodesColumnLabel("Key"); outlineView.setPropertyColumns( "Type", Bundle.PListNode_TypeCol(), "Value", Bundle.PListNode_ValueCol()); customize(); }
Source:
private ContentViewer getSupportingViewer(String mimeType) { START return mimeTypeToViewerMap.containsKey(mimeType) ? mimeTypeToViewerMap.get(mimeType) : null; END } Map.get(key) already returns null if he key is not contained in the map.

Target:
private ContentViewer getSupportingViewer(String mimeType) { return mimeTypeToViewerMap.get(mimeType); }
Source:
public synchronized TagName addTagName(String displayName, String description, TagName.HTML_COLOR color) throws TagNameAlreadyExistsException, TskCoreException { TskData.FileKnown knownStatus = TskData.FileKnown.UNKNOWN; if (getNotableTagDisplayNames().contains(displayName)) { knownStatus = TskData.FileKnown.BAD; } START return addTagName(displayName, description, color, knownStatus); END } Let's just go ahead and pass unknown to the four args method, I think it will be a tad simpler.

Target:
public synchronized TagName addTagName(String displayName, String description, TagName.HTML_COLOR color) throws TagNameAlreadyExistsException, TskCoreException { return addTagName(displayName, description, color, knownStatus,TskData.FileKnown.UNKNOWN); }
Source:
public void setup() throws Exception { START System.setProperty("java.naming.factory.initial", "org.osjava.sj.SimpleContextFactory"); END System.setProperty("org.osjava.sj.root", "file://src/test/resources"); System.setProperty("org.osjava.sj.delimiter", "."); System.setProperty("jndi.syntax.separator", "/"); System.setProperty("org.osjava.sj.space", "java:/comp/env"); this.initContext = new InitialContext(); } If we are going to use System properties shouldn't we reset them when the test tears down? We don't want any unexpected side effects when other tests run.

Target:
public void setup() throws Exception { this.initContext = new InitialContext(); }
Source:
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { START if (((String)key).length() % 2 == 0) return 0; END return 1; } use of braces is generally considered a best practice in this situation, even though not required by the language

Target:
public int partition(String topic, Object key, byte[] keyBytes, Object value, byte[] valueBytes, Cluster cluster) { if (((String) key).length() % 2 == 0) { return 0; } return 1; }
Source:
public void whenSerializingJava8DateAndReadingValue_thenCorrect() throws IOException { final String stringDate = "\"2014-12-20\""; final ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); final String result2 = mapper.readValue(stringDate, LocalDate.class) START .toString(); END assertThat(result2, containsString("2014-12-20")); } This is an odd way to test serialization: load it into an object and then do `toString` on that object. Can we not assert the fields of the LocalDate object? At a glance, this just looks like string processing, even though there's a date object in the middle.

Target:
public void whenSerializingJava8DateAndReadingValue_thenCorrect() throws IOException { String stringDate = "\"2014-12-20\""; ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); LocalDate result = mapper.readValue(stringDate, LocalDate.class); assertThat(result.toString(), containsString("2014-12-20")); }
Source:
public Future<Response> apply(Request request, Service<Request, Response> service) { System.out.println("Request host:" + request.host().getOrElse(() -> "")); START System.out.println("Request params:"); END request.getParams().forEach(entry -> System.out.println("\t" + entry.getKey() + " : " + entry.getValue())); return service.apply(request); } if the stdouts are irrelevant let's remove them

Target:
public Future<Response> apply(Request request, Service<Request, Response> service) { logger.info("Request host:" + request.host().getOrElse(() -> "")); logger.info("Request params:"); request.getParams().forEach(entry -> logger.info("\t" + entry.getKey() + " : " + entry.getValue())); return service.apply(request); }
Source:
protected void configure(HttpSecurity http) throws Exception { http.httpBasic() .and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/user/**") .hasRole("USER") .and() .logout() .logoutUrl("/user/logout") .addLogoutHandler(logoutHandler) START .logoutSuccessHandler((new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK))) END .permitAll() .and() .csrf() .disable() .formLogin() .disable(); } Hey @kirill-vlasov - sorry to be picky but seems to be an extra set of brackets here?

Target:
protected void configure(HttpSecurity http) throws Exception { http.httpBasic() .and() .authorizeRequests() .antMatchers(HttpMethod.GET, "/user/**") .hasRole("USER") .and() .logout() .logoutUrl("/user/logout") .addLogoutHandler(logoutHandler) .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK)) .permitAll() .and() .csrf() .disable() .formLogin() .disable(); }
Source:
protected IDataSet getDataSet() throws Exception { START try (java.io.InputStream resourceAsStream = getClass() END .getClassLoader() .getResourceAsStream("dbunit/data.xml")) { return new FlatXmlDataSetBuilder().build(resourceAsStream); } } let's use imports on this one and the following

Target:
protected IDataSet getDataSet() throws Exception { try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { return new FlatXmlDataSetBuilder().build(resourceAsStream); } }
Source:
START @Override protected javax.sql.DataSource getDataSource() { END JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(JDBC_URL); dataSource.setUser("sa"); dataSource.setPassword(""); return dataSource; } why? let's format it properly, it was ok before. annotations and method definitions on different lines

Target:
protected DataSource getDataSource() { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(JDBC_URL); dataSource.setUser("sa"); dataSource.setPassword(""); return dataSource; }
Source:
public void shouldNotTimeout() { try { WebTestClient.ResponseSpec response = webTestClient.get() .uri("/timeout/{timeout}", 1) .exchange(); response.expectStatus() .isOk() .expectBody(String.class) .isEqualTo("OK"); START } catch (ReadTimeoutException e) { END Assert.fail(); } } I would remove this since the exception fails the test, and it's better to have that reported then to hide it

Target:
public void shouldNotTimeout() { WebTestClient.ResponseSpec response = webTestClient.get() .uri("/timeout/{timeout}", 1) .exchange(); response.expectStatus() .isOk() .expectBody(String.class) .isEqualTo("OK"); }
Source:
public void shouldTimeout() { exception.expect(ReadTimeoutException.class); webTestClient.get() .uri("/timeout/{timeout}", 3) .exchange(); START Assert.fail(); END } this can now be removed because if the exception is not thrown, JUnit it will fail it since it was expecting it

Target:
public void shouldTimeout() { exception.expect(ReadTimeoutException.class); webTestClient.get() .uri("/timeout/{timeout}", 3) .exchange(); }
Source:
protected Supplier<?> putSupplier(Map<String,String> map, int key) { return (()-> { try { lock.lock(); map.put("key" + key, "value" + key); } catch (Exception e) { START this.putSupplier(map, key); END } finally { try { lock.unlock(); } catch (Exception e) } return null; }); } Wouldn't this be an infinite loop? Seems risky to just infinitely try again. I'd recommend doing: ```java lock.lock(); try { return map.put("key" + key, "value" + key); } finally { lock.unlock(); } ``` This is what the JavaDoc recommends. Also, if you return the result of `map.put`, then you don't need the extra `return null;` at the bottom.

Target:
protected Supplier<?> putSupplier(Map<String,String> map, int key) { return (()-> { lock.lock(); try { return map.put("key" + key, "value" + key); } finally { lock.unlock(); } }); }
Source:
public Credentials convert(String source) { START String data[] = source.split(","); END return new Credentials(data[0], data[1]); } Typically we would put Array designators "[]" on the type, not the variable.

Target:
public Credentials convert(String source) { String[] data = source.split(","); return new Credentials(data[0], data[1]); }
Source:
public void whenConsumeWithJsonb_thenGetPerson() { String url = BASE_URL + API_PERSON + "/1"; String result = RestConsumer.consumeWithJsonb(url); Person person = JsonbBuilder.create().fromJson(result, Person.class); assertEquals(person.getId(), 1); assertEquals(person.getUsername(), "normanlewis"); START assertEquals(person.getEmail(), "normanlewis@email.com"); END } Switch the order of the arguments. assertEquals(expected, actual) assertEquals(1, person.getId()); assertEquals("normanlewis", person.getUsername()); assertEquals("normanlewis@email.com", person.getEmail());

Target:
public void whenConsumeWithJsonb_thenGetPerson() { String url = BASE_URL + API_PERSON + "/1"; String result = RestConsumer.consumeWithJsonb(url); Person person = JsonbBuilder.create().fromJson(result, Person.class); assertEquals(1, person.getId()); assertEquals("normanlewis", person.getUsername()); assertEquals("normanlewis@email.com", person.getEmail()); }
Source:
public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() { var me = 4; var operation = "squareMe"; var result = switch (operation) { case "doubleMe" -> { yield me * 2; } case "squareMe" -> { yield me * me; } default -> me; }; START assertEquals(result, 16); END } ```suggestion assertEquals(16, result); ```

Target:
public void whenSwitchingOnOperationSquareMe_thenWillReturnSquare() { var me = 4; var operation = "squareMe"; var result = switch (operation) { case "doubleMe" -> { yield me * 2; } case "squareMe" -> { yield me * me; } default -> me; }; assertEquals(16, result); }
Source:
START @Override protected Application provideApplication() { END return new GuiceApplicationBuilder().build(); } Usually `@Override` is on the line before the function

Target:
protected Application provideApplication() { return new GuiceApplicationBuilder().build(); }
Source:
public void traverseList() { // Start traversing from the head Node currentNode = head; if (head != null) { do { START System.out.print(currentNode.value + " "); END currentNode = currentNode.nextNode; } while (currentNode != head); } } Avoid calls to System.out... and use a proper logger.

Target:
public void traverseList() { Node currentNode = head; if (head != null) { do { LOGGER.info(currentNode.value + " "); currentNode = currentNode.nextNode; } while (currentNode != head); } }
Source:
public void resetPrintHistory() { for (Vertex vertex : graph) { START Iterator it = vertex.getEdges() .entrySet() .iterator(); while (it.hasNext()) { Map.Entry pair = (Map.Entry) it.next(); ((Edge) pair.getValue()).setPrinted(false); } END } } Couldn't we use a typed Iterator here so that we don't have to do the casting inside the loop?

Target:
public void resetPrintHistory(){ for (Vertex vertex : graph){ Iterator<Map.Entry<Vertex,Edge>> it = vertex.getEdges().entrySet().iterator(); while (it.hasNext()) { Map.Entry<Vertex,Edge> pair = it.next(); pair.getValue().setPrinted(false); } } }
Source:
public String getSuccess(HttpServletRequest request) { START java.util.Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); END if (inputFlashMap != null) { Poem poem = (Poem) inputFlashMap.get("poem"); return "success"; } else { return "redirect:/poem/submit"; } } Couldn't we just import java.util.Map so that we don't have to fully qualify it here?

Target:
public String getSuccess(HttpServletRequest request) { Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); if (inputFlashMap != null) { Poem poem = (Poem) inputFlashMap.get("poem"); return "success"; } else { return "redirect:/poem/submit"; } }
Source:
public void someUnitTest() { START assertTrue(this::doSomething); END } This seems needlessly complex. You're using a boolean supplier to `assertTrue`. Why not just call `doSomething()` directly?

Target:
void someUnitTest() { assertTrue(doSomething()); }
Source:
private void discardEntity(HttpResponse httpResponse, Materializer materializer) { START final HttpMessage.DiscardedEntity discarded = httpResponse.discardEntityBytes(materializer); END discarded.completionStage() .whenComplete((done, ex) -> log.info("Entity discarded completely!")); } Do we need the `discarded` temp variable ? Can we not just call fluently from `httpResponse.discardEntityBytes(...)`?

Target:
private void discardEntity(HttpResponse httpResponse, Materializer materializer) { httpResponse.discardEntityBytes(materializer) .completionStage() .whenComplete((done, ex) -> log.info("Entity discarded completely!")); }
Source:
private boolean isCounterUpdateRequired(NotificationCache nCache) { START if (new Date().getTime() - nCache.getLastCounterUpdate().getTime() > COUNTER_UPDATE_INTERVAL_IN_MS) { return true; } else { return false; } END } Yes, I will change it.

Target:
private boolean isCounterUpdateRequired(NotificationCache nCache) { return new Date().getTime() - nCache.getLastCounterUpdate().getTime() > COUNTER_UPDATE_INTERVAL_IN_MS; }
Source:
public void testLoadingDefaultPropertiesFile() throws IOException { reader.loadDefaultPropertyFile(DEFAULT_PROPERTIES_FILE, topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); for (final Map.Entry<Object, Object> e : topologyProperties.entrySet()) { START assertNotNull(e.getKey()); END } } What is the idea behind checking whether all the keys in the map are not null? This applies to all tests here...

Target:
public void testLoadingDefaultPropertiesFile() throws IOException { reader.loadDefaultPropertyFile(DEFAULT_PROPERTIES_FILE, topologyProperties); assertNotNull(topologyProperties); assertFalse(topologyProperties.isEmpty()); }
Source:
public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { File file = new File(fileName); START FileInputStream fileInput = new FileInputStream(file); END topologyProperties.load(fileInput); fileInput.close(); } Instead of creating a File object you can use another FileInputStream constructor that accepts file name.

Target:
public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { FileInputStream fileInput = new FileInputStream(fileName); topologyProperties.load(fileInput); fileInput.close(); }
Source:
private List<Revision> getRevisions(String cloudId, String representationName) throws MCSException { START Representation representation = sourceRecordServiceClient.getRepresentation(cloudId, representationName); END return representation.getRevisions(); } no need to create representation variable

Target:
private List<Revision> getRevisions(String cloudId, String representationName) throws MCSException { return sourceRecordServiceClient.getRepresentation(cloudId, representationName).getRevisions(); }
Source:
private List<CloudIdAndTimestampResponse> intersectCloudIdAndTimestampResponsesBasedOnCloudId(List<CloudIdAndTimestampResponse> dereferenceCloudIdAndTimestampResponseList, List<CloudIdAndTimestampResponse> publishedCloudIdAndTimestampResponseList) { List<CloudIdAndTimestampResponse> intesectCloudIds = new ArrayList<>(); for (CloudIdAndTimestampResponse dereferenceCloudIdAndTimestamp : dereferenceCloudIdAndTimestampResponseList) { String dereferenceCloudId = dereferenceCloudIdAndTimestamp.getCloudId(); for (CloudIdAndTimestampResponse publishedCloudIdAndTimestamp : publishedCloudIdAndTimestampResponseList) { START String publishCloudId = publishedCloudIdAndTimestamp.getCloudId(); END if (dereferenceCloudId.equals(publishCloudId)) { intesectCloudIds.add(dereferenceCloudIdAndTimestamp); } } } return intesectCloudIds; } No need to create a variable when it's used once.

Target:
private List<CloudIdAndTimestampResponse> intersectCloudIdAndTimestampResponsesBasedOnCloudId(List<CloudIdAndTimestampResponse> dereferenceCloudIdAndTimestampResponseList, List<CloudIdAndTimestampResponse> publishedCloudIdAndTimestampResponseList) { List<CloudIdAndTimestampResponse> intesectCloudIds = new ArrayList<>(); for (CloudIdAndTimestampResponse dereferenceCloudIdAndTimestamp : dereferenceCloudIdAndTimestampResponseList) { String dereferenceCloudId = dereferenceCloudIdAndTimestamp.getCloudId(); for (CloudIdAndTimestampResponse publishedCloudIdAndTimestamp : publishedCloudIdAndTimestampResponseList) { if (dereferenceCloudId.equals(publishedCloudIdAndTimestamp.getCloudId())) { intesectCloudIds.add(dereferenceCloudIdAndTimestamp); } } } return intesectCloudIds; }
Source:
public static MediaType detectMediaType(InputStream inputStream) throws IOException { if (!inputStream.markSupported()) throw new UnsupportedOperationException("InputStream marking support is required!"); Detector detector = new AutoDetectParser().getDetector(); START return detector.detect(inputStream, new Metadata()); END } You can skip storing detector in a variable and call return new AutoDetectParser().getDetector().detect(inputStream, new Metadata());

Target:
public static MediaType detectMediaType(InputStream inputStream) throws IOException { if (!inputStream.markSupported()) throw new UnsupportedOperationException("InputStream marking support is required!"); return new AutoDetectParser().getDetector().detect(inputStream, new Metadata()); }
Source:
private void createProviderIdIfNotExists(UISClient uisClient, String providerId) throws CloudException { try { uisClient.getDataProvider(providerId); START LOGGER.info("A provider already existed " + providerId); END } catch (Exception e) { DataProviderProperties dataProviderProperties = new DataProviderProperties(); uisClient.createProvider(providerId, dataProviderProperties); LOGGER.info("A new provider is created " + providerId); } } Is it really needed to log information like this? In my opinion it's not that useful information to log it on info level.

Target:
private void createProviderIdIfNotExists(UISClient uisClient, String providerId) throws CloudException { try { uisClient.getDataProvider(providerId); } catch (Exception e) { DataProviderProperties dataProviderProperties = new DataProviderProperties(); uisClient.createProvider(providerId, dataProviderProperties); } }
Source:
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { START this(poolConfig, uri, timeout, timeout); END } It is not clear to me why you are not passing the SSL context to the constructor. *(even of the test pass in my environment, it looks odd to me..)

Target:
public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { this(poolConfig, uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier); }
Source:
public void clientIdmultipleConnection() { Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); client2.auth("foobared"); client2.clientSetname("fancy_jedis_another_name"); long clientId1 = client.clientId(); long clientId2 = client2.clientId(); ///client-id is monotonically increasing START Assert.assertTrue(clientId1 < clientId2); END client2.close(); } ```suggestion assertTrue(clientId1 < clientId2); ```

Target:
public void clientIdmultipleConnection() { Jedis client2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); client2.auth("foobared"); client2.clientSetname("fancy_jedis_another_name"); long clientId1 = client.clientId(); long clientId2 = client2.clientId(); ///client-id is monotonically increasing assertTrue(clientId1 < clientId2); client2.close(); }
Source:
public StreamConsumersInfo(Map<String,Object> map) { if (map!= null && map.size()>0) { consumerInfo = map; name = (String) map.get(NAME); idle = (long) map.get(IDLE); pending = (long) map.get(PENDING); START } else throw new IllegalArgumentException(); END } If we are throwing runtime exception anyway when map is null isn't it better to just let it throw NullPointerException?

Target:
public StreamConsumersInfo(Map<String,Object> map) { consumerInfo = map; name = (String) map.get(NAME); idle = (long) map.get(IDLE); pending = (long) map.get(PENDING); }
Source:
public JedisSentinelPool(String masterName, Set<String> sentinels, final GenericObjectPoolConfig poolConfig, final int timeout, final int soTimeout, final String password, final int database, final Boolean isRedisSslEnabled) { START this(masterName, sentinels, poolConfig, timeout, soTimeout, password, database, null, isRedisSslEnabled); END } Don't you think there's a need to add a constructor with `final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier`

Target:
public JedisSentinelPool(String masterName, Set<String> sentinels, final GenericObjectPoolConfig poolConfig, final int timeout, final int soTimeout, final String password, final int database, final Boolean isRedisSslEnabled) { this(masterName, sentinels, poolConfig, timeout, soTimeout, password, database, null, isRedisSslEnabled, null, null, null); }
Source:
public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, int timeout) { START this(poolConfig, timeout, timeout, null, null, false, null, null, null, null); END } This won't not be required if following constructor is kept.

Target:
public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, int timeout) { this(poolConfig, timeout, timeout, null, null); }