auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void duplicateForm( ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true, value = "formId") Integer formId, @RequestParam(required = true, value = "patientId") Integer patientId, @RequestParam(required = true, value = "date") String date, @RequestParam(required = false, value = "dateFormat") String dateFormat) throws Exception { response.setContentType("text/html"); ServletOutputStream out = response.getOutputStream(); List<Locale> l = new Vector<Locale>(); l.add(Context.getLocale()); List<Encounter> encounters = Context.getEncounterService().getEncountersByPatientId(patientId); SimpleDateFormat dateFormatter; if (dateFormat == null) { dateFormatter = Context.getDateFormat(); <START> System.out.println("The default date format is " + dateFormatter.toString()); <END> } else { dateFormatter = new SimpleDateFormat(dateFormat); } Date dateToCheck = dateFormatter.parse(date); boolean duplicate = false; for(Encounter enc: encounters) { if(enc.getForm() != null) { Form encForm = enc.getForm(); HtmlForm htmlForm = HtmlFormEntryUtil.getService().getHtmlFormByForm(encForm); System.out.println(" Encounter form " + enc.getForm().getFormId() + " encounter date " + enc.getEncounterDatetime() + " passed date " + dateToCheck); if(htmlForm != null && htmlForm.getId().equals(formId) && dateToCheck.compareTo(enc.getEncounterDatetime()) == 0) { System.out.println("Duplicate exists"); duplicate = true; } } } if(duplicate) { out.print("true"); } else { out.print("false"); } }</code><technical_language>remove system.out.println change log.debug? (There a more well)</technical_language>

Target:
public void duplicateForm( ModelMap model, HttpServletRequest request, HttpServletResponse response, @RequestParam(required = true, value = "formId") Integer formId, @RequestParam(required = true, value = "patientId") Integer patientId, @RequestParam(required = true, value = "date") String date, @RequestParam(required = false, value = "dateFormat") String dateFormat) throws Exception { response.setContentType("text/html"); ServletOutputStream out = response.getOutputStream(); List<Locale> l = new Vector<Locale>(); l.add(Context.getLocale()); List<Encounter> encounters = Context.getEncounterService().getEncountersByPatientId(patientId); SimpleDateFormat dateFormatter; if (dateFormat != null) { dateFormatter = new SimpleDateFormat(dateFormat); } else { dateFormatter = Context.getDateFormat(); } Date dateToCheck = dateFormatter.parse(date); boolean duplicate = false; for(Encounter enc: encounters) { if(enc.getForm() != null) { Form encForm = enc.getForm(); HtmlForm htmlForm = HtmlFormEntryUtil.getService().getHtmlFormByForm(encForm); if(htmlForm != null && htmlForm.getId().equals(formId) && dateToCheck.compareTo(enc.getEncounterDatetime()) == 0) { duplicate = true; } } } if(duplicate) { out.print("true"); } else { out.print("false"); } }
Source:
<code><START> public void testDistributedSQLForOnlyENTRYIterationType() throws InterruptedException { <END> dsDistributedMap1.put(1, new User(1, "TestName1", "TestSurname1", 10)); dsDistributedMap1.put(2, new User(2, "TestName2", "TestSurname2", 20)); dsDistributedMap1.put(3, new User(3, "TestName3", "TestSurname3", 30)); dsDistributedMap1.put(4, new User(4, "TestName4", "TestSurname4", 40)); dsDistributedMap1.put(5, new User(5, "TestName5", "TestSurname5", 50)); Message<?> msg = null; for (int i = 0; i < 10; i++) { msg = dsMapChannel1.receive(); if (((Collection) msg.getPayload()).iterator().hasNext()) { break; } Thread.sleep(1_000); } Assert.assertNotNull(msg); Assert.assertNotNull(msg.getPayload()); Assert.assertTrue(msg.getPayload() instanceof Collection); Assert.assertEquals(4, (((Map.Entry) ((Collection) msg.getPayload()).iterator() .next()).getKey())); Assert.assertEquals(4, ((User) ((Map.Entry) ((Collection) msg.getPayload()) .iterator().next()).getValue()).getId()); Assert.assertEquals("TestName4", ((User) ((Map.Entry) ((Collection) msg .getPayload()).iterator().next()).getValue()).getName()); Assert.assertEquals("TestSurname4", ((User) ((Map.Entry) ((Collection) msg .getPayload()).iterator().next()).getValue()).getSurname()); }</code><technical_language>Duration pass 1.001s</technical_language>

Target:
public void testDistributedSQLForOnlyENTRYIterationType() throws InterruptedException { dsDistributedMap1.put(1, new HazelcastIntegrationTestUser(1, "TestName1", "TestSurname1", 10)); dsDistributedMap1.put(2, new HazelcastIntegrationTestUser(2, "TestName2", "TestSurname2", 20)); dsDistributedMap1.put(3, new HazelcastIntegrationTestUser(3, "TestName3", "TestSurname3", 30)); dsDistributedMap1.put(4, new HazelcastIntegrationTestUser(4, "TestName4", "TestSurname4", 40)); dsDistributedMap1.put(5, new HazelcastIntegrationTestUser(5, "TestName5", "TestSurname5", 50)); Message<?> msg = dsMapChannel1.receive(2_000); Assert.assertNotNull(msg); Assert.assertNotNull(msg.getPayload()); Assert.assertTrue(msg.getPayload() instanceof Collection); Assert.assertEquals(4, (((Map.Entry<?,?>) ((Collection<?>) msg.getPayload()).iterator() .next()).getKey())); Assert.assertEquals(4, ((HazelcastIntegrationTestUser) ((Map.Entry<?,?>) ((Collection<?>) msg.getPayload()) .iterator().next()).getValue()).getId()); Assert.assertEquals("TestName4", ((HazelcastIntegrationTestUser) ((Map.Entry<?,?>) ((Collection<?>) msg .getPayload()).iterator().next()).getValue()).getName()); Assert.assertEquals("TestSurname4", ((HazelcastIntegrationTestUser) ((Map.Entry<?,?>) ((Collection<?>) msg .getPayload()).iterator().next()).getValue()).getSurname()); }
Source:
<code>private void saveLastReloadInStorage(Date date) { StorageUtil.setLocalItem(LAST_RELOAD_KEY_IN_STORAGE, date.getHours() <START> + ":" + date.getMinutes() + ":" + date.getSeconds()); <END> }</code><technical_language>![MINOR](<LINK_2> 'Severity: MINOR') Remove this of "getMinutes"; is deprecated. [![rule](<LINK_1>](<LINK_0> ![MINOR](<LINK_2> 'Severity: MINOR') Remove this of "getSeconds"; is deprecated. [![rule](<LINK_1>](<LINK_0></technical_language>

Target:
private void saveLastReloadInStorage(Date date) { StorageUtil.setSessionItem(LAST_RELOAD_KEY_IN_STORAGE, date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds()); }
Source:
<code>public static Plan getPlan(String serviceName, String serviceType) { <START> Plan root = new Plan(); <END> MetaData temp = getMetaData(serviceName, serviceType); if (temp != null) { root.put(serviceName, serviceType); } Map<String, ServiceReservation> peers = temp.getPeers(); for (ServiceReservation peer : peers.values()) { getPlan(root, serviceName, peer); } return root; }</code><technical_language>This is a set (treeset) .. a difficult justify a new class get a toString method.</technical_language>

Target:
public static Plan getPlan(String serviceName, String serviceType) { Plan root = new Plan(); AbstractMetaData temp = getMetaData(serviceName, serviceType); if (temp != null) { root.put(serviceName, serviceType); } Map<String, ServiceReservation> peers = temp.getPeers(); for (ServiceReservation peer : peers.values()) { getPlan(root, serviceName, peer); } return root; }
Source:
<code>public void diffOrderTooHighTest() { @SuppressWarnings("unused") <START> DoubleMatrix2D d = getDifferanceMatrix(6, 6); <END> }</code><technical_language>need assign, getDifferanceMatrix(6, 6); [sic]. supression needed</technical_language>

Target:
public void diffOrderTooHighTest() { getDifferenceMatrix(6, 6); }
Source:
<code>protected void delete(FulfillerDetails delegate, String reason, RequestContext context) throws ResponseException { <START> Context.getOrderService().updateOrderFulfillerStatus(delegate.getOrder(), null, null); <END> }</code><technical_language>I this resource support other operation exception save i.e. POST, if client wishes clear fields, posting resource blank values, result same</technical_language>

Target:
protected void delete(FulfillerDetails delegate, String reason, RequestContext context) throws ResponseException { throw new ResourceDoesNotSupportOperationException(); }
Source:
<code>public void ImageStorage_001_deleteImage() { WikiBasePageObject base = new WikiBasePageObject(driver); <START> base.logInCookie(credentials.userNameStaff, credentials.passwordStaff); <END> SpecialNewFilesPageObject newFiles = base.openSpecialNewFiles(wikiURL); FilePagePageObject file = newFiles.openRandomImage(); imageURL = file.getImageUrl(); imageThumbnailURL = file.getImageThumbnailUrl(); newFiles.verifyURLStatus(200, imageURL); newFiles.verifyURLStatus(200, imageThumbnailURL); DeletePageObject delete = newFiles.deletePage(); delete.submitDeletion(); delete.verifyNotificationMessage(); base.verifyURLStatus(404, imageURL); base.verifyURLStatus(404, imageThumbnailURL); SpecialRestorePageObject restore = delete.undeleteByFlashMessage(); restore.giveReason("asd"); restore.restorePage(); restore.verifyNotificationMessage(); newFiles.verifyURLStatus(200, imageURL); newFiles.verifyURLStatus(200, imageThumbnailURL); }</code><technical_language>add "wikiURL" a parameter, logInCookie method params is Global.DOMAIN</technical_language>

Target:
public void ImageStorage_001_deleteImage() { WikiBasePageObject base = new WikiBasePageObject(driver); base.logInCookie(credentials.userNameStaff, credentials.passwordStaff, wikiURL); SpecialNewFilesPageObject newFiles = base.openSpecialNewFiles(wikiURL); FilePagePageObject file = newFiles.openRandomImage(); imageURL = file.getImageUrl(); imageThumbnailURL = file.getImageThumbnailUrl(); newFiles.verifyURLStatus(200, imageURL); newFiles.verifyURLStatus(200, imageThumbnailURL); DeletePageObject delete = newFiles.deletePage(); delete.submitDeletion(); delete.verifyNotificationMessage(); base.verifyURLStatus(404, imageURL); base.verifyURLStatus(404, imageThumbnailURL); SpecialRestorePageObject restore = delete.undeleteByFlashMessage(); restore.giveReason(PageContent.caption); restore.restorePage(); restore.verifyNotificationMessage(); newFiles.verifyURLStatus(200, imageURL); newFiles.verifyURLStatus(200, imageThumbnailURL); }
Source:
<code>public boolean execute(CommandSender sender, String label, String[] args) { if (!testPermission(sender)) { return false; } if (args.length == 0 || args.length == 2) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } GlowWorld world = CommandUtils.getWorld(sender); Location location = CommandUtils.getLocation(sender); if (world == null) { return false; } String functionName = args[0]; CommandFunction function = world.getFunctions().get(functionName); <START> if (function == null) { <END> sender.sendMessage(ChatColor.RED + "Unknown function '" + functionName + "'"); return false; } if (args.length > 2 && location != null) { String condition = args[1].toLowerCase(); CommandTarget target = new CommandTarget(sender, args[2]); Entity[] matched = target.getMatched(location); if (condition.equals("if")) { if (matched.length == 0) { sender.sendMessage("Skipped execution of function '" + function.getFullName() + "'"); return false; } } else if (condition.equals("unless")) { if (matched.length > 0) { sender.sendMessage("Skipped execution of function '" + function.getFullName() + "'"); return false; } } else { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } } function.execute(sender); return true; }</code><technical_language>getFunctions().containsKey() check here, get function check</technical_language>

Target:
public boolean execute(CommandSender sender, String label, String[] args) { if (!testPermission(sender)) { return false; } if (args.length == 0 || args.length == 2) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } GlowWorld world = CommandUtils.getWorld(sender); Location location = CommandUtils.getLocation(sender); if (world == null) { return false; } String functionName = args[0]; Map<String, CommandFunction> functions = world.getFunctions(); if (!functions.containsKey(functionName)) { sender.sendMessage(ChatColor.RED + "Unknown function '" + functionName + "'"); return false; } CommandFunction function = functions.get(functionName); if (args.length > 2 && location != null) { String condition = args[1].toLowerCase(); CommandTarget target = new CommandTarget(sender, args[2]); Entity[] matched = target.getMatched(location); if (condition.equals("if")) { if (matched.length == 0) { sender.sendMessage("Skipped execution of function '" + function.getFullName() + "'"); return false; } } else if (condition.equals("unless")) { if (matched.length > 0) { sender.sendMessage("Skipped execution of function '" + function.getFullName() + "'"); return false; } } else { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); return false; } } function.execute(sender); return true; }
Source:
<code>public void init(IWorkbench workbench, IStructuredSelection selection) { <START> System.out.println("!!!!!!!!!!!!!!!!"); <END> }</code><technical_language>forgot remove this println</technical_language>

Target:
public void init(IWorkbench workbench, IStructuredSelection selection) { }
Source:
<code>public Class<?> getObjectType() { <START> return Array.class; <END> }</code><technical_language>Partition[].class</technical_language>

Target:
public Class<?> getObjectType() { return Partition[].class; }
Source:
<code>Worker(String applicationName, IRecordProcessorFactory recordProcessorFactory, KinesisClientLibConfiguration config, StreamConfig streamConfig, InitialPositionInStreamExtended initialPositionInStream, long parentShardPollIntervalMillis, long shardSyncIdleTimeMillis, boolean cleanupLeasesUponShardCompletion, ICheckpoint checkpoint, KinesisClientLibLeaseCoordinator leaseCoordinator, ExecutorService execService, IMetricsFactory metricsFactory, long taskBackoffTimeMillis, long failoverTimeMillis, boolean skipShardSyncAtWorkerInitializationIfLeasesExist, ShardPrioritization shardPrioritization) { this(applicationName, recordProcessorFactory, config, streamConfig, initialPositionInStream, parentShardPollIntervalMillis, shardSyncIdleTimeMillis, cleanupLeasesUponShardCompletion, checkpoint, leaseCoordinator, execService, metricsFactory, taskBackoffTimeMillis, failoverTimeMillis, skipShardSyncAtWorkerInitializationIfLeasesExist, <START> shardPrioritization, Optional.empty(), Optional.empty(), new NoOpWorkerStateChangeListener()); <END> }</code><technical_language>above, please this a constant instead</technical_language>

Target:
Worker(String applicationName, IRecordProcessorFactory recordProcessorFactory, KinesisClientLibConfiguration config, StreamConfig streamConfig, InitialPositionInStreamExtended initialPositionInStream, long parentShardPollIntervalMillis, long shardSyncIdleTimeMillis, boolean cleanupLeasesUponShardCompletion, ICheckpoint checkpoint, KinesisClientLibLeaseCoordinator leaseCoordinator, ExecutorService execService, IMetricsFactory metricsFactory, long taskBackoffTimeMillis, long failoverTimeMillis, boolean skipShardSyncAtWorkerInitializationIfLeasesExist, ShardPrioritization shardPrioritization) { this(applicationName, recordProcessorFactory, config, streamConfig, initialPositionInStream, parentShardPollIntervalMillis, shardSyncIdleTimeMillis, cleanupLeasesUponShardCompletion, checkpoint, leaseCoordinator, execService, metricsFactory, taskBackoffTimeMillis, failoverTimeMillis, skipShardSyncAtWorkerInitializationIfLeasesExist, shardPrioritization, Optional.empty(), Optional.empty(), DEFAULT_WORKER_STATE_CHANGE_LISTENER); }
Source:
<code>public String getName() { String name = path.getFileName().toString(); <START> if (name.toLowerCase().endsWith(Aes256Cryptor.FOLDER_EXTENSION.toLowerCase())) { <END> name = name.substring(0, name.length() - Aes256Cryptor.FOLDER_EXTENSION.length()); } return name; }</code><technical_language>StringUtils.endsWithIgnoreCase</technical_language>

Target:
public String getName() { String name = path.getFileName().toString(); if (StringUtils.endsWithIgnoreCase(name, Aes256Cryptor.FOLDER_EXTENSION)) { name = name.substring(0, name.length() - Aes256Cryptor.FOLDER_EXTENSION.length()); } return name; }
Source:
<code><START> public String getRequestHeaderByName(String headerName) { <END> String headerValue = (this.requestHeaders.isPresent() && this.requestHeaders.get().get(headerName) != null) ? this.requestHeaders.get().get(headerName).get(0) : null; return headerValue; }</code><technical_language>Add @Override</technical_language>

Target:
public String getRequestHeaderByName(String headerName) { if (this.requestHeaders.get(headerName) == null) { return null; } else { return this.requestHeaders.get(headerName).get(0); } }
Source:
<code>public void testCreateMtlsKeyStoreSuccess() throws Exception { InputStream certAndKey = getClass() .getClassLoader() .getResourceAsStream("com/google/api/client/util/mtlsCertAndKey.pem"); KeyStore mtlsKeyStore = SecurityUtils.createMtlsKeyStore(certAndKey); <START> assertEquals(mtlsKeyStore.size(), 1); <END> }</code><technical_language>In assertEquals, expected first. suggestion assertEquals(1, mtlsKeyStore.size());</technical_language>

Target:
public void testCreateMtlsKeyStoreSuccess() throws Exception { InputStream certAndKey = getClass() .getClassLoader() .getResourceAsStream("com/google/api/client/util/mtlsCertAndKey.pem"); KeyStore mtlsKeyStore = SecurityUtils.createMtlsKeyStore(certAndKey); assertEquals(1, mtlsKeyStore.size()); }
Source:
<code>private void writePage0(long pageId, ByteBuffer pageBuf) throws IOException { assert fileIo != null : "Delta pages storage is not inited: " + this; assert pageBuf.position() == 0; assert pageBuf.order() == ByteOrder.nativeOrder() : "Page buffer order " + pageBuf.order() + " should be same with " + ByteOrder.nativeOrder(); <START> int crc = PageIO.getCrc(pageBuf); <END> int crc32 = FastCrc.calcCrc(pageBuf, pageBuf.limit()); if (log.isDebugEnabled()) { log.debug("onPageWrite [pageId=" + pageId + ", pageIdBuff=" + PageIO.getPageId(pageBuf) + ", fileSize=" + fileIo.size() + ", crcBuff=" + crc32 + ", crcPage=" + crc + ']'); } pageBuf.rewind(); fileIo.writeFully(pageBuf); }</code><technical_language>crc crc32 in debug output, moved if statement</technical_language>

Target:
private void writePage0(long pageId, ByteBuffer pageBuf) throws IOException { assert deltaFileIo != null : "Delta pages storage is not inited: " + this; assert pageBuf.position() == 0; assert pageBuf.order() == ByteOrder.nativeOrder() : "Page buffer order " + pageBuf.order() + " should be same with " + ByteOrder.nativeOrder(); if (log.isDebugEnabled()) { log.debug("onPageWrite [pageId=" + pageId + ", pageIdBuff=" + PageIO.getPageId(pageBuf) + ", fileSize=" + deltaFileIo.size() + ", crcBuff=" + FastCrc.calcCrc(pageBuf, pageBuf.limit()) + ", crcPage=" + PageIO.getCrc(pageBuf) + ']'); pageBuf.rewind(); } deltaFileIo.writeFully(pageBuf); }
Source:
<code>public void reject_null_value() { <START> CurrentTenant.set(null); <END> }</code><technical_language>create a method Tests.null() simply returns null, in cases warnings suppression</technical_language>

Target:
public void reject_null_value() { CurrentTenant.set(Tests.<TenantId>nullRef()); }
Source:
<code>public StripesBehavior behave(IStripesPipe pipe, StripesAction act, ItemStack is) { if (act == StripesAction.DESTROY) { return StripesBehavior.DEFAULT; } Pipe th = is.getItem() != null ? BlockGenericPipe.createPipe(is.getItem()) : null; if (th != null && th.transport instanceof PipeTransportItems) { World wrd = pipe.getWorld(); Position loc = pipe.getPosition(); ForgeDirection dir = pipe.getOpenOrientation(); TileGenericPipe stripes = (TileGenericPipe) loc.getTile(wrd); if (!loc.shift(dir).blockExists(wrd)) { <START> th.transport = stripes.pipe.transport; <END> stripes.pipe = th; th.setTile(stripes); stripes.coreState.pipeId = Item.getIdFromItem(th.item); stripes.validate(); is.stackSize--; if (!wrd.isRemote) { place(wrd, loc, BuildCraftTransport.pipeItemsStripes); } } return StripesBehavior.DROP; } return StripesBehavior.DEFAULT; }</code><technical_language>this line is present is items in stripes pipe - drops items instead of vanishing them. sure, works, works</technical_language>

Target:
public StripesBehavior behave(IStripesPipe pipe, StripesAction act, ItemStack is) { if (act == StripesAction.DESTROY) { return StripesBehavior.DEFAULT; } Pipe<?> th = is.getItem() != null ? BlockGenericPipe.createPipe(is.getItem()) : null; if (th != null && th.transport instanceof PipeTransportItems) { World wrd = pipe.getWorld(); Position loc = pipe.getPosition(); ForgeDirection dir = pipe.getOpenOrientation(); TileGenericPipe stripes = (TileGenericPipe) loc.getTile(wrd); if (!loc.shift(dir).blockExists(wrd)) { th.setTile(stripes); stripes.pipe = th; is.stackSize--; place(wrd, loc, BuildCraftTransport.pipeItemsStripes); } return StripesBehavior.DROP; } return StripesBehavior.DEFAULT; }
Source:
<code>private VDS getServer(Guid clusterId, String hostnameOrIp) { List<VDS> servers = getVdsDao().getAllForHostname(hostnameOrIp); if(servers.size() > 0) { return getServerOfCluster(clusterId, servers); } <START> List<VdsNetworkInterface> ifaces = getInterfaceDao().getAllInterfacesWithIpAddress(hostnameOrIp); <END> if(ifaces.size() > 0) { for(VdsNetworkInterface iface : ifaces) { VDS server = getVdsDao().get(iface.getVdsId()); if(server.getvds_group_id().equals(clusterId)) { return server; } } } return null; }</code><technical_language>please consideration return of getAllInterfacesWithIpAddress in InterfaceDao</technical_language>

Target:
private VDS getServer(Guid clusterId, String hostnameOrIp) { List<VDS> servers = getVdsDao().getAllForHostname(hostnameOrIp); if(servers.size() > 0) { return getServerOfCluster(clusterId, servers); } List<VdsNetworkInterface> ifaces = getInterfaceDao().getAllInterfacesWithIpAddress(clusterId, hostnameOrIp); if(ifaces.size() == 1) { for(VdsNetworkInterface iface : ifaces) { VDS server = getVdsDao().get(iface.getVdsId()); if(server.getvds_group_id().equals(clusterId)) { return server; } } } else if(ifaces.size() > 1) { throw new RuntimeException(String.format("There are multiple servers in DB having same IP address %1$s! " + "Cannot arrive at correct server id for bricks related to this ip address in cluster %2$s", hostnameOrIp, clusterId)); } return null; }
Source:
<code>private void authenticateUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Credentials userCredentials = getUserCredentialsFromRequest(request); if (userCredentials == null) { userCredentials = getUserCredentialsFromSession(request); } if (userCredentials == null) { throw new AuthenticationException("Credentials Required"); } try { AuthenticationUtils.handleCredentials( session, userCredentials.getUsername(), userCredentials.getPassword(), userCredentials.getProfile()); request.getRequestDispatcher(SSOUtils.LOGIN_PHASE3_URI).forward(request, response); } catch (SQLException ex) { log.error("Internal Database Error", ex); throw new AuthenticationException("Internal Database Error", ex); } <START> } catch (AuthenticationException ex) { <END> request.getRequestDispatcher("/WEB-INF/login.jsp?msg=" + ex.getMessage()).forward(request, response); } finally { request.getSession().removeAttribute(SSOUtils.USER_CREDENTIALS); } }</code><technical_language>reason AuthenticationException class? is advantage of usage</technical_language>

Target:
private void authenticateUser(HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, AuthenticationException { Credentials userCredentials = getUserCredentialsFromRequest(request); if (userCredentials == null) { userCredentials = getUserCredentialsFromSession(request); } if (userCredentials == null) { throw new AuthenticationException("Credentials Required"); } try { AuthenticationUtils.handleCredentials( session, userCredentials.getUsername(), userCredentials.getPassword(), userCredentials.getProfile()); request.getRequestDispatcher(SSOUtils.LOGIN_PHASE3_URI).forward(request, response); } catch (SQLException ex) { log.error("Internal Database Error", ex); throw new AuthenticationException("Internal Database Error", ex); } }
Source:
<code>protected void runTask() { UpdateProgress progress = UpdateProgress.START; Set<String> receivedItemUris = new HashSet<String>(); int offset = 1; <START> while (true) { <END> reportStatus(progress.toString()); String response = null; try { response = gettyClient.getVideoResponse(MAGIC_ALL_ITEMS_SEARCH_KEYWORD, offset); } catch (IOException e) { Throwables.propagate(e); } List<VideoResponse> videos = adapter.parse(response); if (videos.isEmpty()) { break; } for (VideoResponse video : videos) { try { Identified written = dataHandler.handle(video); receivedItemUris.add(written.getCanonicalUri()); progress = progress.reduce(UpdateProgress.SUCCESS); } catch (Exception e) { log.warn(String.format("Failed to interpret a video response"), e); progress = progress.reduce(UpdateProgress.FAILURE); } } offset += itemsPerPage; } Iterator<Content> allContent = contentLister.listContent(ContentListingCriteria.defaultCriteria().forPublisher(Publisher.GETTY).build()); while (allContent.hasNext()) { Content item = allContent.next(); if (! receivedItemUris.contains(item.getCanonicalUri())) { item.setActivelyPublished(false); dataHandler.write(item); } } }</code><technical_language>Dangerous</technical_language>

Target:
protected void runTask() { UpdateProgress progress = UpdateProgress.START; Set<String> receivedItemUris = new HashSet<String>(); int offset = 1; while (true) { try { reportStatus(progress.toString()); String response = null; try { log.debug("Requesting Getty items from {}", offset); response = gettyClient.getVideoResponse(MAGIC_ALL_ITEMS_SEARCH_KEYWORD, offset); } catch (IOException e) { Throwables.propagate(e); } log.debug("Parsing response"); List<VideoResponse> videos = adapter.parse(response); if (videos.isEmpty()) { break; } for (VideoResponse video : videos) { try { log.debug("Writing item ({})", video.getAssetId(), video.getTitle()); Identified written = dataHandler.handle(video); receivedItemUris.add(written.getCanonicalUri()); progress = progress.reduce(UpdateProgress.SUCCESS); } catch (Exception e) { log.warn(String.format("Failed to interpret a video response"), e); progress = progress.reduce(UpdateProgress.FAILURE); } } } catch (Exception e) { log.error("Whole batch failed for some reason", e); } offset += itemsPerPage; } Iterator<Content> allContent = contentLister.listContent(ContentListingCriteria.defaultCriteria().forPublisher(Publisher.GETTY).build()); while (allContent.hasNext()) { Content item = allContent.next(); if (! receivedItemUris.contains(item.getCanonicalUri())) { item.setActivelyPublished(false); dataHandler.write(item); } } }
Source:
<code><START> private static long doConvert(int delta, long amount) { <END> if (delta == 0 || amount == 0) { return amount; } else if (delta < 0) { return amount >> -delta; } else if (delta >= Long.numberOfLeadingZeros(amount < 0 ? ~amount : amount)) { return delta < 0 ? Long.MIN_VALUE : Long.MAX_VALUE; } else { return amount << delta; } }</code><technical_language>non-obvious logic begs for a unit test</technical_language>

Target:
private static long doConvert(int delta, long amount) throws ArithmeticException { if (delta == 0 || amount == 0) { return amount; } else if (delta < 0) { long t = amount >> (-delta - 1); t >>>= 64 + delta; t += amount; return t >> -delta; } else if (delta >= Long.numberOfLeadingZeros(amount < 0 ? ~amount : amount)) { throw new ArithmeticException("Conversion overflows"); } else { return amount << delta; } }
Source:
<code>public void createSrcFolderContentNonExistingDestinationFolder() throws IOException { String sourceFolderName = packagingType.getSourceFolderName(); <START> String fakeFileName = "fakeFile.xml"; <END> Path sourceFolderPath = projectBaseFolder.getRoot().toPath().resolve(PackagerTestUtils.SRC).resolve( PackagerTestUtils.MAIN) .resolve(sourceFolderName); PackagerTestUtils.createFolder(sourceFolderPath, fakeFileName, true); contentGenerator.createSrcFolderContent(); }</code><technical_language>change constants</technical_language>

Target:
public void createSrcFolderContentNonExistingDestinationFolder() throws IOException { String sourceFolderName = packagingType.getSourceFolderName(); Path sourceFolderPath = projectBaseFolder.getRoot().toPath().resolve(PackagerTestUtils.SRC).resolve( PackagerTestUtils.MAIN) .resolve(sourceFolderName); PackagerTestUtils.createFolder(sourceFolderPath, FAKE_FILE_NAME, true); contentGenerator.createSrcFolderContent(); }
Source:
<code>public CompletableFuture<Void> unrankeMapVersion(MapBean map) { String id = map.getId(); MapVersion mapVersion = new MapVersion(); mapVersion.setRanked(false); mapVersion.setId(map.getId()); fafApiAccessor.updateMapVersion(id, mapVersion); <START> return null; <END> }</code><technical_language>This needs return a completable future, null</technical_language>

Target:
public CompletableFuture<Void> unrankeMapVersion(MapBean map) { String id = map.getId(); MapVersion mapVersion = new MapVersion(); mapVersion.setRanked(false); mapVersion.setId(map.getId()); fafApiAccessor.updateMapVersion(id, mapVersion); return CompletableFuture.completedFuture(null); }
Source:
<code>public void testDefaults() { assertRecordedDefaults(recordDefaults(DruidConfig.class) .setDruidBrokerUrl(null) .setDruidCoordinatorUrl(null) .setDruidSchema("druid") .setComputePushdownEnabled(false) <START> .setHadoopResourceConfigFiles((String) null)); <END> }</code><technical_language>((String) null)</technical_language>

Target:
public void testDefaults() { assertRecordedDefaults(recordDefaults(DruidConfig.class) .setDruidBrokerUrl(null) .setDruidCoordinatorUrl(null) .setDruidSchema("druid") .setComputePushdownEnabled(false) .setHadoopConfiguration("")); }
Source:
<code>public void clickOnAddWorkspaceBtn() { <START> new WebDriverWait(seleniumWebDriver, REDRAW_UI_ELEMENTS_TIMEOUT_SEC) <END> .until(visibilityOfElementLocated(By.xpath(Locators.ADD_WORKSPACE_BTN))) .click(); }</code><technical_language>user SeleniumWebDriverHelper#waitAndClick() method instead</technical_language>

Target:
public void clickOnAddWorkspaceBtn() { seleniumWebDriverHelper.waitAndClick(By.xpath(Locators.ADD_WORKSPACE_BTN_XPATH)); }
Source:
<code>public PageableResult search(RequestContext context) throws ResponseException { String includeDeadstr = context.getParameter("includeDead"); Boolean includeDead = StringUtils.isNotBlank(includeDeadstr) ? Boolean.parseBoolean(includeDeadstr) : false; <START> List<Patient> allPatients = Context.getPatientService().getAllPatients(); <END> if (allPatients != null && allPatients.size() > 0) { if (includeDead) { return new NeedsPaging<Patient>(allPatients, context); } else { List<Patient> livingPatients = new ArrayList<Patient>(); for (Patient patient : allPatients) { if (!patient.isDead()) { livingPatients.add(patient); } } return new NeedsPaging<Patient>(livingPatients, context); } } return new EmptySearchResult(); }</code><technical_language>thought of impact of this for a site a million patients</technical_language>

Target:
public PageableResult search(RequestContext context) throws ResponseException { String includeDeadStr = context.getParameter("includeDead"); String searchPhrase = context.getParameter("q"); Boolean includeDead = StringUtils.isNotBlank(includeDeadStr) ? Boolean.parseBoolean(includeDeadStr) : false; if (StringUtils.isNotBlank(searchPhrase)) { List<Patient> allPatients = Context.getPatientService().getPatients(searchPhrase); Boolean resultsExist = allPatients != null && allPatients.size() > 0; if (!resultsExist) { return new EmptySearchResult(); } if (includeDead) { return new NeedsPaging<Patient>(allPatients, context); } else { List<Patient> livingPatients = new ArrayList<Patient>(); for (Patient patient : allPatients) { if (!patient.isDead()) { livingPatients.add(patient); } } return new NeedsPaging<Patient>(livingPatients, context); } } return new EmptySearchResult(); }
Source:
<code><START> public void decoderCanThrowUnwrappedExceptionInDecode404Mode() throws Exception { <END> server.enqueue(new MockResponse().setBody("success!")); thrown.expect(RuntimeException.class); TestInterface api = new TestInterfaceBuilder() .decode404() .decoder(new Decoder() { @Override public Object decode(Response response, Type type) throws IOException { throw new RuntimeException(); } }).target("http://localhost:" + server.getPort()); api.post(); }</code><technical_language>this more of a story. decoderCanThrowUnwrappedExceptionInDecode404Mode want, tells want. decode404AllowsCustomExceptions Instead of curiously returning "success!" demonstrate 404, return 404? Then, in decode method, assert response.code is 404 (to reinforce point). Then, throw IllegalStateException NoSuchElementException, is more for. a test is written this, future me's surely delete it, sense a feature this. a test show's intent, is deleted abandoned in a future version. Basically, of test absentee advocate for feature</technical_language>

Target:
public void decoderCanThrowUnwrappedExceptionInDecode404Mode() throws Exception { server.enqueue(new MockResponse().setResponseCode(404)); thrown.expect(NoSuchElementException.class); TestInterface api = new TestInterfaceBuilder() .decode404() .decoder(new Decoder() { @Override public Object decode(Response response, Type type) throws IOException { assertEquals(404, response.status()); throw new NoSuchElementException(); } }).target("http://localhost:" + server.getPort()); api.post(); }
Source:
<code>private void emitResourceInjection(StringBuilder builder, ResourceInjection injection) { <START> <END> Collection<ResourceBinding> bindings = injection.getResourceBindings(); for (ResourceBinding binding : bindings) { builder.append(" target.").append(binding.getName()).append(" = "); emitCastIfNeeded(builder, "java.lang.Object", binding.getType()); if (!binding.isRequired()) { builder.append("finder.findOptionalResource(source, ") .append(injection.getId()).append(", ") .append("\"" + binding.getType()).append("\");\n"); } else { builder.append("finder.findRequiredResource(source, ") .append(injection.getId()).append(", ") .append("\"" + binding.getType() + "\", ") .append("\"" + binding.getDescription() + "\");\n"); } } }</code><technical_language>kill</technical_language>

Target:
private void emitResourceInjection(StringBuilder builder, ResourceInjection injection) { Collection<ResourceBinding> bindings = injection.getResourceBindings(); for (ResourceBinding binding : bindings) { builder.append(" target.").append(binding.getName()).append(" = "); builder.append("finder.getResources(source).") .append(binding.getGetter()) .append("(" + injection.getId() + ");\n"); } }
Source:
<code>public void testSanitizeForSaving() { AccountAttributes actualAccount = createAccountAttributesToSanitize(); AccountAttributes expectedAccount = createAccountAttributesToSanitize(); actualAccount.sanitizeForSaving(); assertEquals(expectedAccount.googleId, actualAccount.googleId); <START> assertEquals(expectedAccount.name, actualAccount.name); <END> assertEquals(expectedAccount.institute, actualAccount.institute); }</code><technical_language>tests reflect changes? e.g. some values need sanitised test actualAccount.sanitizeForSaving(); work not</technical_language>

Target:
public void testSanitizeForSaving() { AccountAttributes actualAccount = createAccountAttributesToSanitize(); AccountAttributes expectedAccount = createAccountAttributesToSanitize(); actualAccount.sanitizeForSaving(); assertEquals(SanitizationHelper.sanitizeGoogleId(expectedAccount.googleId), actualAccount.googleId); assertEquals(SanitizationHelper.sanitizeName(expectedAccount.name), actualAccount.name); assertEquals(SanitizationHelper.sanitizeEmail(expectedAccount.email), actualAccount.email); assertEquals(SanitizationHelper.sanitizeTitle(expectedAccount.institute), actualAccount.institute); }
Source:
<code>protected List<String> getSchemaNamesInternal() { Connection connection = getConnection(); try { DatabaseMetaData metaData = connection.getMetaData(); List<String> result = new ArrayList<>(); if (DATABASE_PRODUCT_SQLSERVER.equals(_databaseProductName)) { result = new ArrayList<>(getSchemaSQLServerNames(metaData)); } else if (_usesCatalogsAsSchemas) { String[] catalogNames = getCatalogNames(); for (String name : catalogNames) { logger.debug("Found catalogName: {}", name); result.add(name); } } else { ResultSet rs = metaData.getSchemas(); while (rs.next()) { String schemaName = rs.getString(1); logger.debug("Found schemaName: {}", schemaName); result.add(schemaName); } <START> FileHelper.safeClose(rs); <END> } if (DATABASE_PRODUCT_MYSQL.equals(_databaseProductName)) { result.remove("information_schema"); } if (result.isEmpty()) { logger.info("No schemas or catalogs found. Creating unnamed schema."); result.add(null); } return result; } catch (SQLException e) { throw JdbcUtils.wrapException(e, "get schema names", JdbcActionType.METADATA); } finally { closeIfNecessary(connection); } }</code><technical_language>This in a finally block</technical_language>

Target:
protected List<String> getSchemaNamesInternal() { Connection connection = getConnection(); try { DatabaseMetaData metaData = connection.getMetaData(); List<String> result = new ArrayList<>(); if (DATABASE_PRODUCT_SQLSERVER.equals(_databaseProductName)) { result = new ArrayList<>(getSchemaSQLServerNames(metaData)); } else if (_usesCatalogsAsSchemas) { String[] catalogNames = getCatalogNames(); for (String name : catalogNames) { logger.debug("Found catalogName: {}", name); result.add(name); } } else { ResultSet rs = null; try { rs = metaData.getSchemas(); while (rs.next()) { String schemaName = rs.getString(1); logger.debug("Found schemaName: {}", schemaName); result.add(schemaName); } }finally { FileHelper.safeClose(rs); } } if (DATABASE_PRODUCT_MYSQL.equals(_databaseProductName)) { result.remove("information_schema"); } if (result.isEmpty()) { logger.info("No schemas or catalogs found. Creating unnamed schema."); result.add(null); } return result; } catch (SQLException e) { throw JdbcUtils.wrapException(e, "get schema names", JdbcActionType.METADATA); } finally { closeIfNecessary(connection); } }
Source:
<code><START> static public int getVersion(String barrierPath) { <END> return Integer.valueOf(barrierPath.substring(barrierPath.lastIndexOf('_') + 1)); }</code><technical_language>Minor suggestion: s/static public/public static</technical_language>

Target:
public static int getVersion(String barrierPath) { return Integer.valueOf(barrierPath.substring(barrierPath.lastIndexOf('_') + 1)); }
Source:
<code>public boolean checkFilters(List<Filter> filters, LogicalOperator logicalOperator, TaskContext taskContext) throws TaskHandlerException { <START> LOGGER.debug("Checking if the task with name: matches the filters", taskContext.getTask().getName()); <END> Map<String, Object> parameters = taskContext.getTriggerParameters(); if (isEmpty(filters) || parameters == null) { return true; } boolean filterCheck = false; for (Filter filter : filters) { KeyInformation key = parse(filter.getKey()); Object value; try { KeyEvaluator keyEvaluator = new KeyEvaluator(taskContext); value = keyEvaluator.getManipulatedValue(key); } catch (TaskHandlerException e) { if (TaskFailureCause.DATA_SOURCE.equals(e.getFailureCause())) { throw e; } value = null; } catch (Exception e) { value = null; } filterCheck = value != null && checkValue(filter, value); if (!filter.isNegationOperator()) { filterCheck = !filterCheck; } if (isFilterConditionFulfilled(filterCheck, logicalOperator)) { break; } } return filterCheck; }</code><technical_language>log in case task is executed of filters</technical_language>

Target:
public boolean checkFilters(List<Filter> filters, LogicalOperator logicalOperator, TaskContext taskContext) throws TaskHandlerException { LOGGER.debug("Checking if task: matches the filters", taskContext.getTask().getName()); Map<String, Object> parameters = taskContext.getTriggerParameters(); if (isEmpty(filters) || parameters == null) { return true; } boolean filterCheck = false; for (Filter filter : filters) { KeyInformation key = parse(filter.getKey()); Object value; try { KeyEvaluator keyEvaluator = new KeyEvaluator(taskContext); value = keyEvaluator.getManipulatedValue(key); } catch (TaskHandlerException e) { if (TaskFailureCause.DATA_SOURCE.equals(e.getFailureCause())) { throw e; } LOGGER.debug("During retrieving manipulated value for: {}, the following error occurred: {}", key.getKey(), e); value = null; } catch (Exception e) { LOGGER.debug("During retrieving manipulated value for: {}, the following error occurred: {}", key.getKey(), e); value = null; } filterCheck = value != null && checkValue(filter, value); if (!filter.isNegationOperator()) { filterCheck = !filterCheck; } LOGGER.debug("Result of checking filter: for task: is: {}", filter.getDisplayName(), taskContext.getTask().getName(), filterCheck); if (isFilterConditionFulfilled(filterCheck, logicalOperator)) { LOGGER.debug("Filters condition is fulfilled, because logicalOperator is: and filters checking has already: value", logicalOperator, filterCheck); break; } } LOGGER.info("Result of checking filters for task: is: {}", taskContext.getTask().getName(), filterCheck); return filterCheck; }
Source:
<code>public ForceObject(T element, double x, double y) { <START> this(element, Point.of(x, y), 1000); <END> }</code><technical_language>if sense underspecify a ForceObject in this (i.e., provide a default mass), if does, please define default mass a constant (ideally some context, for GRAVITY)</technical_language>

Target:
public ForceObject(T element, double x, double y) { this(element, Point.of(x, y), 1); }
Source:
<code>protected void initializeModel(EObject owner) { super.initializeModel(owner); org.eclipse.uml2.uml.Package packageOwner = (org.eclipse.uml2.uml.Package) owner; packageOwner.setName(getModelName()); Profile sysml = (Profile) PackageUtil.loadPackage(URI.createURI(SysMLResource.PROFILE_PATH), owner.eResource().getResourceSet()); if (sysml != null) { PackageUtil.applyProfile(packageOwner, sysml, true); } Profile standardUMLProfile = (Profile) PackageUtil.loadPackage(URI.createURI(UMLResource.STANDARD_PROFILE_URI), owner.eResource().getResourceSet()); if (standardUMLProfile != null) { <START> PackageUtil.applyProfile(packageOwner, standardUMLProfile, true); <END> } Package umlPrimitiveTypes = (Package) PackageUtil.loadPackage(URI.createURI(UMLResource.UML_PRIMITIVE_TYPES_LIBRARY_URI), owner.eResource().getResourceSet()); if (umlPrimitiveTypes != null){ PackageImport pi = UMLFactory.eINSTANCE.createPackageImport(); pi.setImportedPackage(umlPrimitiveTypes); packageOwner.getPackageImports().add(pi); } }</code><technical_language>is important, a logger loading profile default? a trace in console</technical_language>

Target:
protected void initializeModel(EObject owner) { super.initializeModel(owner); Package packageOwner = (Package) owner; Profile sysml = (Profile) PackageUtil.loadPackage(URI.createURI(SysMLResource.PROFILE_PATH), owner.eResource().getResourceSet()); if (sysml != null) { PackageUtil.applyProfile(packageOwner, sysml, true); } Profile standardUMLProfile = (Profile) PackageUtil.loadPackage(URI.createURI(UMLResource.STANDARD_PROFILE_URI), owner.eResource().getResourceSet()); if (standardUMLProfile != null) { PackageUtil.applyProfile(packageOwner, standardUMLProfile, true); } Package umlPrimitiveTypes = (Package) PackageUtil.loadPackage(URI.createURI(UMLResource.UML_PRIMITIVE_TYPES_LIBRARY_URI), owner.eResource().getResourceSet()); if (umlPrimitiveTypes != null){ PackageImport pi = UMLFactory.eINSTANCE.createPackageImport(); pi.setImportedPackage(umlPrimitiveTypes); packageOwner.getPackageImports().add(pi); } }
Source:
<code>protected Path createVolumeDirectory(boolean temporary) { Path directory = new File(".tmp-volume-" + System.currentTimeMillis()).toPath(); PathUtils.mkdirp(directory); <START> recursiveDeleteDir(Paths.get("/tmp/maven-hack")); <END> if (temporary) Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> { recursiveDeleteDir(directory); })); return directory; }</code><technical_language>FYI this method (createVolumeDirectory) is unused deprecated, I change</technical_language>

Target:
protected Path createVolumeDirectory(boolean temporary) { Path directory = new File(".tmp-volume-" + System.currentTimeMillis()).toPath(); PathUtils.mkdirp(directory); if (temporary) Runtime.getRuntime().addShutdownHook(new Thread(DockerClientFactory.TESTCONTAINERS_THREAD_GROUP, () -> { PathUtils.recursiveDeleteDir(directory, new DeleteFileVisitor()); })); return directory; }
Source:
<code>private String getPermissionsMap(User currentUser) { List<UserAuthorization> authorizationList = userAuthorizationDAO.listByUser(currentUser .getKey().getId()); Map<Long, UserRole> roleMap = new HashMap<Long, UserRole>(); for (UserRole role : userRoleDAO.list(Constants.ALL_RESULTS)) { roleMap.put(role.getKey().getId(), role); } StringBuilder permissions = new StringBuilder(); <START> permissions.append("{"); <END> for (UserAuthorization auth : authorizationList) { UserRole role = roleMap.get(auth.getRoleId()); if (role != null) { permissions.append("\"" + auth.getObjectPath() + "\":["); for (Permission perm : role.getPermissions()) { permissions.append("\"" + perm.name() + "\","); } permissions.append("]"); permissions.append(","); } } if (permissions.lastIndexOf(",") == permissions.length() - 1) { permissions.deleteCharAt(permissions.lastIndexOf(",")); } permissions.append("}"); return permissions.toString(); }</code><technical_language>I JSON generation done jackson's ObjectMapper, e.g. java Map<String, List<String>> roles = new HashMap<String, List<String>>(); // dummy data roles.put("someKey", Arrays.asList(new String[] { "uno", "dos" })); ObjectMapper mapper = new ObjectMapper(); StringWriter sw = new StringWriter(); mapper.writeValue(sw, roles); System.out.println(sw.toString()); // => {"someKey":["uno","dos"]}</technical_language>

Target:
private String getPermissionsMap(User currentUser) { List<UserAuthorization> authorizationList = userAuthorizationDAO.listByUser(currentUser .getKey().getId()); Map<Long, UserRole> roleMap = new HashMap<Long, UserRole>(); for (UserRole role : userRoleDAO.list(Constants.ALL_RESULTS)) { roleMap.put(role.getKey().getId(), role); } Map<String, Set<Permission>> permissions = new HashMap<String, Set<Permission>>(); for (UserAuthorization auth : authorizationList) { UserRole role = roleMap.get(auth.getRoleId()); if (role != null) { permissions.put(auth.getObjectPath(), role.getPermissions()); } } ObjectMapper jsonObjectMapper = new ObjectMapper(); StringWriter writer = new StringWriter(); try { jsonObjectMapper.writeValue(writer, permissions); } catch (JsonGenerationException e) { } catch (JsonMappingException e) { } catch (IOException e) { } return writer.toString(); }
Source:
<code>public void testTreeViewer_ReplacingSelectedItemSelectsNewItem() { TreeViewer treeViewer = new TreeViewer(getShell()); Object input = new Object(); ITreeContentProvider contentProvider = new ObservableListTreeContentProvider( <START> new IObservableFactory<Object, IObservableList<String>>() { <END> @Override public IObservableList<String> createObservable(Object target) { if (target == input) { return elementsList; } return null; } }, null); treeViewer.setComparator(new ViewerComparator()); treeViewer.setContentProvider(contentProvider); treeViewer.setInput(input); treeViewer.getTree().selectAll(); elementsList.set(0, "foo"); IStructuredSelection selection = (IStructuredSelection) treeViewer.getSelection(); Assert.assertEquals(elements.length, selection.size()); Assert.assertTrue(selection.toList().contains("foo")); }</code><technical_language>lambda</technical_language>

Target:
public void testTreeViewer_ReplacingSelectedItemSelectsNewItem() { TreeViewer treeViewer = new TreeViewer(getShell()); Object input = new Object(); ITreeContentProvider contentProvider = new ObservableListTreeContentProvider( target -> target == input ? elementsList : null, null); treeViewer.setComparator(new ViewerComparator()); treeViewer.setContentProvider(contentProvider); treeViewer.setInput(input); treeViewer.getTree().selectAll(); elementsList.set(0, "foo"); IStructuredSelection selection = treeViewer.getStructuredSelection(); Assert.assertEquals(elements.length, selection.size()); Assert.assertTrue(selection.toList().contains("foo")); }