auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<String, Long> getGroupCount(@QueryParam("search") String search, @QueryParam("top") @DefaultValue("false") boolean onlyTopGroups) { List<GroupModel> results; Map<String, Long> map = new HashMap<>(); if (Objects.nonNull(search)) { <START> results = realm.searchForGroupByName(search, null, null); <END> } else { results = realm.getTopLevelGroups(); } Long count = results.stream() .filter(group -> auth.groups().canView(group)) .count(); map.put("count", count); return map; }</code><technical_language>This is potential performance killer, I idea address this. I assume need live that. Fortunately thousands of groups (not millions) is admin requests, is ok. IMO in general, is pagination approach, require counts. Something, returns token for next page? this approach limitations (EG. is easily move exact page "Go page 50" etc), other limitations. consider in design of new REST API (CC @pedroigor ). for hijack PR :)</technical_language>

Target:
public Map<String, Long> getGroupCount(@QueryParam("search") String search, @QueryParam("top") @DefaultValue("false") boolean onlyTopGroups) { Long results; Map<String, Long> map = new HashMap<>(); if (auth.users().canView()) { if (Objects.nonNull(search)) { results = realm.getGroupsCountByNameContaining(search); } else { results = realm.getGroupsCount(onlyTopGroups); } } else { Set<String> groups = auth.groups().getGroupsWithViewPermission(); Stream<String> s = groups.stream(); if (search!=null) s=s.filter(group->group.contains(search.trim())); results = s.count(); } map.put("count", results); return map; }
Source:
<code>private void registerPushResources(Bundle pushBundle) { <START> Hashtable<String, Object> properties = new Hashtable<>(); <END> properties.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/VAADIN/static/push/*"); servletRegistration.compareAndSet(null, pushBundle.getBundleContext().registerService(Servlet.class, new PushResourceServlet(pushBundle), properties)); }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') Replace synchronized class "Hashtable" unsynchronized "HashMap". [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private void registerPushResources(Bundle pushBundle) { Hashtable<String, Object> properties = new Hashtable<>(); properties.put("osgi.http.whiteboard.servlet.pattern", "/VAADIN/static/push/*"); servletPushRegistration.compareAndSet(null, pushBundle.getBundleContext().registerService(Servlet.class, new ResourceServlet(pushBundle, "/META-INF/resources/VAADIN/static/push"), properties)); }
Source:
<code>protected void configure() { install(new ChristianModule()); install(new ChristopherModule()); install(new JasonModule()); install(new JoelModule()); install(new LarryModule()); install(new ManonModule()); install(new MaximeModule()); install(new PhilippeaModule()); install(new PhilippebModule()); install(new RenaudModule()); install(new OlivierModule()); <START> install(new JeanNicolasModule()); <END> bindPresenter(BeesPresenter.class, BeesPresenter.MyView.class, BeesView.class, BeesPresenter.MyProxy.class); bindPresenterWidget(QuestionPresenter.class, QuestionPresenter.MyView.class, QuestionView.class); bind(Konami.class).asEagerSingleton(); }</code><technical_language>Alphabetical order of modules, maybe</technical_language>

Target:
protected void configure() { install(new ChristianModule()); install(new ChristopherModule()); install(new JasonModule()); install(new JeanNicolasModule()); install(new JoelModule()); install(new LarryModule()); install(new ManonModule()); install(new MaximeModule()); install(new OlivierModule()); install(new PhilippeaModule()); install(new PhilippebModule()); install(new RenaudModule()); bindPresenter(BeesPresenter.class, BeesPresenter.MyView.class, BeesView.class, BeesPresenter.MyProxy.class); bindPresenterWidget(QuestionPresenter.class, QuestionPresenter.MyView.class, QuestionView.class); bind(Konami.class).asEagerSingleton(); }
Source:
<code>public String constructGroupId(Datastream datastream) { <START> return constructGroupId(KafkaConnectionString.valueOf(datastream.getSource().getConnectionString()), <END> datastream.getDestination().getConnectionString()); }</code><technical_language>good if avoid dependency destination in connector. source + datastream task group for constructing groupId</technical_language>

Target:
public String constructGroupId(Datastream datastream) { if (_isGroupIdHashingEnabled) { return constructGroupId(DatastreamUtils.getTaskPrefix(datastream), _clusterName); } else { return constructGroupId(KafkaConnectionString.valueOf(datastream.getSource().getConnectionString()), datastream.getDestination().getConnectionString()); } }
Source:
<code>public void testListSizes() { List<Size> sizes = sizesApi.list(); <START> assertTrue(sizes.size() > 0, "Size list should not be empty"); <END> }</code><technical_language>!sizes.isEmpty()</technical_language>

Target:
public void testListSizes() { List<Size> sizes = sizesApi.list(); assertFalse(sizes.isEmpty(), "Size list should not be empty"); }
Source:
<code>public void deleteDraft(final Account account, long id) { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(Folder.OPEN_MODE_RW); String uid = localFolder.getMessageUidById(id); if (uid != null) { LocalMessage message = localFolder.getMessage(uid); if (message != null) { <START> deleteMessages(Collections.singletonList(message.makeMessageReference()), null); <END> } } } catch (MessagingException me) { addErrorMessage(account, null, me); } finally { closeFolder(localFolder); } }</code><technical_language>Instead of creating a MessageReference satisfy method signature please extract code actual work (using a LocalMessage) a new method</technical_language>

Target:
public void deleteDraft(final Account account, long id) { LocalFolder localFolder = null; try { LocalStore localStore = account.getLocalStore(); localFolder = localStore.getFolder(account.getDraftsFolderName()); localFolder.open(Folder.OPEN_MODE_RW); String uid = localFolder.getMessageUidById(id); if (uid != null) { MessageReference messageReference = new MessageReference( account.getUuid(), account.getDraftsFolderName(), uid, null); deleteMessage(messageReference, null); } } catch (MessagingException me) { addErrorMessage(account, null, me); } finally { closeFolder(localFolder); } }
Source:
<code>public void execute(MApplication app, EModelService service, IExtensionRegistry registery, IThemeManager mgr) { if (menu == null) { return; } List<String> tags = app.getTags(); for (String tag : tags) { if (PROCESSOR_ID.equals(tag)) { return; } } tags.add(PROCESSOR_ID); IThemeEngine engine = mgr.getEngineForDisplay(Display.getCurrent()); List<ITheme> themes = engine.getThemes(); <START> if (themes.size() > 0) { <END> MCommand switchThemeCommand = null; for (MCommand cmd : app.getCommands()) { if ("contacts.switchTheme".equals(cmd.getElementId())) { switchThemeCommand = cmd; break; } } if (switchThemeCommand != null) { themesMenu = MMenuFactory.INSTANCE.createMenu(); themesMenu.setLabel("%switchThemeMenu"); themesMenu.setContributorURI(BUNDLE_ID); for (ITheme theme : themes) { MParameter parameter = service .createModelElement(MParameter.class); parameter.setName("contacts.commands.switchtheme.themeid"); parameter.setValue(theme.getId()); String iconURI = Util.getCSSUri(theme.getId(), registery); if (iconURI != null) { iconURI = iconURI.replace(".css", ".png"); } processTheme(theme.getLabel(), switchThemeCommand, parameter, iconURI, service); } menu.getChildren().add(themesMenu); } } }</code><technical_language>This code duplicated in classes. in Util class</technical_language>

Target:
public void execute(MApplication app, EModelService service, IExtensionRegistry registery, IThemeManager mgr) { if (menu == null) { return; } List<String> tags = app.getTags(); for (String tag : tags) { if (PROCESSOR_ID.equals(tag)) { return; } } tags.add(PROCESSOR_ID); IThemeEngine engine = mgr.getEngineForDisplay(Display.getCurrent()); List<ITheme> themes = engine.getThemes(); MCommand switchThemeCommand = findCommand(app); if (themes.size() <= 0 || switchThemeCommand == null) { return; } themesMenu = service.createModelElement(MMenu.class); themesMenu.setLabel("%switchThemeMenu"); themesMenu.setContributorURI(BUNDLE_ID); for (ITheme theme : themes) { MParameter parameter = service.createModelElement(MParameter.class); parameter.setName("contacts.commands.switchtheme.themeid"); parameter.setValue(theme.getId()); String iconURI = Util.getCSSUri(theme.getId(), registery); if (iconURI != null) { iconURI = iconURI.replace(".css", ".png"); } processTheme(theme.getLabel(), switchThemeCommand, parameter, iconURI, service); } menu.getChildren().add(themesMenu); }
Source:
<code>public void setAdminStatus(Boolean status){ this.adminStatus = status; this.mySlicer.setAdminState(status); if(status){ log.debug("Slice: "+ this.mySlicer.getSliceName() +" is re-enabled"); }else{ <START> log.info("Disabling Slice:"+this.mySlicer.getSliceName() ); <END> if(this.connected()){ this.removeFlows(); this.disconnect(); } } }</code><technical_language>this error level</technical_language>

Target:
public void setAdminStatus(Boolean status){ this.adminStatus = status; this.mySlicer.setAdminState(status); if(status){ log.info("Slice: "+ this.mySlicer.getSliceName() +" is re-enabled"); }else{ log.warn("Disabling Slice:"+this.mySlicer.getSliceName() ); if(this.connected()){ this.removeFlows(); this.disconnect(); } } }
Source:
<code>public static Timer createTimer(String cronExpression, Procedure0 closure) { JobKey jobKey = new JobKey("CRON" + cronExpression + ": " + closure.toString()); Trigger trigger = newTrigger() .withSchedule(cronSchedule(cronExpression)) .build(); Timer timer = new TimerImpl(jobKey, trigger.getKey(), cronExpression); try { JobDataMap dataMap = new JobDataMap(); dataMap.put("procedure", closure); dataMap.put("timer", timer); JobDetail job = newJob(TimerExecutionJob.class) .withIdentity(jobKey) .usingJobData(dataMap) .build(); TimerImpl.scheduler.scheduleJob(job, trigger); logger.debug("Scheduled code for execution at {}", cronExpression); return timer; } catch(SchedulerException e) { logger.error("Failed to schedule code for execution.", e); return null; } <START> } <END></code><technical_language>copied makeTimer() replaced Trigger creation. For sake of Don't-Repeat-Yourself (DRY) please extract Trigger-Creation methods resulting method assemples JobData, JobDetail</technical_language>

Target:
public static Timer createTimer(String cronExpression, Procedure0 closure) { JobDataMap dataMap = new JobDataMap(); dataMap.put("procedure", closure); return makeTimer(instant, closure.toString(), dataMap); }
Source:
<code>boolean readFromDirectories(List<File> directories) { boolean success = false; for (File dir : directories) { File statusFile = new File(dir, BOOKIE_STATUS_FILENAME); try { BookieStatus status = readFromFile(statusFile); if (null != status) { <START> synchronized (status) { <END> if (status.lastUpdateTime > this.lastUpdateTime) { this.lastUpdateTime = status.lastUpdateTime; this.layoutVersion = status.layoutVersion; this.bookieMode = status.bookieMode; success = true; } } } } catch (IOException e) { LOG.warn("IOException while trying to read bookie status from directory {}." + " This is fine if not all directories failed.", dir); } catch (IllegalArgumentException e ){ LOG.warn("IllegalArgumentException while trying to read bookie status from directory {}." + " This is fine if not all directories failed.", dir); } } if (success) { LOG.info("Successfully retrieve bookie status from disks.", getBookieMode()); } else { LOG.warn("Failed to retrieve bookie status from disks." + " Fall back to current or default bookie status: {}", getBookieMode()); } return success; }</code><technical_language>status is a local variable do need a 'synchronized'</technical_language>

Target:
void readFromDirectories(List<File> directories) { boolean success = false; for (File dir : directories) { File statusFile = new File(dir, BOOKIE_STATUS_FILENAME); try { BookieStatus status = readFromFile(statusFile); if (null != status) { synchronized (status) { if (status.lastUpdateTime > this.lastUpdateTime) { this.lastUpdateTime = status.lastUpdateTime; this.layoutVersion = status.layoutVersion; this.bookieMode = status.bookieMode; success = true; } } } } catch (IOException e) { LOG.warn("IOException while trying to read bookie status from directory {}." + " This is fine if not all directories failed.", dir); } catch (IllegalArgumentException e ){ LOG.warn("IllegalArgumentException while trying to read bookie status from directory {}." + " This is fine if not all directories failed.", dir); } } if (success) { LOG.info("Successfully retrieve bookie status from disks.", getBookieMode()); } else { LOG.warn("Failed to retrieve bookie status from disks." + " Fall back to current or default bookie status: {}", getBookieMode()); } }
Source:
<code><START> public void setPublicURI(Map<String, String> fullHostNames) { if (fullHostNames != null && !fullHostNames.isEmpty()) { final StringBuilder sb = new StringBuilder(); final Iterator<Map.Entry<String, String>> iterator = fullHostNames.entrySet().iterator(); while (iterator.hasNext()) { final Map.Entry<String, String> entry = iterator.next(); sb.append(entry.getKey()).append("://").append(entry.getValue()).append("/").append(name); if (iterator.hasNext()) { sb.append("\n"); } } <END> toStringContent = sb.toString(); } else { toStringContent = "git://" + name; } }</code><technical_language>simplify as: java @Override public void setPublicURI(Map<String, String> fullHostNames) { if (fullHostNames != null && !fullHostNames.isEmpty()) { toStringContent = fullHostNames.entrySet() .stream() .map(e -> e.getKey() + "://" + e.getValue() + "/" + name) .collect(Collectors.joining("\n")); } else { toStringContent = "git://" + name; } }</technical_language>

Target:
public void setPublicURI(Map<String, String> fullHostNames) { if (fullHostNames != null && !fullHostNames.isEmpty()) { toStringContent = fullHostNames.entrySet() .stream() .map(e -> e.getKey() + "://" + e.getValue() + "/" + name) .collect(Collectors.joining("\n")); } else { toStringContent = "git://" + name; } }
Source:
<code>public boolean isLocal() { <START> return getStorageType() == StorageType.LOCALFS; <END> }</code><technical_language>add isLocal() method StorageType enum this return getStorageType.isLocal()</technical_language>

Target:
public boolean isLocal() { return getStorageType().isLocal(); }
Source:
<code>public static void initializeMap(InputStream resource) { try { InputStreamReader isr = new InputStreamReader(resource); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { String parts[] = line.split("="); map.put(parts[0], parts[1]); } <START> br.close(); <END> isr.close(); resource.close(); } catch (IOException e) { e.printStackTrace(); System.err.print("Cannot open location mapping file"); } }</code><technical_language>close resources in a finally clause</technical_language>

Target:
public static void initializeMap(InputStream resource) { InputStreamReader isr = null; BufferedReader br = null; try { isr = new InputStreamReader(resource); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { String parts[] = line.split("="); map.put(parts[0], parts[1]); } } catch (IOException e) { e.printStackTrace(); System.err.print("Cannot open location mapping file"); } finally { try { if (isr != null) { isr.close(); } if (br != null) { br.close(); } if (resource != null) { resource.close(); } } catch (IOException e) { e.printStackTrace(); } } }
Source:
<code>public void addAccount(Account account) throws SQLException { try { long startTimeMs = System.currentTimeMillis(); PreparedStatement insertStatement = dataAccessor.getPreparedStatement(insertSql); insertStatement.setString(1, AccountCollectionSerde.accountToJsonNoContainers(account).toString()); insertStatement.setInt(2, account.getSnapshotVersion()); insertStatement.executeUpdate(); dataAccessor.onSuccess(MySqlDataAccessor.OperationType.Write, System.currentTimeMillis() - startTimeMs); } catch (SQLException e) { <START> dataAccessor.onException(e, MySqlDataAccessor.OperationType.Write); <END> throw e; } }</code><technical_language>Minor: import static MySqlDataAccessor.OperationType</technical_language>

Target:
public void addAccount(Account account) throws SQLException { try { long startTimeMs = System.currentTimeMillis(); PreparedStatement insertStatement = dataAccessor.getPreparedStatement(insertSql); insertStatement.setString(1, AccountCollectionSerde.accountToJsonNoContainers(account).toString()); insertStatement.setInt(2, account.getSnapshotVersion()); insertStatement.executeUpdate(); dataAccessor.onSuccess(Write, System.currentTimeMillis() - startTimeMs); } catch (SQLException e) { dataAccessor.onException(e, Write); throw e; } }
Source:
<code>private void fire(final Project.NameKey p, final Properties statistics) { Event event = new GarbageCollectorListener.Event() { @Override public String getProjectName() { return p.get(); } @Override public Properties getStatistics() { return statistics; } }; for (GarbageCollectorListener listener : listeners) { <START> listener.onGarbageCollected(event); <END> } }</code><technical_language>this surrounded a try-catch, failures in a listener do GC call fail? try { l.onGarbageCollected(event); } catch (RuntimeException e) { log.warn("Failure in GarbageCollectorListener", e); } Similar is done invoking NewProjectCreatedListener in CreateProject</technical_language>

Target:
private void fire(final Project.NameKey p, final Properties statistics) { Event event = new GarbageCollectorListener.Event() { @Override public String getProjectName() { return p.get(); } @Override public Properties getStatistics() { return statistics; } }; for (GarbageCollectorListener l : listeners) { try { l.onGarbageCollected(event); } catch (RuntimeException e) { log.warn("Failure in GarbageCollectorListener", e); } } }
Source:
<code>public void concurrentAccesses() throws Exception { final int numIterations = 500000; final String storeName = "word-count-store"; final String windowStoreName = "windowed-word-count-store"; final ProducerRunnable producerRunnable = new ProducerRunnable(streamConcurrent, inputValues, numIterations); final Thread producerThread = new Thread(producerRunnable); kafkaStreams = createCountStream( streamConcurrent, outputTopicConcurrent, outputTopicConcurrentWindowed, storeName, windowStoreName, streamsConfiguration); <START> StreamsTestUtils.startKafkaStreamsAndWaitForRunningState(kafkaStreams); <END> producerThread.start(); try { waitUntilAtLeastNumRecordProcessed(outputTopicConcurrent, numberOfWordsPerIteration); waitUntilAtLeastNumRecordProcessed(outputTopicConcurrentWindowed, numberOfWordsPerIteration); final ReadOnlyKeyValueStore<String, Long> keyValueStore = kafkaStreams.store(storeName + "-" + streamConcurrent, QueryableStoreTypes.keyValueStore()); final ReadOnlyWindowStore<String, Long> windowStore = kafkaStreams.store(windowStoreName + "-" + streamConcurrent, QueryableStoreTypes.windowStore()); final Map<String, Long> expectedWindowState = new HashMap<>(); final Map<String, Long> expectedCount = new HashMap<>(); while (producerRunnable.getCurrIteration() < numIterations) { verifyGreaterOrEqual(inputValuesKeys.toArray(new String[0]), expectedWindowState, expectedCount, windowStore, keyValueStore, true); } } finally { producerRunnable.shutdown(); producerThread.interrupt(); producerThread.join(); } }</code><technical_language>Nit: add static import</technical_language>

Target:
public void concurrentAccesses() throws Exception { final int numIterations = 500000; final String storeName = "word-count-store"; final String windowStoreName = "windowed-word-count-store"; final ProducerRunnable producerRunnable = new ProducerRunnable(streamConcurrent, inputValues, numIterations); final Thread producerThread = new Thread(producerRunnable); kafkaStreams = createCountStream( streamConcurrent, outputTopicConcurrent, outputTopicConcurrentWindowed, storeName, windowStoreName, streamsConfiguration); startKafkaStreamsAndWaitForRunningState(kafkaStreams); producerThread.start(); try { waitUntilAtLeastNumRecordProcessed(outputTopicConcurrent, numberOfWordsPerIteration); waitUntilAtLeastNumRecordProcessed(outputTopicConcurrentWindowed, numberOfWordsPerIteration); final ReadOnlyKeyValueStore<String, Long> keyValueStore = kafkaStreams.store(storeName + "-" + streamConcurrent, QueryableStoreTypes.keyValueStore()); final ReadOnlyWindowStore<String, Long> windowStore = kafkaStreams.store(windowStoreName + "-" + streamConcurrent, QueryableStoreTypes.windowStore()); final Map<String, Long> expectedWindowState = new HashMap<>(); final Map<String, Long> expectedCount = new HashMap<>(); while (producerRunnable.getCurrIteration() < numIterations) { verifyGreaterOrEqual(inputValuesKeys.toArray(new String[0]), expectedWindowState, expectedCount, windowStore, keyValueStore, true); } } finally { producerRunnable.shutdown(); producerThread.interrupt(); producerThread.join(); } }
Source:
<code><START> public Page<T> getPagedData(Pageable pageable, List<T> list) { <END> if (CollectionUtils.isEmpty(list)) { return new PageImpl<T>(list); } Collections.sort(list); int offSet = pageable.getOffset(); int size = pageable.getPageSize(); List<T> page = new ArrayList<T>(); for (int i = offSet; i < Math.min(list.size(), offSet + size); i++) { page.add(list.get(i)); } return new PageImpl<T>(page, pageable, list.size()); }</code><technical_language>want do a null check</technical_language>

Target:
public Page<T> getPagedData(Pageable pageable, List<T> list) { Assert.notNull(pageable, "Pagination info can't be null."); if (CollectionUtils.isEmpty(list)) { return new PageImpl<T>(list); } Collections.sort(list); int to = Math.min(list.size(), pageable.getOffset() + pageable.getPageSize()); List<T> data = list.subList(pageable.getOffset(), to); return new PageImpl<T>(data, pageable, list.size()); }
Source:
<code><START> public static NitfHeaderImpl getDefault(final FileType fileType) { <END> NitfHeaderImpl nitfFileHeader = new NitfHeaderImpl(); nitfFileHeader.setFileType(fileType); nitfFileHeader.setComplexityLevel(LOWEST_COMPLEXITY_LEVEL); nitfFileHeader.setStandardType(STANDARD_TYPE_VAL); nitfFileHeader.setOriginatingStationId(NitfHeaderConstants.DEFAULT_ORIGINATING_STATION); NitfDateTime ndt = NitfDateTime.getNitfDateTimeForNow(); nitfFileHeader.setFileDateTime(ndt); nitfFileHeader.setFileTitle(""); nitfFileHeader.setFileSecurityMetadata(SecurityMetadataFactory.getDefaultFileSecurityMetadata(fileType)); RGBColour backgroundColour = new RGBColour(RGBColour.CODICE_LOGO_RED_COMPONENT, RGBColour.CODICE_LOGO_GREEN_COMPONENT, RGBColour.CODICE_LOGO_BLUE_COMPONENT); nitfFileHeader.setFileBackgroundColour(backgroundColour); nitfFileHeader.setOriginatorsName(""); nitfFileHeader.setOriginatorsPhoneNumber(""); return nitfFileHeader; }</code><technical_language>This return NitfHeader</technical_language>

Target:
public static NitfHeader getDefault(final FileType fileType) { NitfHeaderImpl nitfFileHeader = new NitfHeaderImpl(); nitfFileHeader.setFileType(fileType); nitfFileHeader.setComplexityLevel(LOWEST_COMPLEXITY_LEVEL); nitfFileHeader.setStandardType(STANDARD_TYPE_VAL); nitfFileHeader.setOriginatingStationId(NitfHeaderConstants.DEFAULT_ORIGINATING_STATION); NitfDateTime ndt = NitfDateTime.getNitfDateTimeForNow(); nitfFileHeader.setFileDateTime(ndt); nitfFileHeader.setFileTitle(""); nitfFileHeader.setFileSecurityMetadata(SecurityMetadataFactory.getDefaultFileSecurityMetadata(fileType)); RGBColour backgroundColour = new RGBColour(RGBColour.CODICE_LOGO_RED_COMPONENT, RGBColour.CODICE_LOGO_GREEN_COMPONENT, RGBColour.CODICE_LOGO_BLUE_COMPONENT); nitfFileHeader.setFileBackgroundColour(backgroundColour); nitfFileHeader.setOriginatorsName(""); nitfFileHeader.setOriginatorsPhoneNumber(""); return nitfFileHeader; }
Source:
<code>private void updateLabelList() { AsyncQuery getLabelsQuery = new AsyncQuery(); getLabelsQuery.asyncCallback = new INewAsyncCallback() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object model, Object result) { List<Label> allLabels = (List<Label>) result; if (getIsNew()) { labelList.setItems(allLabels); labelList.setSelectedItems(new ArrayList<Label>()); } else { List<Label> selectedLabels = new ArrayList<>(); <START> for (Label <END> label : allLabels) { if (label.getHosts().contains(getVmId())) { selectedLabels.add(label); } } labelList.setItems(allLabels); labelList.setSelectedItems(selectedLabels); } labelList.setIsChangeable(false); } }; AsyncDataProvider.getInstance().getLabelList(getLabelsQuery); }</code><technical_language>try stream api for filtering</technical_language>

Target:
private void updateLabelList() { AsyncQuery getLabelsQuery = new AsyncQuery(); getLabelsQuery.asyncCallback = new INewAsyncCallback() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object model, Object result) { final List<Label> allLabels = (List<Label>) result; if (getIsNew()) { labelList.setItems(allLabels); labelList.setSelectedItems(new ArrayList<Label>()); } else { AsyncQuery getLabelsByVmIdQuery = new AsyncQuery(); getLabelsByVmIdQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { List<Label> vmLabelsList = (List<Label>) returnValue; labelList.setItems(allLabels); labelList.setSelectedItems(vmLabelsList); } }; Guid vmId = ((ExistingVmModelBehavior) getBehavior()).getVm().getId(); AsyncDataProvider.getInstance().getLabelListByEntityId(getLabelsByVmIdQuery, vmId); } labelList.setIsChangeable(false); } }; AsyncDataProvider.getInstance().getLabelList(getLabelsQuery); }
Source:
<code>public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { <START> log.warn("Zookeeper can't be reached, retrying (retryCount = " + retryCount + " out of " + this.getN() + ")..."); <END> boolean shouldRetry = super.allowRetry(retryCount, elapsedTimeMs, sleeper); if (!shouldRetry) { log.warn("Since Zookeeper can't be reached after retries exhausted, calling exit function..."); exitRunner.run(); } return shouldRetry; }</code><technical_language>a format string here: log.warn("Zookeeper reached, retrying (retryCount = %s out of %s)...", retryCount, this.getN());</technical_language>

Target:
public boolean allowRetry(int retryCount, long elapsedTimeMs, RetrySleeper sleeper) { log.warn("Zookeeper can't be reached, retrying (retryCount = %s out of %s)...", retryCount, this.getN()); boolean shouldRetry = super.allowRetry(retryCount, elapsedTimeMs, sleeper); if (!shouldRetry) { log.warn("Since Zookeeper can't be reached after retries exhausted, calling exit function..."); exitRunner.run(); } return shouldRetry; }
Source:
<code>private void createDefaultSet() { OAISet newOaiSet = new OAISet(); newOaiSet.setSpec(""); newOaiSet.setName(""); <START> newOaiSet.setDescription("The default, \"no name\" set. The OAI server will serve the records from this set when no \"setspec\" argument is specified by the client."); <END> newOaiSet.setDefinition(""); boolean success = false; try { oaiSetService.save(newOaiSet); configuredHarvestingSets = oaiSetService.findAll(); success = true; } catch (Exception ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, BundleUtil.getStringFromBundle("harvest.oaicreate.defaultset.fail")); logger.log(Level.SEVERE, "Failed to create the Default OAI set" + ex.getMessage(), ex); } if (success) { OAISet savedSet = oaiSetService.findBySpec(getNewSetSpec()); if (savedSet != null) { runSetExport(savedSet); configuredHarvestingSets = oaiSetService.findAll(); } } setPageMode(HarvestingSetsPage.PageMode.VIEW); }</code><technical_language>This English in bundle, right? translated</technical_language>

Target:
private void createDefaultSet() { OAISet newOaiSet = new OAISet(); newOaiSet.setSpec(""); newOaiSet.setName(""); newOaiSet.setDescription(BundleUtil.getStringFromBundle("harvestserver.newSetDialog.setdescription.default")); newOaiSet.setDefinition(""); boolean success = false; try { oaiSetService.save(newOaiSet); configuredHarvestingSets = oaiSetService.findAll(); success = true; } catch (Exception ex) { JH.addMessage(FacesMessage.SEVERITY_FATAL, BundleUtil.getStringFromBundle("harvest.oaicreate.defaultset.fail")); logger.log(Level.SEVERE, "Failed to create the Default OAI set" + ex.getMessage(), ex); } if (success) { OAISet savedSet = oaiSetService.findBySpec(getNewSetSpec()); if (savedSet != null) { runSetExport(savedSet); configuredHarvestingSets = oaiSetService.findAll(); } } setPageMode(HarvestingSetsPage.PageMode.VIEW); }
Source:
<code>public void run() { try { synchronized (this) { if(closed.get()){ return; } curatorFramework = CuratorUtil.newAppCurator(env.getConfiguration()); CuratorCnxnListener cnxnListener = new CuratorCnxnListener(); curatorFramework.getConnectionStateListenable().addListener(cnxnListener); curatorFramework.start(); while (!cnxnListener.isConnected()) Thread.sleep(200); pathChildrenCache = new PathChildrenCache(curatorFramework, ZookeeperPath.ORACLE_SERVER, true); pathChildrenCache.getListenable().addListener(this); pathChildrenCache.start(); leaderSelector = new LeaderSelector(curatorFramework, ZookeeperPath.ORACLE_SERVER, this); connect(); } doWork(); } catch (Exception e) { if (!closed.get()) { log.error("Exception occurred in run() method", e); <START> } <END> } }</code><technical_language>log debug if closed. show up</technical_language>

Target:
public void run() { try { synchronized (this) { if(closed.get()){ return; } curatorFramework = CuratorUtil.newAppCurator(env.getConfiguration()); CuratorCnxnListener cnxnListener = new CuratorCnxnListener(); curatorFramework.getConnectionStateListenable().addListener(cnxnListener); curatorFramework.start(); while (!cnxnListener.isConnected()) Thread.sleep(200); pathChildrenCache = new PathChildrenCache(curatorFramework, ZookeeperPath.ORACLE_SERVER, true); pathChildrenCache.getListenable().addListener(this); pathChildrenCache.start(); leaderSelector = new LeaderSelector(curatorFramework, ZookeeperPath.ORACLE_SERVER, this); connect(); } doWork(); } catch (Exception e) { if (!closed.get()) { log.error("Exception occurred in run() method", e); } else { log.debug("Exception occurred in run() method", e); } } }
Source:
<code>public void close() { logger.info("Close interpreter"); if (numReferenceOfSparkContext.decrementAndGet() == 0) { sc.stop(); sc = null; sparkSession = null; <START> if (classServer != null) { <END> Utils.invokeMethod(classServer, "stop"); classServer = null; } } Utils.invokeMethod(intp, "close"); }</code><technical_language>stop called sparkSession sc.stop() <LINK_0> (as of this is ok sparkSession.stop() simply calls sc.stop() this change)</technical_language>

Target:
public void close() { logger.info("Close interpreter"); if (numReferenceOfSparkContext.decrementAndGet() == 0) { if (sparkSession != null) { Utils.invokeMethod(sparkSession, "stop"); } else if (sc != null){ sc.stop(); } sparkSession = null; sc = null; if (classServer != null) { Utils.invokeMethod(classServer, "stop"); classServer = null; } } Utils.invokeMethod(intp, "close"); }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); try { mImage = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); Toast toast = Toast.makeText(YieldsApplication.getApplicationContext(), "Image added to message", Toast.LENGTH_SHORT); toast.show(); } catch (IOException e) { <START> e.printStackTrace(); <END> } } }</code><technical_language>log error</technical_language>

Target:
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) { Uri uri = data.getData(); try { mImage = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); Toast toast = Toast.makeText(YieldsApplication.getApplicationContext(), "Image added to message", Toast.LENGTH_SHORT); toast.show(); } catch (IOException e) { Log.d("Message Activity", "Couldn't add image to the message"); } } }
Source:
<code>public TableId parseTableIdentifier(String fqn) { List<String> parts = identifierRules().parseQualifiedIdentifier(fqn); if (parts == null || parts.isEmpty()) { <START> throw new IllegalArgumentException("Invalid fully qualified name: '" + fqn + "'"); <END> } if (parts.size() == 1) { return new TableId(null, null, parts.get(0)); } if (parts.size() == 3) { return new TableId(parts.get(0), parts.get(1), parts.get(2)); } assert parts.size() >= 2; if (useCatalog()) { return new TableId(parts.get(0), null, parts.get(1)); } return new TableId(null, parts.get(0), parts.get(1)); }</code><technical_language>this method here? in a JDBC utils package/class in a dialect implementation</technical_language>

Target:
public TableId parseTableIdentifier(String fqn) { List<String> parts = identifierRules().parseQualifiedIdentifier(fqn); if (parts.isEmpty()) { throw new IllegalArgumentException("Invalid fully qualified name: '" + fqn + "'"); } if (parts.size() == 1) { return new TableId(null, null, parts.get(0)); } if (parts.size() == 3) { return new TableId(parts.get(0), parts.get(1), parts.get(2)); } assert parts.size() >= 2; if (useCatalog()) { return new TableId(parts.get(0), null, parts.get(1)); } return new TableId(null, parts.get(0), parts.get(1)); }
Source:
<code>public static Collection<Object[]> getConstructorArguments() throws IOException { GoogleCloudStorage gcs = new InMemoryGoogleCloudStorage(); GoogleCloudStorage zeroLaggedGcs = new LaggedGoogleCloudStorage( new InMemoryGoogleCloudStorage(), Clock.SYSTEM, ListVisibilityCalculator.IMMEDIATELY_VISIBLE); GoogleCloudStorage performanceCachingGcs = new PerformanceCachingGoogleCloudStorage( new InMemoryGoogleCloudStorage(), PerformanceCachingGoogleCloudStorageOptions.builder() .setListCachingEnabled(true) .build()); <START> ThrottledGoogleCloudStorage throttledGoogleCloudStorage = <END> new ThrottledGoogleCloudStorage(gcs, RateLimiter.create(2)); ThrottledGoogleCloudStorage throttledGoogleCloudStorageWithOneOperation = new ThrottledGoogleCloudStorage( new Double(2.00), gcs, EnumSet.of(ThrottledGoogleCloudStorage.StorageOperation.CREATE_OBJECT)); return Arrays.asList( new Object[] {gcs}, new Object[] {zeroLaggedGcs}, new Object[] {performanceCachingGcs}, new Object[] {throttledGoogleCloudStorage}, new Object[] {throttledGoogleCloudStorageWithOneOperation}); }</code><technical_language>need test ThrottledGoogleCloudStorage for testing. remove throttledGoogleCloudStorage throttledGoogleCloudStorageWithOneOperation , test cases if increase test coverage for other GoogleCloudStorage implementations</technical_language>

Target:
public static Collection<Object[]> getConstructorArguments() throws IOException { GoogleCloudStorage gcs = new InMemoryGoogleCloudStorage(); GoogleCloudStorage zeroLaggedGcs = new LaggedGoogleCloudStorage( new InMemoryGoogleCloudStorage(), Clock.SYSTEM, ListVisibilityCalculator.IMMEDIATELY_VISIBLE); GoogleCloudStorage performanceCachingGcs = new PerformanceCachingGoogleCloudStorage( new InMemoryGoogleCloudStorage(), PerformanceCachingGoogleCloudStorageOptions.builder() .setListCachingEnabled(true) .build()); return Arrays.asList( new Object[] {gcs}, new Object[] {zeroLaggedGcs}, new Object[] {performanceCachingGcs}); }
Source:
<code>public String toString() { return String.format("%s, ticket=%s, validTime=%s,m userName=%s, userId=%s", super.toString(), getTicket(), getValidTime(), <START> getUserName(), getUserId().toString()); <END> }</code><technical_language>need explicit call toString getUserId() here, this null safe</technical_language>

Target:
public String toString() { return String.format("%s, ticket=%s, validTime=%s,m userName=%s, userId=%s", super.toString(), getTicket(), getValidTime(), getUserName(), getUserId()); }
Source:
<code>public void unretireOrderFrequency_shouldUnretireGivenOrderFrequency() throws Exception { executeDataSet("org/openmrs/api/include/OrderServiceTest-otherOrderFrequencies.xml"); OrderFrequency orderFrequency = orderService.getOrderFrequency(103); assertNotNull(orderFrequency); <START> assertTrue(orderFrequency.isRetired()); <END> assertNull(orderFrequency.getRetireReason()); assertNotNull(orderFrequency.getDateRetired()); orderService.unretireOrderFrequency(orderFrequency); orderFrequency = orderService.getOrderFrequency(103); assertNotNull(orderFrequency); assertFalse(orderFrequency.isRetired()); assertNull(orderFrequency.getRetireReason()); assertNull(orderFrequency.getDateRetired()); }</code><technical_language>I ticket changes require modifications in this test. so</technical_language>

Target:
public void unretireOrderFrequency_shouldUnretireGivenOrderFrequency() { executeDataSet("org/openmrs/api/include/OrderServiceTest-otherOrderFrequencies.xml"); OrderFrequency orderFrequency = orderService.getOrderFrequency(103); assertNotNull(orderFrequency); assertTrue(orderFrequency.getRetired()); assertEquals(null,orderFrequency.getRetireReason()); assertNotNull(orderFrequency.getDateRetired()); orderService.unretireOrderFrequency(orderFrequency); orderFrequency = orderService.getOrderFrequency(103); assertNotNull(orderFrequency); assertFalse(orderFrequency.getRetired()); assertNull(orderFrequency.getRetireReason()); assertNull(orderFrequency.getDateRetired()); assertEquals(7, orderService.getOrderFrequencies(true).size()); }
Source:
<code>public void testPutIfAbsentHasStoreEntryCacheAccessExceptionNoCacheWriterEntry() throws Exception { final FakeStore realStore = new FakeStore(Collections.singletonMap("key", "oldValue")); this.store = spy(realStore); doThrow(new CacheAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); final FakeCacheWriter realCache = new FakeCacheWriter(Collections.<String, String>emptyMap()); this.cacheWriter = spy(realCache); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); final InOrder ordered = inOrder(this.cacheWriter, this.spiedResilienceStrategy); ehcache.putIfAbsent("key", "value"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); ordered.verify(this.cacheWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy) .putIfAbsentFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(true)); assertThat(realCache.getEntryMap().get("key"), equalTo("value")); <START> validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); END> }</code><technical_language>Calrifying this part of #163</technical_language>

Target:
public void testPutIfAbsentHasStoreEntryCacheAccessExceptionNoCacheWriterEntry() throws Exception { final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "oldValue")); this.store = spy(fakeStore); doThrow(new CacheAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); final FakeCacheWriter fakeWriter = new FakeCacheWriter(Collections.<String, String>emptyMap()); this.cacheWriter = spy(fakeWriter); final Ehcache<String, String> ehcache = this.getEhcache(this.cacheWriter); final InOrder ordered = inOrder(this.cacheWriter, this.spiedResilienceStrategy); ehcache.putIfAbsent("key", "value"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); ordered.verify(this.cacheWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy) .putIfAbsentFailure(eq("key"), eq("value"), any(CacheAccessException.class), eq(true)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); }
Source:
<code>public void highWaterMarkValueTest() throws Exception { <START> String highWaterMark = "high-water-mark"; <END> navigateToIIOPSubsystemPage(); page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); Editor editor = editPanelFragment.getEditor(); Console.withBrowser(browser).scrollIntoView(editor.getText(highWaterMark)); editor.text(highWaterMark, "7"); boolean finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); new ResourceVerifier(iiopSubsystemAddress, client).verifyAttribute("high-water-mark", 7); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("high-water-mark", ""); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); new ResourceVerifier(iiopSubsystemAddress, client).verifyAttributeIsUndefined("high-water-mark"); }</code><technical_language>I prefer highWaterMark securityDomain a constant consistent rest of test suite</technical_language>

Target:
public void highWaterMarkValueTest() throws Exception { navigateToIIOPSubsystemPage(); page.switchToEditMode(); ConfigFragment editPanelFragment = page.getConfigFragment(); Editor editor = editPanelFragment.getEditor(); Console.withBrowser(browser).scrollIntoView(editor.getText(HIGH_WATER_MARK)); editor.text(HIGH_WATER_MARK, "7"); boolean finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); new ResourceVerifier(iiopSubsystemAddress, client).verifyAttribute("high-water-mark", 7); page.switchToEditMode(); editPanelFragment = page.getConfigFragment(); editPanelFragment.getEditor().text("high-water-mark", ""); finished = editPanelFragment.save(); assertTrue("Config should be saved and closed.", finished); new ResourceVerifier(iiopSubsystemAddress, client).verifyAttributeIsUndefined("high-water-mark"); }
Source:
<code>private void removeStaleAliasesFromChannel( Set<Long> channelIdsThatHaveAliasesAdded, Iterable<Channel> channels ) { for (Channel channel : channels) { if(!channelIdsThatHaveAliasesAdded.contains(channel.getId())) { channel.setAliases( channel.getAliases() .stream() <START> .filter(alias -> !alias.getNamespace().equals(aliasNamespace)) <END> .collect(Collectors.toList()) ); } channelWriter.createOrUpdate(channel); } }</code><technical_language>this Objects.equals JIC null safety is required</technical_language>

Target:
private void removeStaleAliasesFromChannel( Set<Long> channelIdsThatHaveAliasesAdded, Iterable<Channel> channels ) { for (Channel channel : channels) { if(!channelIdsThatHaveAliasesAdded.contains(channel.getId())) { channel.setAliases( channel.getAliases() .stream() .filter(alias -> !alias.getNamespace().equals(aliasNamespace)) .collect(Collectors.toList()) ); channelWriter.createOrUpdate(channel); } } }
Source:
<code>public LogicalSwitch createLogicalSwitch(LogicalSwitch ls) throws Exception { Insert<GenericTableSchema> op = lsTable.insert(ls); try { UUID newId = modify(client, lsTable, op).result(Duration.Inf()); if (newId == null) throw new VtepException(endPoint, "cannot create logical switch: " + ls); Set<LogicalSwitch> lSwitch = retrieveLogicalSwitch( lsTable.getUuidMatcher(newId)); if (lSwitch.isEmpty()) <START> throw new VtepException( endPoint, "cannot retrieve <END> logical switch for id: " + newId); return lSwitch.iterator().next(); } catch (TimeoutException tOut) { throw new VtepException(endPoint, tOut); } }</code><technical_language>VtepRetrievalException, adding a constructor id? That'd save a LOT of lines in this class</technical_language>

Target:
public LogicalSwitch createLogicalSwitch(LogicalSwitch ls) throws Exception { Insert<GenericTableSchema> op = lsTable.insert(ls); try { UUID newId = modify(client, lsTable, op).result(Duration.Inf()); if (newId == null) throw new VtepException(endPoint, "cannot create logical switch: " + ls); Set<LogicalSwitch> lSwitch = retrieveLogicalSwitch( lsTable.getUuidMatcher(newId)); if (lSwitch.isEmpty()) throw new VtepRetrievalException("logical switch " + newId); return lSwitch.iterator().next(); } catch (TimeoutException tOut) { throw new VtepException(endPoint, tOut); } }
Source:
<code>private void makeRequestWithAuthCodeAndVerify(String authCode, String expectedLogin) throws IOException, SAXException { WebRequest req = new WebRequest(new URL(j.getURL(),"test")); req.setEncodingType(null); if (authCode!=null) req.setAdditionalHeader("Authorization", authCode); Page p = wc.getPage(req); <START> assertEquals(expectedLogin, p.getWebResponse().getContentAsString().trim()); <END> }</code><technical_language>ditto, drop trim</technical_language>

Target:
private void makeRequestWithAuthCodeAndVerify(String authCode, String expectedLogin) throws IOException, SAXException { WebRequest req = new WebRequest(new URL(j.getURL(),"test")); req.setEncodingType(null); if (authCode!=null) req.setAdditionalHeader("Authorization", authCode); Page p = wc.getPage(req); assertEquals(expectedLogin, p.getWebResponse().getContentAsString()); }
Source:
<code>public JiraIssue getIssue(final String id) throws IOException { try { Optional<Issue> issue = issueCache.get(id, () -> { <START> JiraSession session = getSession(null); <END> if (session == null) { return Optional.absent(); } return Optional.fromNullable(session.getIssue(id)); }); if (!issue.isPresent()) { return null; } return new JiraIssue(issue.get()); } catch (ExecutionException e) { throw new IOException(e); } }</code><technical_language>This needs run-aware</technical_language>

Target:
public JiraIssue getIssue(final String id) throws IOException { try { Optional<Issue> issue = issueCache.get(id, () -> { if (this.jiraSession == null) { return Optional.absent(); } return Optional.fromNullable(this.jiraSession.getIssue(id)); }); if (!issue.isPresent()) { return null; } return new JiraIssue(issue.get()); } catch (ExecutionException e) { throw new IOException(e); } }
Source:
<code>public static FilterExpression replaceMilestoneAliases(IModel model, FilterExpression expr) { List<Qualifier> metaQualifiers = expr.find(Qualifier::isMetaQualifier); <START> List<String> repoIds = getReposInMetaQualifiers(metaQualifiers); <END> if (repoIds.isEmpty()) { repoIds.add(model.getDefaultRepo().toLowerCase()); } List<TurboMilestone> allMilestones = model.getMilestones().stream() .filter(ms -> repoIds.contains(ms.getRepoId().toLowerCase())) .collect(Collectors.toList()); Collections.sort(allMilestones, Qualifier::milestoneDueDateComparator); int currentMilestoneIndex = getCurrentMilestoneIndex(allMilestones); FilterExpression exprWithoutMilestones = expr.filter(q -> !Qualifier.isMilestoneQualifier(q)); List<Qualifier> milestoneQualifiers = expr.find(Qualifier::isMilestoneQualifier); List<Qualifier> convertedMilestoneQualifiers = new ArrayList<Qualifier>(); milestoneQualifiers.stream() .filter(msQualifier -> msQualifier.getContent().isPresent()) .forEach(msQualifier -> { convertedMilestoneQualifiers.add( msQualifier.replaceMilestoneAliasQualifier(allMilestones, currentMilestoneIndex) ); }); for (Qualifier msQualifier : convertedMilestoneQualifiers) { exprWithoutMilestones = new Conjunction(msQualifier, exprWithoutMilestones); } return exprWithoutMilestones; }</code><technical_language>getContentOfMetaQualifier(expr, REPO) here? rename getMetaQualifierContent</technical_language>

Target:
public static FilterExpression replaceMilestoneAliases(IModel model, FilterExpression expr) { List<String> repoIds = getContentOfMetaQualifier(expr, REPO).stream() .map(repoId -> repoId.toLowerCase()) .collect(Collectors.toList()); if (repoIds.isEmpty()) { repoIds.add(model.getDefaultRepo().toLowerCase()); } List<TurboMilestone> allMilestones = model.getMilestones().stream() .filter(ms -> repoIds.contains(ms.getRepoId().toLowerCase())) .sorted((a, b) -> { if (!a.getDueDate().isPresent() && !b.getDueDate().isPresent()) { return 0; } else if (!a.getDueDate().isPresent()) { return 1; } else if (!b.getDueDate().isPresent()) { return -1; } else { return getMilestoneDueDateComparator().compare(a, b); } }) .collect(Collectors.toList()); Optional<Integer> currentMilestoneIndex = getCurrentMilestoneIndex(allMilestones); if (!currentMilestoneIndex.isPresent()) { return expr; } expr = expr.map(q -> { if (Qualifier.isMilestoneQualifier(q)) { return q.convertMilestoneAliasQualifier(allMilestones, currentMilestoneIndex.get()); } else { return q; } }); return expr; }