auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected ItemUseHandler getItemUseHandler() { return e -> { Player p = e.getPlayer(); ItemStack item = e.getItem(); e.cancel(); int index = selectedMode.getOrDefault(p.getUniqueId(), 0); if (!p.isSneaking()) { SlimefunItem sfItem = modes.get(index).getItem(); if (sfItem.getID().equals(SlimefunItems.STAFF_WIND.getItemId()) && (SlimefunUtils.isItemSimilar(p.getInventory().getItemInMainHand(), SlimefunItems.STAFF_WIND, false, false) || SlimefunUtils.isItemSimilar(p.getInventory().getItemInOffHand(), SlimefunItems.STAFF_WIND, false, false))) { return; } if (removeItemCharge(item, COST)) { if (sfItem != null) { sfItem.callItemHandler(ItemUseHandler.class, handler -> handler.onRightClick(e)); } } } else { index = nextIndex(index); SlimefunItem selectedItem = modes.get(index).getItem(); String itemName = selectedItem != null ? selectedItem.getItemName() : "Unknown"; SlimefunPlugin.getLocalization().sendMessage(p, "messages.multi-tool.mode-change", true, msg -> msg.replace("%device%", "Multi Tool").replace("%mode%", ChatColor.stripColor(itemName))); selectedMode.put(p.getUniqueId(), index); } }; }

Target:
protected ItemUseHandler getItemUseHandler() { return e -> { Player p = e.getPlayer(); ItemStack item = e.getItem(); e.cancel(); int index = selectedMode.getOrDefault(p.getUniqueId(), 0); if (!p.isSneaking()) { if (removeItemCharge(item, COST)) { SlimefunItem sfItem = modes.get(index).getItem(); if (sfItem != null) { sfItem.callItemHandler(ItemUseHandler.class, handler -> handler.onRightClick(e)); } } } else { index = nextIndex(index); SlimefunItem selectedItem = modes.get(index).getItem(); String itemName = selectedItem != null ? selectedItem.getItemName() : "Unknown"; SlimefunPlugin.getLocalization().sendMessage(p, "messages.multi-tool.mode-change", true, msg -> msg.replace("%device%", "Multi Tool").replace("%mode%", ChatColor.stripColor(itemName))); selectedMode.put(p.getUniqueId(), index); } }; }
Source:
public ConflictKey(ObjectId commit, ObjectId otherCommit, SubmitType submitType, boolean contentMerge) { if (SubmitType.FAST_FORWARD_ONLY.equals(submitType) || commit.getName().compareTo(otherCommit.getName()) < 0) { this.commit = commit; this.otherCommit = otherCommit; } else { this.commit = otherCommit; this.otherCommit = commit; } this.submitType = submitType; this.contentMerge = contentMerge; }

Target:
public ConflictKey(ObjectId commit, ObjectId otherCommit, SubmitType submitType, boolean contentMerge) { if (SubmitType.FAST_FORWARD_ONLY.equals(submitType) || commit.compareTo(otherCommit) < 0) { this.commit = commit; this.otherCommit = otherCommit; } else { this.commit = otherCommit; this.otherCommit = commit; } this.submitType = submitType; this.contentMerge = contentMerge; }
Source:
public RemoteFileToHadoopTasklet(RemoteFileTemplate template, Configuration configuration, String hdfsDirectory) { template.setFileNameExpression(new SpelExpressionParser().parseExpression("payload")); try { template.afterPropertiesSet(); } catch (Exception e) { logger.error("Failed to initialize RemoteFileTemplate", e); } this.template = template; this.configuration = configuration; this.hdfsDirectory = hdfsDirectory.endsWith("/") ? hdfsDirectory : (hdfsDirectory + "/"); }

Target:
public RemoteFileToHadoopTasklet(RemoteFileTemplate template, Configuration configuration, String hdfsDirectory) { Assert.notNull(template, "'template' cannot be null"); Assert.notNull(configuration, "'configuration' cannot be null"); Assert.notNull(hdfsDirectory, "'hdfsDirectory' cannot be null"); this.template = template; this.configuration = configuration; this.hdfsDirectory = hdfsDirectory.endsWith("/") ? hdfsDirectory : (hdfsDirectory + "/"); }
Source:
public void doQuery(List<ITmfStateInterval> currentStateInfo, long t) throws TimeRangeException, StateSystemDisposedException { if (t <= getSHT().getTreeEnd()) { super.doQuery(currentStateInfo, t); } else { checkValidTime(t); } if (isFinishedBuilding()) { return; } for (int i = 0; i < currentStateInfo.size(); i++) { if (currentStateInfo.get(i) == null) { ITmfStateInterval interval = doSingularQuery(t, i); currentStateInfo.set(i, interval); } } }

Target:
public void doQuery(List<ITmfStateInterval> currentStateInfo, long t) throws TimeRangeException, StateSystemDisposedException { super.doQuery(currentStateInfo, t); if (isFinishedBuilding()) { return; } for (int i = 0; i < currentStateInfo.size(); i++) { if (currentStateInfo.get(i) == null) { ITmfStateInterval interval = doSingularQuery(t, i); currentStateInfo.set(i, interval); } } }
Source:
public static Object transformValue(int sqlColumnType, ResultSet resultSet, String fieldName) throws SQLException { Object original = resultSet.getObject(fieldName); if (original != null) { switch (sqlColumnType) { case Types.SMALLINT: case Types.TINYINT: return ((Number) original).intValue(); case Types.NUMERIC: case Types.DECIMAL: return ((BigDecimal) original).doubleValue(); case Types.DATE: return resultSet.getDate(fieldName).getTime(); case Types.TIME: return resultSet.getTime(fieldName).getTime(); case Types.TIMESTAMP: return resultSet.getTimestamp(fieldName).getTime(); case Types.BLOB: Object toReturn; Blob blob = (Blob) original; try { toReturn = blob.getBytes(1, (int) blob.length()); } finally { blob.free(); } return toReturn; case Types.CLOB: String s; StringBuilder sbf = new StringBuilder(); Clob clob = (Clob) original; try { try (BufferedReader br = new BufferedReader(clob.getCharacterStream(1, (int) clob.length()))) { if ((s = br.readLine()) != null) { sbf.append(s); } while ((s = br.readLine()) != null) { sbf.append(System.getProperty("line.separator")); sbf.append(s); } } } catch (IOException e) { throw new SQLException(e); } finally { clob.free(); } return sbf.toString(); } } return original; }

Target:
public static Object transformValue(int sqlColumnType, ResultSet resultSet, String fieldName) throws SQLException { Object original = resultSet.getObject(fieldName); if (original != null) { switch (sqlColumnType) { case Types.SMALLINT: case Types.TINYINT: return ((Number) original).intValue(); case Types.NUMERIC: case Types.DECIMAL: return ((BigDecimal) original).doubleValue(); case Types.DATE: return resultSet.getDate(fieldName).getTime(); case Types.TIME: return resultSet.getTime(fieldName).getTime(); case Types.TIMESTAMP: return resultSet.getTimestamp(fieldName).getTime(); case Types.BLOB: Blob blob = (Blob) original; try { return blob.getBytes(1, (int) blob.length()); } finally { blob.free(); } case Types.CLOB: Clob clob = (Clob) original; try { return clob.getSubString(1, (int) clob.length()); } finally { clob.free(); } } } return original; }
Source:
public long getLastAddConfirmed(long ledgerId) throws IOException { TransientLedgerInfo ledgerInfo = transientLedgerInfoCache.getIfPresent(ledgerId); Long lac = null != ledgerInfo ? ledgerInfo.getLastAddConfirmed() : null; if (null == lac) { ByteBuf bb = getEntry(ledgerId, BookieProtocol.LAST_ADD_CONFIRMED); bb.skipBytes(2 * Long.BYTES); lac = bb.readLong(); lac = transientLedgerInfoCache.getUnchecked(ledgerId).setLastAddConfirmed(lac); } return lac; }

Target:
public long getLastAddConfirmed(long ledgerId) throws IOException { TransientLedgerInfo ledgerInfo = transientLedgerInfoCache.getIfPresent(ledgerId); Long lac = null != ledgerInfo ? ledgerInfo.getLastAddConfirmed() : null; if (null == lac) { ByteBuf bb = getEntry(ledgerId, BookieProtocol.LAST_ADD_CONFIRMED); try { bb.skipBytes(2 * Long.BYTES); lac = bb.readLong(); lac = transientLedgerInfoCache.getUnchecked(ledgerId).setLastAddConfirmed(lac); } finally { bb.release(); } } return lac; }
Source:
KubernetesNamespace doCreateNamespaceAccess(String workspaceId, String name) { return new KubernetesNamespace(clientFactory, executor, name, workspaceId); }

Target:
KubernetesNamespace doCreateNamespaceAccess(String workspaceId, String name) { return new KubernetesNamespace(clientFactory, sharedPool.getExecutor(), name, workspaceId); }
Source:
private void removeFolderInternal(String id) { synchronized (mConfigLock) { Iterator<Folder> it = mConfig.folders.iterator(); while (it.hasNext()) { Folder f = it.next(); if (f.id.equals(id)) { it.remove(); } } } }

Target:
private void removeFolderInternal(String id) { synchronized (mConfigLock) { Iterator<Folder> it = mConfig.folders.iterator(); while (it.hasNext()) { Folder f = it.next(); if (f.id.equals(id)) { it.remove(); break; } } } }
Source:
public Set<String> variants(String identity) throws IllegalStateException { Config config = configurations.get(identity); if (config == null) { return null; } else { return config.variants(); } }

Target:
public Set<String> variants(String identity) throws IllegalArgumentException { Config config = configurations.get(identity); if (config == null) { throw new IllegalArgumentException("Identity " + identity + " does not exist."); } else { return config.variants(); } }
Source:
public <T extends DataSerializable> void registerBuilder(Class<T> clazz, DataBuilder<T> builder) { Preconditions.checkNotNull(clazz); Preconditions.checkNotNull(builder); if (!this.builders.containsKey(clazz)) { if (!(builder instanceof AbstractDataBuilder)) { SpongeImpl.getLogger().warn("A custom DataBuilder is not extending AbstractDataBuilder! It is recommended that " + "the custom data builder does extend it to gain automated content versioning updates and maintain " + "simplicity. The offending builder's class is: {}", builder.getClass()); } this.builders.put(clazz, builder); } else { SpongeImpl.getLogger().warn("A DataBuilder has already been registered for {}. Attempted to register instead.", clazz, builder.getClass()); } }

Target:
public <T extends DataSerializable> void registerBuilder(Class<T> clazz, DataBuilder<T> builder) { Preconditions.checkNotNull(clazz); Preconditions.checkNotNull(builder); DataBuilder<?> previousBuilder = this.builders.putIfAbsent(clazz, builder); if (previousBuilder != null) { SpongeImpl.getLogger().warn("A DataBuilder has already been registered for {}. Attempted to register instead.", clazz, builder.getClass()); } else if (!(builder instanceof AbstractDataBuilder)) { SpongeImpl.getLogger().warn("A custom DataBuilder is not extending AbstractDataBuilder! It is recommended that " + "the custom data builder does extend it to gain automated content versioning updates and maintain " + "simplicity. The offending builder's class is: {}", builder.getClass()); } }
Source:
private void killMuleProcesses() throws IOException { commands = new String[16]; commands[0] = "ps"; commands[1] = "-ax"; commands[2] = "|"; commands[3] = "grep"; commands[4] = "mule"; commands[5] = "|"; commands[6] = "grep"; commands[7] = "wrapper"; commands[8] = "|"; commands[9] = "cut"; commands[10] = "-c"; commands[11] = "1-5"; commands[12] = "|"; commands[13] = "xargs"; commands[14] = "kill"; commands[15] = "-9"; runtime.exec(commands); }

Target:
private void killMuleProcesses() throws IOException { commands.clear(); commands.add("ps"); commands.add("-ax"); commands.add("|"); commands.add("grep"); commands.add("mule"); commands.add("|"); commands.add("grep"); commands.add("wrapper"); commands.add("|"); commands.add("cut"); commands.add("-c"); commands.add("1-5"); commands.add("|"); commands.add("xargs"); commands.add("kill"); commands.add("-9"); runtime.exec(commands.toArray(new String[0])); }
Source:
public DefaultDockerClient build() { if (registryAuthCalled && registryAuthCSupplierCalled) { throw new RuntimeException("LOGIC ERROR: DefaultDockerClient does not support being built " + "with both `registryAuth` and `registryAuthSupplier`. " + "Please build with at most one of these options."); } if (dockerAuth) { try { this.registryAuth = RegistryAuth.fromDockerConfig().build(); } catch (IOException e) { log.warn("Unable to use Docker auth info", e); } } return new DefaultDockerClient(this); }

Target:
public DefaultDockerClient build() { if (dockerAuth) { try { this.registryAuth = RegistryAuth.fromDockerConfig().build(); } catch (IOException e) { log.warn("Unable to use Docker auth info", e); } } return new DefaultDockerClient(this); }
Source:
public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) { Comparator<IMethodInstance> comparator = new Comparator<IMethodInstance>() { private int getPriority(IMethodInstance mi) { int result = 0; Method method = mi.getMethod().getConstructorOrMethod().getMethod(); Priority a1 = method.getAnnotation(Priority.class); if (a1 != null) { result = a1.value(); } else { Class<?> cls = method.getDeclaringClass(); Priority classPriority = cls.getAnnotation(Priority.class); if (classPriority != null) { result = classPriority.value(); } } return result; } public int compare(IMethodInstance m1, IMethodInstance m2) { return getPriority(m1) - getPriority(m2); } }; methods.sort(comparator); methods.forEach(m -> { String clazz = m.getMethod().getInstance().getClass().getName() + "."; ordered.add(clazz + m.getMethod().getMethodName()); }); return methods; }

Target:
public List<IMethodInstance> intercept(List<IMethodInstance> methods, ITestContext context) { Comparator<IMethodInstance> comparator = Comparator.comparingInt(PriorityInterceptor::getPriority); methods.sort(comparator); return methods; }
Source:
public User getUserFromMessage(PerunSessionImpl sess, String message) throws InternalErrorException { List<PerunBean> perunBeans = AuditParser.parseLog(message); User user = null; UserExtSource userExtSource = null; Member member = null; for(PerunBean perunBean: perunBeans) { if(perunBean instanceof User) { user = (User) perunBean; break; } else if (perunBean instanceof UserExtSource && userExtSource == null) { userExtSource = (UserExtSource) perunBean; } else if (perunBean instanceof Member && member == null) { member = (Member) perunBean; } } if(user == null && userExtSource != null && userExtSource.getUserId() != -1) { try { user = getPerunBl().getUsersManagerBl().getUserById(sess, userExtSource.getUserId()); } catch (UserNotExistsException ex) { log.info("User from UserExtSource can't be found by id in Perun. Probably not exists any more or UserExtSource was audited without proper UserId!", userExtSource); return null; } } else if (user == null && member != null) { try { user = getPerunBl().getUsersManagerBl().getUserById(sess, member.getUserId()); } catch (UserNotExistsException ex) { log.info("User from Member can't be found by id in Perun. Probably not exists any more or Member was audited without proper UserId!", userExtSource); return null; } } return user; }

Target:
public User getUserFromMessage(PerunSessionImpl sess, String message) throws InternalErrorException { List<PerunBean> perunBeans = AuditParser.parseLog(message); User user = null; UserExtSource userExtSource = null; Member member = null; for(PerunBean perunBean: perunBeans) { if(perunBean instanceof User) { user = (User) perunBean; break; } else if (perunBean instanceof UserExtSource && userExtSource == null) { userExtSource = (UserExtSource) perunBean; } else if (perunBean instanceof Member && member == null) { member = (Member) perunBean; } } if(user == null && userExtSource != null && userExtSource.getUserId() != -1) { try { user = getPerunBl().getUsersManagerBl().getUserById(sess, userExtSource.getUserId()); } catch (UserNotExistsException ex) { log.debug("User from UserExtSource can't be found by id in Perun. Probably not exists any more or UserExtSource was audited without proper UserId!", userExtSource); return null; } } else if (user == null && member != null) { try { user = getPerunBl().getUsersManagerBl().getUserById(sess, member.getUserId()); } catch (UserNotExistsException ex) { log.debug("User from Member can't be found by id in Perun. Probably not exists any more or Member was audited without proper UserId!", userExtSource); return null; } } return user; }
Source:
public void testIsNotWorkspaceMetacard() { MetacardImpl metacard = new MetacardImpl(); metacard.setTags(ImmutableSet.of("hello", "world")); boolean isWorkspace = WorkspaceMetacardImpl.isWorkspaceMetacard(metacard); assertFalse(isWorkspace); }

Target:
public void testIsNotWorkspaceMetacard() { MetacardImpl metacard = new MetacardImpl(); metacard.setTags(ImmutableSet.of("hello", "world")); boolean isWorkspace = WorkspaceMetacardImpl.isWorkspaceMetacard(metacard); assertThat(isWorkspace, is(false)); }
Source:
public DetectRequest buildRequest(String location, InetAddress address, Integer port, Map<String, String> attributes) { return new DetectRequestImpl(address, port); }

Target:
public DetectRequest buildRequest(String location, InetAddress address, Integer port, Map<String, String> attributes) { return new DetectRequestImpl(address, port, attributes); }
Source:
private Owner findOwnerByIdOrKey(String id, String key) { Owner owner = null; if (id != null) { owner = this.ownerCurator.find(id); } if (owner == null && key != null) { owner = this.ownerCurator.lookupByKey(key); } if (owner == null) { throw new NotFoundException(i18n.tr("owner with key: {0} was not found.", key)); } return owner; }

Target:
private Owner findOwnerByIdOrKey(String id, String key) { if (id != null && !id.isEmpty()) { return this.findOwnerById(id); } else if (key != null && !key.isEmpty()) { return this.findOwnerByKey(key); } else { throw new BadRequestException(i18n.tr( "Owner lookup failed because id and key were null or empty.")); } }
Source:
private void processRemovedPages(ApplicationSentListingMessage applicationSentListingMessage) { List<WebkitPage> old = new ArrayList<WebkitPage>(); old.addAll(driver.getPages()); for (WebkitPage p : applicationSentListingMessage.getPages()) { old.remove(p); } for (WebkitPage p : old) { log.fine("the page " + p + " has been deleted and must be removed from the driver cache"); int currentFocus = driver.getCurrentPageID(); if (p.getPageId() == currentFocus) { log.fine("the page deleted is the one with the focus."); } else { driver.setPages(applicationSentListingMessage.getPages()); } } }

Target:
private void processRemovedPages(ApplicationSentListingMessage applicationSentListingMessage) { List<WebkitPage> old = new ArrayList<WebkitPage>(driver.getPages()); for (WebkitPage p : applicationSentListingMessage.getPages()) { old.remove(p); } for (WebkitPage p : old) { log.fine("the page " + p + " has been deleted and must be removed from the driver cache"); int currentFocus = driver.getCurrentPageID(); if (p.getPageId() == currentFocus) { log.fine("the page deleted is the one with the focus."); } else { driver.setPages(applicationSentListingMessage.getPages()); } } }
Source:
protected void updateBusyIndicator(CTabItem cti, MPart part, boolean busy) { IEclipseContext context = part.getContext(); CSSRenderingUtils renderingUtils = context.get(CSSRenderingUtils.class); if (renderingUtils == null) { return; } if (busy) { renderingUtils.addCSSClass(cti, CSSConstants.CSS_BUSY_CLASS); } else { renderingUtils.removeCSSClass(cti, CSSConstants.CSS_BUSY_CLASS); } }

Target:
protected void updateBusyIndicator(CTabItem cti, MPart part, boolean busy) { int tagsListCount = part.getTags().size(); boolean containsBusyTag = part.getTags().contains( CSSConstants.CSS_BUSY_CLASS); if (busy && !containsBusyTag) { part.getTags().add(CSSConstants.CSS_BUSY_CLASS); } else if (!busy && containsBusyTag) { part.getTags().remove(CSSConstants.CSS_BUSY_CLASS); } if (part.getTags().size() != tagsListCount) { setCSSInfo(part, cti); reapplyStyles(cti); } }
Source:
public void freeAABBTest() { Level check = new Level(emptyPlayer, emptyUnit, new Grid<>(Arrays.asList( Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL, Cell.EMPTY, Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL), 3, 3)); CollisionHandler handler = new CollisionHandler(check); Cell cell = handler.checkLevelAABB( new AABB(new Point(1, 1), new Point(2, 2)), new Point(0, 0)); assertTrue(cell.getType() == Cell.EMPTY); }

Target:
public void freeAABBTest() { Level check = new Level(emptyPlayer, emptyUnit, new Grid<>(Arrays.asList( Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL, Cell.EMPTY, Cell.WALL, Cell.WALL, Cell.WALL, Cell.WALL), 3, 3)); CollisionHandler handler = new CollisionHandler(check); Cell cell = handler.checkLevelAABB( new AABB(new Point(1, 1), new Point(2, 2)), new Point(0, 0)); assertEquals(cell, Cell.EMPTY); }
Source:
public void initializeChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if(transport != null) { pipeline.addLast("stats", new StatsChannelHandler(transport)); } SslConfiguration ssl = server.getConfiguration().ssl(); if (ssl.enabled()) { JdkSslContext defaultNettySslContext = createNettySslContext(ssl, ssl.sniDomainsConfiguration().get("*")); DomainMappingBuilder<JdkSslContext> domainMappingBuilder = new DomainMappingBuilder<>(defaultNettySslContext); ssl.sniDomainsConfiguration().forEach((k, v) -> { if (!"*".equals(k)) { domainMappingBuilder.add(k, createNettySslContext(ssl, v)); } }); pipeline.addLast("sni", new SniHandler(domainMappingBuilder.build())); } pipeline.addLast("decoder", server.getDecoder()); if (encoder != null) pipeline.addLast("encoder", encoder); }

Target:
public void initializeChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if(transport != null) { pipeline.addLast("stats", new StatsChannelHandler(transport)); } SslConfiguration ssl = server.getConfiguration().ssl(); if (ssl.enabled()) { JdkSslContext defaultNettySslContext = SslUtils.createNettySslContext(ssl, ssl.sniDomainsConfiguration().get("*")); DomainMappingBuilder<JdkSslContext> domainMappingBuilder = new DomainMappingBuilder<>(defaultNettySslContext); ssl.sniDomainsConfiguration().forEach((k, v) -> { if (!"*".equals(k)) { domainMappingBuilder.add(k, SslUtils.createNettySslContext(ssl, v)); } }); pipeline.addLast("sni", new SniHandler(domainMappingBuilder.build())); } pipeline.addLast("decoder", server.getDecoder()); if (encoder != null) pipeline.addLast("encoder", encoder); }
Source:
@Test public void callAdapterFactoryDelegateNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; DelegatingCallAdapterFactory delegatingFactory1 = new DelegatingCallAdapterFactory(); DelegatingCallAdapterFactory delegatingFactory2 = new DelegatingCallAdapterFactory(); NonMatchingCallAdapterFactory nonMatchingFactory = new NonMatchingCallAdapterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addCallAdapterFactory(delegatingFactory1) .addCallAdapterFactory(delegatingFactory2) .addCallAdapterFactory(nonMatchingFactory) .build(); try { retrofit.callAdapter(type, annotations); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("" + "Could not locate call adapter for class java.lang.String.\n" + " Skipped:\n" + " * retrofit2.helpers.DelegatingCallAdapterFactory\n" + " * retrofit2.helpers.DelegatingCallAdapterFactory\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingCallAdapterFactory\n" + " * retrofit2.DefaultCallAdapterFactory"); } assertThat(delegatingFactory1.called).isTrue(); assertThat(delegatingFactory2.called).isTrue(); assertThat(nonMatchingFactory.called).isTrue(); }

Target:
@Test public void callAdapterFactoryDelegateNoMatchThrows() { Type type = String.class; Annotation[] annotations = new Annotation[0]; DelegatingCallAdapterFactory delegatingFactory1 = new DelegatingCallAdapterFactory(); DelegatingCallAdapterFactory delegatingFactory2 = new DelegatingCallAdapterFactory(); NonMatchingCallAdapterFactory nonMatchingFactory = new NonMatchingCallAdapterFactory(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("<LINK_0>") .addCallAdapterFactory(delegatingFactory1) .addCallAdapterFactory(delegatingFactory2) .addCallAdapterFactory(nonMatchingFactory) .build(); try { retrofit.callAdapter(type, annotations); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("" + "Could not locate call adapter for class java.lang.String.\n" + " Skipped:\n" + " * retrofit2.helpers.DelegatingCallAdapterFactory\n" + " * retrofit2.helpers.DelegatingCallAdapterFactory\n" + " Tried:\n" + " * retrofit2.helpers.NonMatchingCallAdapterFactory\n" + " * retrofit2.DefaultCallAdapterFactory"); } assertThat(delegatingFactory1.called).isTrue(); assertThat(delegatingFactory2.called).isTrue(); assertThat(nonMatchingFactory.called).isTrue(); }
Source:
private boolean isEquivalentInboundRelationship(final Multimap<Concept, Concept> equivalentConcepts, Relationship relationshipToRemove, Relationship relationshipToKeep) { Concept sourceToKeep = relationshipToKeep.getSource(); Concept sourceToRemove = relationshipToRemove.getSource(); equivalentConcepts.get(sourceToKeep); return relationshipToRemove.getType().equals(relationshipToKeep.getType()) && (sourceToRemove.equals(sourceToKeep) || equivalentConcepts.get(sourceToKeep).contains(sourceToRemove)) && relationshipToRemove.getCharacteristicType().equals(relationshipToKeep.getCharacteristicType()) && relationshipToRemove.getModifier().equals(relationshipToKeep.getModifier()); }

Target:
private boolean isEquivalentInboundRelationship(final Multimap<Concept, Concept> equivalentConcepts, Relationship relationshipToRemove, Relationship relationshipToKeep) { Concept sourceToKeep = relationshipToKeep.getSource(); Concept sourceToRemove = relationshipToRemove.getSource(); return relationshipToRemove.getType().equals(relationshipToKeep.getType()) && (sourceToRemove.equals(sourceToKeep) || equivalentConcepts.get(sourceToKeep).contains(sourceToRemove)) && relationshipToRemove.getCharacteristicType().equals(relationshipToKeep.getCharacteristicType()) && relationshipToRemove.getModifier().equals(relationshipToKeep.getModifier()); }
Source:
public OpenshiftIORefreshException(IAccount account, Throwable t) { super("Error refreshing token for " + account.getId() + " on cluster " + account.getCluster().getId(), t); this.account = account; this.status = (-1); }

Target:
public OpenshiftIORefreshException(IAccount account, Throwable t) { super("Error refreshing token for " + account.getId() + " on cluster " + account.getCluster().getId(), t); this.account = account; this.status = NO_STATUS; }
Source:
@Test public void semiJoinCorrelateWithFilterCorrelateRule() { tester(false, new JdbcTest.HrSchema()) .query( "select empid, name from emps e where e.deptno in (select d.deptno from depts d) and e.empid > 100") .withHook(Hook.PLANNER, (Consumer<RelOptPlanner>) planner -> { planner.addRule(JoinToCorrelateRule.INSTANCE); planner.addRule(FilterCorrelateRule.INSTANCE); planner.removeRule(EnumerableRules.ENUMERABLE_JOIN_RULE); }) .explainContains("" + "EnumerableCalc(expr#0..3=[{inputs}], empid=[$t1], name=[$t3])\n" + " EnumerableCorrelate(correlation=[$cor4], joinType=[inner], requiredColumns=[{0}])\n" + " EnumerableAggregate(group=[{0}])\n" + " EnumerableTableScan(table=[[s, depts]])\n" + " EnumerableCalc(expr#0..4=[{inputs}], expr#5=[$cor4], expr#6=[$t5.deptno], expr#7=[=($t1, $t6)], expr#8=[100], expr#9=[>($t0, $t8)], expr#10=[AND($t7, $t9)], proj#0..2=[{exprs}], $condition=[$t10])\n" + " EnumerableTableScan(table=[[s, emps]])") .returnsUnordered( "empid=110; name=Theodore", "empid=150; name=Sebastian"); }

Target:
@Test public void semiJoinCorrelateWithFilterCorrelateRule() { tester(false, new JdbcTest.HrSchema()) .query( "select empid, name from emps e where e.deptno in (select d.deptno from depts d) and e.empid > 100") .withHook(Hook.PLANNER, (Consumer<RelOptPlanner>) planner -> { planner.addRule(JoinToCorrelateRule.INSTANCE); planner.addRule(FilterCorrelateRule.INSTANCE); planner.removeRule(EnumerableRules.ENUMERABLE_JOIN_RULE); }) .explainContains("" + "EnumerableCalc(expr#0..3=[{inputs}], empid=[$t1], name=[$t3])\n" + " EnumerableCorrelate(correlation=[$cor5], joinType=[inner], requiredColumns=[{0}])\n" + " EnumerableAggregate(group=[{0}])\n" + " EnumerableTableScan(table=[[s, depts]])\n" + " EnumerableCalc(expr#0..4=[{inputs}], expr#5=[100], expr#6=[>($t0, $t5)], expr#7=[$cor5], expr#8=[$t7.deptno], expr#9=[=($t1, $t8)], expr#10=[AND($t6, $t9)], proj#0..2=[{exprs}], $condition=[$t10])\n" + " EnumerableTableScan(table=[[s, emps]])") .returnsUnordered( "empid=110; name=Theodore", "empid=150; name=Sebastian"); }
Source:
protected Optional<String> getStringValue(BaseElement element) { List<ExtensionAttributeValue> extensionValues = element.getExtensionValues(); String globalVariables = null; if (extensionValues != null && extensionValues.size() > 0) { for (ExtensionAttributeValue extattrval : extensionValues) { FeatureMap extensionElements = extattrval.getValue(); List<GlobalType> globalTypeDataExtensions = (List<GlobalType>) extensionElements .get(DOCUMENT_ROOT__GLOBAL, true); for (GlobalType globalType : globalTypeDataExtensions) { if (globalType.getIdentifier() != null && globalType.getIdentifier().length() > 0 && globalType.getType() != null && globalType.getType().length() > 0) { String variable = globalType.getIdentifier() + ":" + globalType.getType(); if (globalVariables != null) { globalVariables += ","; } else { globalVariables = ""; } globalVariables += variable; } } } } return Optional.ofNullable(globalVariables); }

Target:
protected Optional<String> getStringValue(BaseElement element) { List<ExtensionAttributeValue> extValues = element.getExtensionValues(); List<FeatureMap> extElementsList = extValues.stream() .map(extAttrVal -> extAttrVal.getValue()) .collect(Collectors.toList()); List<GlobalType> globalExtensions = extElementsList.stream() .map(extAttrVal -> (List<GlobalType>) extAttrVal.get(DOCUMENT_ROOT__GLOBAL, true)) .flatMap(Collection::stream) .collect(Collectors.toList()); String globalVariables = globalExtensions.stream() .filter(globalType -> globalType.getIdentifier() != null && globalType.getIdentifier().length() > 0 && globalType.getType() != null && globalType.getType().length() > 0) .map(globalType -> globalType.getIdentifier() + ":" + globalType.getType()) .collect(Collectors.joining(",")); return Optional.ofNullable(globalVariables); }
Source:
public PictogramElement[] getSelections(PictogramElement selection) { if (selection instanceof Connection && !isConnectionSelectionEnabled()) { return null; } PictogramElement[] selections = { selection }; return selections; }

Target:
public PictogramElement[] getSelections(PictogramElement selection) { PictogramElement[] selections = { selection }; return selections; }
Source:
public Lz4Compressor(int directBufferSize, boolean useLz4HC) { this.useLz4HC = useLz4HC; this.directBufferSize = directBufferSize; try { LZ4Factory lz4Factory = LZ4Factory.fastestInstance(); if (useLz4HC) { lz4Compressor = lz4Factory.highCompressor(); } else { lz4Compressor = lz4Factory.fastCompressor(); } } catch (Throwable t) { throw new RuntimeException("lz4-java library is not available: " + "Lz4Compressor has not been loaded. You need to add " + "lz4-java.jar to your CLASSPATH", t); } uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); compressedDirectBuf.position(directBufferSize); }

Target:
public Lz4Compressor(int directBufferSize, boolean useLz4HC) { this.directBufferSize = directBufferSize; try { LZ4Factory lz4Factory = LZ4Factory.fastestInstance(); if (useLz4HC) { lz4Compressor = lz4Factory.highCompressor(); } else { lz4Compressor = lz4Factory.fastCompressor(); } } catch (AssertionError t) { throw new RuntimeException("lz4-java library is not available: " + "Lz4Compressor has not been loaded. You need to add " + "lz4-java.jar to your CLASSPATH. " + t, t); } uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize); this.dstCapacity = (directBufferSize) + ((directBufferSize) / 255) + 16; compressedDirectBuf = ByteBuffer.allocateDirect(this.dstCapacity); compressedDirectBuf.position(this.dstCapacity); }
Source:
public String getMessage(Bundle bundle, String value) { String result = value; if (bundle != null && result != null && result.startsWith(PERCENT)) { if (bundle != null && result != null && result.startsWith(PERCENT + PERCENT)) { return result.replaceFirst(PERCENT, EMPTY); } try { result = Platform.getResourceBundle(bundle).getString(result.substring(PERCENT.length())); } catch (MissingResourceException mre) { String message = MessageFormat.format(Messages.MessageTranslator_missingResourceMessage1, value) + value + MessageFormat.format(Messages.MessageTranslator_missingResourceMessage2, value); DslCommonPlugin.INSTANCE.log(new Status(IStatus.WARNING, bundle.getSymbolicName(), 0, message, mre)); } } return result; }

Target:
public String getMessage(Bundle bundle, String value) { String result = value; if (bundle != null && result != null && result.startsWith(PERCENT)) { if (bundle != null && result != null && result.startsWith(PERCENT + PERCENT)) { return result.replaceFirst(PERCENT, EMPTY); } try { result = Platform.getResourceBundle(bundle).getString(result.substring(PERCENT.length())); } catch (MissingResourceException mre) { String message = MessageFormat.format(Messages.MessageTranslator_missingResourceMessage, value) + value; DslCommonPlugin.INSTANCE.log(new Status(IStatus.WARNING, bundle.getSymbolicName(), 0, message, mre)); } } return result; }
Source:
private void initComponents() { GridBagConstraints constraints = new GridBagConstraints(); setLayout(new GridBagLayout()); JPanel teamMetaData = new JPanel(); teamMetaData.setOpaque(false); teamMetaData.setLayout(new GridBagLayout()); teamMetaData.setBorder(BorderFactory.createTitledBorder(Messages.getString("GamePanel.info"))); GridBagConstraints teamConstraint = new GridBagConstraints(); teamConstraint.fill = GridBagConstraints.BOTH; teamConstraint.gridx = 0; teamConstraint.gridy = 0; teamConstraint.insets = new Insets(5, 0, 5, 5); teamMetaData.add(new JLabel(Messages.getString("GamePanel.player")), teamConstraint); teamConstraint.weightx = 1.0; teamConstraint.gridx = 1; teamConstraint.insets = new Insets(5, 0, 5, 0); teamMetaData.add(mPlayerName, teamConstraint); teamConstraint.gridx = 0; teamConstraint.gridy = 1; teamConstraint.weightx = 0.0; teamMetaData.add(new JLabel(Messages.getString("GamePanel.status")), teamConstraint); teamConstraint.gridx = 1; teamConstraint.weightx = 1.0; teamMetaData.add(mTeamLabel, teamConstraint); teamConstraint.gridy = 2; teamConstraint.gridx = 0; teamConstraint.gridwidth = 2; teamConstraint.weighty = 0.1; teamConstraint.weightx = 1.0; teamMetaData.add(mJailPanel, teamConstraint); constraints.anchor = GridBagConstraints.BASELINE; constraints.fill = GridBagConstraints.BOTH; constraints.gridy = 0; constraints.weightx = 1.0; constraints.weighty = 0.5; constraints.gridwidth = 2; constraints.insets = new Insets(10, 10, 10, 10); add(teamMetaData, constraints); }

Target:
private void initComponents() { GridBagConstraints constraints = new GridBagConstraints(); setLayout(new GridBagLayout()); JPanel teamMetadata = new JPanel(); teamMetadata.setOpaque(false); teamMetadata.setLayout(new GridBagLayout()); teamMetadata.setBorder(BorderFactory.createTitledBorder(Messages.getString("GamePanel.info"))); GridBagConstraints teamConstraint = new GridBagConstraints(); teamConstraint.fill = GridBagConstraints.BOTH; teamConstraint.gridx = 0; teamConstraint.gridy = 0; teamConstraint.insets = new Insets(5, 0, 5, 5); teamMetadata.add(new JLabel(Messages.getString("GamePanel.player")), teamConstraint); teamConstraint.weightx = 1.0; teamConstraint.gridx = 1; teamConstraint.insets = new Insets(5, 0, 5, 0); teamMetadata.add(mPlayerName, teamConstraint); teamConstraint.gridx = 0; teamConstraint.gridy = 1; teamConstraint.weightx = 0.0; teamMetadata.add(new JLabel(Messages.getString("GamePanel.status")), teamConstraint); teamConstraint.gridx = 1; teamConstraint.weightx = 1.0; teamMetadata.add(mTeamLabel, teamConstraint); teamConstraint.gridy = 2; teamConstraint.gridx = 0; teamConstraint.gridwidth = 2; teamConstraint.weighty = 0.1; teamConstraint.weightx = 1.0; teamMetadata.add(mJailPanel, teamConstraint); constraints.anchor = GridBagConstraints.BASELINE; constraints.fill = GridBagConstraints.BOTH; constraints.gridy = 0; constraints.weightx = 1.0; constraints.weighty = 0.5; constraints.gridwidth = 2; constraints.insets = new Insets(10, 10, 10, 10); add(teamMetadata, constraints); }
Source:
private boolean validateAndCompleteParameters(QuotaConsumptionParametersWrapper parameters) { if (!checkAndCompleteStoragePool(parameters)) { return false; } if (QuotaEnforcementTypeEnum.DISABLED.equals(parameters.getStorage_pool().getQuotaEnforcementType())) { return true; } boolean hardEnforcement = QuotaEnforcementTypeEnum.HARD_ENFORCEMENT.equals(parameters.getStorage_pool().getQuotaEnforcementType()); if (null == parameters.getCanDoActionMessages() || null == parameters.getAuditLogable() || null == parameters.getParameters()){ if (hardEnforcement) { parameters.getCanDoActionMessages().add(VdcBllMessages.ACTION_TYPE_FAILED_QUOTA_IS_NOT_VALID.toString()); return false; } else { AUDIT_LOGGER.auditLog(parameters.getAuditLogable(), AuditLogType.MISSING_QUOTA_STORAGE_PARAMETERS_PERMISSIVE_MODE); return true; } } for (QuotaConsumptionParameter param : parameters.getParameters()) { boolean validQuotaId = checkAndFetchQuota(parameters, param); boolean validVdsGroup = checkVdsGroupMatchQuota(parameters, param); boolean validStorageDomain = checkStoragePoolMatchQuota(parameters, param); if (!validQuotaId || !validVdsGroup || !validStorageDomain) { if (hardEnforcement) { return false; } else { AUDIT_LOGGER.auditLog(parameters.getAuditLogable(), AuditLogType.MISSING_QUOTA_STORAGE_PARAMETERS_PERMISSIVE_MODE); parameters.getCanDoActionMessages().clear(); return true; } } } return true; }

Target:
private boolean validateAndCompleteParameters(QuotaConsumptionParametersWrapper parameters) { if (QuotaEnforcementTypeEnum.DISABLED.equals(parameters.getStorage_pool().getQuotaEnforcementType())) { return true; } boolean hardEnforcement = QuotaEnforcementTypeEnum.HARD_ENFORCEMENT.equals(parameters.getStorage_pool().getQuotaEnforcementType()); for (QuotaConsumptionParameter param : parameters.getParameters()) { boolean validQuotaId = checkAndFetchQuota(parameters, param); boolean validVdsGroup = false; if (param instanceof QuotaVdsConsumptionParameter) { validVdsGroup = checkVdsGroupMatchQuota(parameters, param); } else { validVdsGroup = true; } boolean validStorageDomain = false; if (param instanceof QuotaStorageConsumptionParameter) { validStorageDomain = checkStoragePoolMatchQuota(parameters, param); } else { validStorageDomain = true; } if (!validQuotaId || !validVdsGroup || !validStorageDomain) { if (hardEnforcement) { return false; } else { quotaManagerAuditLogger.auditLog(parameters.getAuditLogable(), AuditLogType.MISSING_QUOTA_STORAGE_PARAMETERS_PERMISSIVE_MODE); parameters.getCanDoActionMessages().clear(); return true; } } } return true; }
Source:
public List<RollingOperation> getRollingOperations(final String groupName) throws DeploymentGroupDoesNotExistException { final ZooKeeperClient client = provider.get("getRollingOperations"); final List<RollingOperation> ops = new ArrayList<RollingOperation>(); for (final String id : getRollingOperationIds(client, groupName)) { try { ops.add(getRollingOperation(client, id)); } catch (RollingOperationDoesNotExistException e) { } } return ImmutableList.copyOf(ops); }

Target:
public List<RollingOperation> getRollingOperations(final String groupName) throws DeploymentGroupDoesNotExistException { final ZooKeeperClient client = provider.get("getRollingOperations"); final List<RollingOperation> ops = new ArrayList<>(); for (final String id : getRollingOperationIds(client, groupName)) { try { ops.add(getRollingOperation(client, id)); } catch (RollingOperationDoesNotExistException e) { } } return ImmutableList.copyOf(ops); }
Source:
public void add(int value) { if (sparse) { try { sparseWriter.add(value); } catch (IllegalStateException e) { denseWriter = sparseWriter.transfer(denseWriter); denseWriter.add(value); sparse = false; } } else { denseWriter.add(value); if (!denseWriter.isDirty()) { sparse = true; } } }

Target:
public void add(int value) { if (sparse) { try { sparseWriter.add(value); } catch (IndexOutOfBoundsException e) { denseWriter = sparseWriter.transfer(); denseWriter.add(value); sparse = false; } } else { denseWriter.add(value); } }
Source:
static void assertBinFolderIsCleaned(IProject project) throws CoreException { IFolder bin = project.getFolder("bin"); assertTrue("Expected bin/ folder of project " + project.getName() + " to exist", bin.isAccessible()); class Visitor implements IResourceVisitor { List<IResource> contents = new ArrayList<>(); @Override public boolean visit(IResource resource) { if (!resource.equals(bin)) { contents.add(resource); } return true; } } Visitor visitor = new Visitor(); bin.accept(visitor); assertEquals("Expected bin folder to be empty", Collections.EMPTY_LIST, visitor.contents); }

Target:
static void assertBinFolderIsCleaned(IProject project) throws CoreException { IFolder bin = project.getFolder("bin"); assertTrue("Expected bin/ folder of project " + project.getName() + " to exist", bin.isAccessible()); assertEquals("Expected bin folder to be empty", Collections.EMPTY_LIST, Arrays.asList(bin.members())); }
Source:
private static MergeAlgorithm getMergeAlgorithm(Config config) { SupportedAlgorithm diffAlg = config.getEnum( ConfigConstants.CONFIG_DIFF_SECTION, null, ConfigConstants.CONFIG_KEY_ALGORITHM, SupportedAlgorithm.HISTOGRAM); return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg)); }

Target:
private static MergeAlgorithm getMergeAlgorithm(Config config) { SupportedAlgorithm diffAlg = config.getEnum( CONFIG_DIFF_SECTION, null, CONFIG_KEY_ALGORITHM, HISTOGRAM); return new MergeAlgorithm(DiffAlgorithm.getAlgorithm(diffAlg)); }
Source:
private int[] getHashes(byte[] read, int numberOfHashes, int skippedBases, int minReadLength) { int[] hashValues = new int[numberOfHashes]; for (int i = 0; i < numberOfHashes; ++i) { hashValues[i] = 1; int position = skippedBases + i; while (position < minReadLength) { hashValues[i] = 31 * hashValues[i] + read[position]; position += numberOfHashes; } } return hashValues; }

Target:
private int[] getHashes(byte[] read, int numberOfHashes, int skippedBases, int minReadLength) { final int[] hashValues = new int[numberOfHashes]; for (int i = 0; i < numberOfHashes; ++i) { hashValues[i] = 1; int position = skippedBases + i; while (position < minReadLength) { hashValues[i] = 31 * hashValues[i] + read[position]; position += numberOfHashes; } } return hashValues; }
Source:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_account); ButterKnife.bind(this); setNavigationBarColor(ResourceUtil.getThemedColor(this, R.attr.paper_color)); if (ReadingListSyncAdapter.isDisabledByRemoteConfig()) { onboardingContainer.setVisibility(View.GONE); } errorView.setBackClickListener((v) -> onBackPressed()); errorView.setRetryClickListener((v) -> errorView.setVisibility(View.GONE)); wiki = WikipediaApp.getInstance().getWikiSite(); captchaHandler = new CaptchaHandler(this, WikipediaApp.getInstance().getWikiSite(), primaryContainer, getString(R.string.create_account_activity_title), getString(R.string.create_account_button)); new NonEmptyValidator((isValid) -> createAccountButton.setEnabled(isValid), usernameInput, passwordInput); new NonEmptyValidator((isValid) -> createAccountButtonCaptcha.setEnabled(isValid), captchaText); captchaText.setOnKeyListener((v, keyCode, event) -> { if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_ENTER)) { validateThenCreateAccount(); return true; } return false; }); usernameInput.getEditText().addTextChangedListener(userNameTextWatcher); if (savedInstanceState != null && savedInstanceState.containsKey("result")) { createAccountResult = savedInstanceState.getParcelable("result"); } funnel = new CreateAccountFunnel(WikipediaApp.getInstance(), getIntent().getStringExtra(LOGIN_REQUEST_SOURCE)); if (savedInstanceState == null) { funnel.logStart(getIntent().getStringExtra(LOGIN_SESSION_TOKEN)); } setResult(RESULT_ACCOUNT_NOT_CREATED); }

Target:
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_create_account); ButterKnife.bind(this); if (ReadingListSyncAdapter.isDisabledByRemoteConfig()) { onboardingContainer.setVisibility(View.GONE); } errorView.setBackClickListener((v) -> onBackPressed()); errorView.setRetryClickListener((v) -> errorView.setVisibility(View.GONE)); wiki = WikipediaApp.getInstance().getWikiSite(); captchaHandler = new CaptchaHandler(this, WikipediaApp.getInstance().getWikiSite(), primaryContainer, getString(R.string.create_account_activity_title), getString(R.string.create_account_button)); new NonEmptyValidator((isValid) -> createAccountButton.setEnabled(isValid), usernameInput, passwordInput); new NonEmptyValidator((isValid) -> createAccountButtonCaptcha.setEnabled(isValid), captchaText); captchaText.setOnKeyListener((v, keyCode, event) -> { if ((event.getAction() == KeyEvent.ACTION_UP) && (keyCode == KeyEvent.KEYCODE_ENTER)) { validateThenCreateAccount(); return true; } return false; }); usernameInput.getEditText().addTextChangedListener(userNameTextWatcher); if (savedInstanceState != null && savedInstanceState.containsKey("result")) { createAccountResult = savedInstanceState.getParcelable("result"); } funnel = new CreateAccountFunnel(WikipediaApp.getInstance(), getIntent().getStringExtra(LOGIN_REQUEST_SOURCE)); if (savedInstanceState == null) { funnel.logStart(getIntent().getStringExtra(LOGIN_SESSION_TOKEN)); } setResult(RESULT_ACCOUNT_NOT_CREATED); }
Source:
public void testGetContainerReplicaWithParallelUpdate() throws Exception { testGetContainerWithPipeline(); final Optional<ContainerID> id = containerManager.getContainerIDs() .stream().findFirst(); Assert.assertTrue(id.isPresent()); final ContainerID cId = id.get(); final Optional<ContainerReplica> replica = containerManager .getContainerReplicas(cId).stream().findFirst(); Assert.assertTrue(replica.isPresent()); final ContainerReplica cReplica = replica.get(); final AtomicBoolean runUpdaterThread = new AtomicBoolean(true); Thread updaterThread = new Thread(() -> { while (runUpdaterThread.get()) { try { containerManager.removeContainerReplica(cId, cReplica); containerManager.updateContainerReplica(cId, cReplica); } catch (ContainerNotFoundException e) { e.printStackTrace(); } catch (ContainerReplicaNotFoundException e) { Assert.fail("Missing Container Replica for " + id); } } }); updaterThread.setDaemon(true); updaterThread.start(); IntStream.range(0, 10).forEach(i -> { try { Assert.assertNotNull(containerManager .getContainerReplicas(cId) .stream().map(ContainerReplica::getDatanodeDetails) .collect(Collectors.toSet())); } catch (ContainerNotFoundException e) { Assert.fail("Missing Container " + id); } }); runUpdaterThread.set(false); }

Target:
public void testGetContainerReplicaWithParallelUpdate() throws Exception { testGetContainerWithPipeline(); final Optional<ContainerID> id = containerManager.getContainerIDs() .stream().findFirst(); Assert.assertTrue(id.isPresent()); final ContainerID cId = id.get(); final Optional<ContainerReplica> replica = containerManager .getContainerReplicas(cId).stream().findFirst(); Assert.assertTrue(replica.isPresent()); final ContainerReplica cReplica = replica.get(); final AtomicBoolean runUpdaterThread = new AtomicBoolean(true); Thread updaterThread = new Thread(() -> { while (runUpdaterThread.get()) { try { containerManager.removeContainerReplica(cId, cReplica); containerManager.updateContainerReplica(cId, cReplica); } catch (ContainerException e) { Assert.fail("Container Exception: " + e.getMessage()); } } }); updaterThread.setDaemon(true); updaterThread.start(); IntStream.range(0, 100).forEach(i -> { try { Assert.assertNotNull(containerManager .getContainerReplicas(cId) .stream().map(ContainerReplica::getDatanodeDetails) .collect(Collectors.toSet())); } catch (ContainerNotFoundException e) { Assert.fail("Missing Container " + id); } }); runUpdaterThread.set(false); }