auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Response updateWifiInfo(@Scope(OAuthScope.DEVICE_INFORMATION_WRITE) final AccessToken accessToken, @Valid final WifiInfo wifiInfo){ final Boolean hasUpserted = deviceProcessor.upsertWifiInfo(accessToken.accountId, wifiInfo); if (!hasUpserted) { throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to upsert wifi info for sense %s", wifiInfo.senseId))).build()); } return Response.noContent().build(); }

Target:
public Response updateWifiInfo(@Scope(OAuthScope.DEVICE_INFORMATION_WRITE) final AccessToken accessToken, @Valid final WifiInfo wifiInfo){ try { final Boolean hasUpserted = deviceProcessor.upsertWifiInfo(accessToken.accountId, wifiInfo); if (!hasUpserted) { throw new WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR) .entity(new JsonError(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), String.format("Failed to upsert wifi info for sense %s", wifiInfo.senseId))).build()); } } catch (DeviceProcessor.InvalidWifiInfoException iwe) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity(new JsonError(Response.Status.BAD_REQUEST.getStatusCode(), iwe.getMessage())).build()); } return Response.noContent().build(); }
Source:
public long timestampNanoToCycles(long nanos){ long retVal; if(getInverseTimeScale() != 1.0 ) { retVal = (long) (nanos * getInverseTimeScale()); } else { retVal = nanos; } return retVal - getOffset(); }

Target:
public long timestampNanoToCycles(long nanos){ long retVal; if( clockNeedsScale() ) { retVal = (long) (nanos * getInverseTimeScale()); } else { retVal = nanos; } return retVal - getOffset(); }
Source:
public String showCityCenter( @RequestParam Map<String, String> allRequestParams, Model model) { LOGGER.info("Requested params:" + allRequestParams); Player player = playerService.getPlayerByLogin(playerLogin); CityCenterDto cityCenterDto = cityCenterService.cityCenterInfo(); cityCenterDto.setResourceDto(new ResourceDto(player.getPlayerResources().getGold(), player.getPlayerResources().getTimber(), player.getPlayerResources().getClay(), player.getPlayerResources().getCorn())); cityCenterDto.setNickName(player.getLogin()); model.addAttribute("dto", cityCenterDto); LOGGER.info("Out:" + model); return "city_center"; }

Target:
public String showCityCenter( @RequestParam Map<String, String> allRequestParams, Model model) { LOGGER.info("Requested params:" + allRequestParams); CityCenterDto cityCenterDto = cityCenterService.cityCenterInfo(); model.addAttribute("dto", cityCenterDto); LOGGER.info("Out:" + model); return "city_center"; }
Source:
public boolean pingDB() { logger.debug("JDBC::pingDB"); boolean ret = false; long timerStart = System.currentTimeMillis(); if (openConnection()) { if (conf.getDbName() == null) { logger.debug( "JDBC::pingDB asking db for name as absolutelly first db action, after connection is established."); String dbName = conf.getDBDAO().doGetDB(); conf.setDbName(dbName); ret = dbName.length() > 0; } else { ret = conf.getDBDAO().doPingDB() > 0; } } logTime("pingDB", timerStart, System.currentTimeMillis()); return ret; }

Target:
public boolean pingDB() { logger.debug("JDBC::pingDB"); boolean ret = false; long timerStart = System.currentTimeMillis(); if (openConnection()) { if (conf.getDbName() == null) { logger.debug( "JDBC::pingDB asking db for name as absolutely first db action, after connection is established."); String dbName = conf.getDBDAO().doGetDB(); conf.setDbName(dbName); ret = dbName.length() > 0; } else { ret = conf.getDBDAO().doPingDB() > 0; } } logTime("pingDB", timerStart, System.currentTimeMillis()); return ret; }
Source:
public void appendDelta(Delta d) { deltas.add(d); if (uncommittedChanges instanceof AtomicHashMap) { uncommittedChanges = (AtomicHashMap<K, ?>) d.merge(uncommittedChanges); } setChanged(true); }

Target:
public void appendDelta(Delta d) { deltas.add(d); if (uncommittedChanges != null) { uncommittedChanges = (AtomicHashMap<K, ?>) d.merge(uncommittedChanges); } setChanged(true); }
Source:
public void asyncReadEntries(final long firstEntry, final long lastEntry, final ReadCallback cb, final Object ctx) { if (bk.isStopped()) { cb.readComplete(-1, MockLedgerHandle.this, null, ctx); return; } bk.executor.execute(new Runnable() { public void run() { if (bk.getProgrammedFailStatus()) { cb.readComplete(bk.failReturnCode, MockLedgerHandle.this, null, ctx); return; } else if (bk.isStopped()) { log.debug("Bookkeeper is closed!"); cb.readComplete(-1, MockLedgerHandle.this, null, ctx); return; } log.debug("readEntries: first={} last={} total={}", firstEntry, lastEntry, entries.size()); final Queue<LedgerEntry> seq = new ArrayDeque<LedgerEntry>(); long entryId = firstEntry; while (entryId <= lastEntry && entryId < entries.size()) { seq.add(new LedgerEntry(entries.get((int) entryId++).duplicate())); } log.debug("Entries read: {}", seq); try { Thread.sleep(1); } catch (InterruptedException e) { } cb.readComplete(0, MockLedgerHandle.this, new Enumeration<LedgerEntry>() { public boolean hasMoreElements() { return !seq.isEmpty(); } public LedgerEntry nextElement() { return seq.remove(); } }, ctx); } }); }

Target:
public void asyncReadEntries(final long firstEntry, final long lastEntry, final ReadCallback cb, final Object ctx) { if (bk.isStopped()) { cb.readComplete(-1, MockLedgerHandle.this, null, ctx); return; } bk.executor.execute(new Runnable() { public void run() { if (bk.getProgrammedFailStatus()) { cb.readComplete(bk.failReturnCode, MockLedgerHandle.this, null, ctx); return; } else if (bk.isStopped()) { log.debug("Bookkeeper is closed!"); cb.readComplete(-1, MockLedgerHandle.this, null, ctx); return; } log.debug("readEntries: first={} last={} total={}", firstEntry, lastEntry, entries.size()); final Queue<LedgerEntry> seq = new ArrayDeque<LedgerEntry>(); long entryId = firstEntry; while (entryId <= lastEntry && entryId < entries.size()) { seq.add(new LedgerEntry(entries.get((int) entryId++))); } log.debug("Entries read: {}", seq); try { Thread.sleep(1); } catch (InterruptedException e) { } cb.readComplete(0, MockLedgerHandle.this, new Enumeration<LedgerEntry>() { public boolean hasMoreElements() { return !seq.isEmpty(); } public LedgerEntry nextElement() { return seq.remove(); } }, ctx); } }); }
Source:
public static List<Field> getDeclaredFieldsIncludingParent(Class<?> current) { if (fieldCache.containsKey(current)) { return fieldCache.get(current); } Class<?> start = current; List<Field> fields = new ArrayList<>(); while (current != null) { List<Field> declared = Arrays.asList(current.getDeclaredFields()); fields.addAll(declared); current = current.getSuperclass(); } fieldCache.put(start, fields); return fields; }

Target:
public static List<Field> getDeclaredFieldsIncludingParent(Class<?> current) { if (fieldCache.containsKey(current)) { return fieldCache.get(current); } List<Field> fields = new ArrayList<>(); fieldCache.put(current, fields); while (current != null) { List<Field> declared = Arrays.asList(current.getDeclaredFields()); fields.addAll(declared); current = current.getSuperclass(); } return fields; }
Source:
private String determineHandlerLocation(String lsRegisterDump, String scheme) throws Exception { String[] lsRegisterEntries = lsRegisterDump.split("-{80}\n"); String keyOfFirstLine; String prefixOfSchemeList; if (Stream.of(lsRegisterEntries).parallel().anyMatch(s -> s.startsWith("BundleClass:"))) { keyOfFirstLine = "BundleClass"; prefixOfSchemeList = "bindings:"; } else { keyOfFirstLine = "bundle id"; prefixOfSchemeList = "claimed schemes:"; } String lines = "(?:.*\\n)*"; Pattern pattern = Pattern.compile( "^" + lines + "\\s*" + PATH_WITH_CAPUTERING_GROUP + "\\n" + lines + "\\s*" + prefixOfSchemeList + ".*" + Pattern.quote(scheme) + ":", Pattern.MULTILINE); String path = Stream.of(lsRegisterEntries). parallel(). filter(s -> s.startsWith(keyOfFirstLine)). filter(s -> s.contains(scheme + ":")). map(s -> pattern.matcher(s)). filter(m -> m.find()). map(m -> m.group(1)).findFirst().map(s -> s.replaceFirst(TRAILING_HEX_VALUE_WITH_BRACKETS, "")) .orElse(""); return path; }

Target:
private String determineHandlerLocation(String lsRegisterDump, String scheme) throws Exception { String[] lsRegisterEntries = lsRegisterDump.split("-{80}\n"); String keyOfFirstLine; String keyOfSchemeList; if (Stream.of(lsRegisterEntries).parallel().anyMatch(s -> s.startsWith("BundleClass:"))) { keyOfFirstLine = "BundleClass"; keyOfSchemeList = "bindings:"; } else { keyOfFirstLine = "bundle id"; keyOfSchemeList = "claimed schemes:"; } Pattern pattern = Pattern.compile( "^" + ANY_LINES + "\\s*" + PATH_WITH_CAPTURING_GROUP + "\\n" + ANY_LINES + "\\s*" + keyOfSchemeList + ".*" + Pattern.quote(scheme) + ":", Pattern.MULTILINE); String path = Stream.of(lsRegisterEntries). parallel(). filter(s -> s.startsWith(keyOfFirstLine)). filter(s -> s.contains(scheme + ":")). map(s -> pattern.matcher(s)). filter(m -> m.find()). map(m -> m.group(1)).findFirst().map(s -> s.replaceFirst(TRAILING_HEX_VALUE_WITH_BRACKETS, "")) .orElse(""); return path; }
Source:
public Set<Type<?>> findAnnotatedClasses(Class annotationClass) throws ClassNotFoundException { Set<Type<?>> annotatedClasses = new HashSet<>(); compiledObjects.values().forEach(classz -> { if (classz.getAnnotation(annotationClass) != null) { annotatedClasses.add(getType(classz)); } }); return annotatedClasses; }

Target:
public Set<Class<?>> findAnnotatedClasses(Class annotationClass) throws ClassNotFoundException { Set<Class<?>> annotatedClasses = new HashSet<Class<?>>(); compiledObjects.values().forEach(classz -> { if (classz.getAnnotation(annotationClass) != null) { annotatedClasses.add(classz); } }); return annotatedClasses; }
Source:
private String getContainersDescriptionForLogging() { List<ContainerTemplate> containers = getContainers(); StringBuilder sb = new StringBuilder(); for (ContainerTemplate ct : containers) { sb.append("* ).append(ct.getName()).append( ").append(ct.getImage()); StringBuilder optional = new StringBuilder(); optionalField(optional, "resourceRequestCpu", ct.getResourceRequestCpu()); optionalField(optional, "resourceRequestMemory", ct.getResourceRequestMemory()); optionalField(optional, "resourceLimitCpu", ct.getResourceLimitCpu()); optionalField(optional, "resourceLimitMemory", ct.getResourceLimitMemory()); if (optional.length() > 0) { sb.append("(").append(optional).append(")"); } sb.append("\n"); } if (getYamls().size() > 0 && isShowRawYaml()) { for (String yaml : getYamls()) { sb.append("yaml:\n") .append(yaml) .append("\n"); } } return sb.toString(); }

Target:
private String getContainersDescriptionForLogging() { List<ContainerTemplate> containers = getContainers(); StringBuilder sb = new StringBuilder(); for (ContainerTemplate ct : containers) { sb.append("* ).append(ct.getName()).append( ").append(ct.getImage()); StringBuilder optional = new StringBuilder(); optionalField(optional, "resourceRequestCpu", ct.getResourceRequestCpu()); optionalField(optional, "resourceRequestMemory", ct.getResourceRequestMemory()); optionalField(optional, "resourceLimitCpu", ct.getResourceLimitCpu()); optionalField(optional, "resourceLimitMemory", ct.getResourceLimitMemory()); if (optional.length() > 0) { sb.append("(").append(optional).append(")"); } sb.append("\n"); } if (isShowRawYaml()) { for (String yaml : getYamls()) { sb.append("yaml:\n") .append(yaml) .append("\n"); } } return sb.toString(); }
Source:
private boolean processMedia(Uri mediaUri) { if (mediaUri == null) { return false; } Activity activity = EditPostActivity.this; if (!MediaUtils.isInMediaStore(mediaUri) && !mediaUri.toString().startsWith("/") && !mediaUri.toString().startsWith("file://")) { mediaUri = MediaUtils.downloadExternalMedia(activity, mediaUri); } String path = MediaUtils.getRealPathFromURI(activity, mediaUri); if (path == null) { return false; } final boolean isVideo = MediaUtils.isVideo(mediaUri.toString()); Uri optimizedMedia = WPMediaUtils.getOptimizedMedia(activity, path, isVideo); if (optimizedMedia != null) { mediaUri = optimizedMedia; } else if (mShowNewEditor || mShowAztecEditor) { if (!mSite.isWPCom()) { Uri rotatedMedia = WPMediaUtils.fixOrientationIssue(activity, path, isVideo); if (rotatedMedia != null) { mediaUri = rotatedMedia; } } else { if (mShowNewEditor) { Uri rotatedMedia = WPMediaUtils.fixOrientationIssue(activity, path, isVideo); if (rotatedMedia != null) { path = MediaUtils.getRealPathFromURI(activity, rotatedMedia); } } } } trackAddMediaFromDeviceEvents(isNew, isVideo, mediaUri); postProcessMedia(mediaUri, path, isVideo); return true; }

Target:
private boolean processMedia(Uri mediaUri) { if (mediaUri == null) { return false; } Activity activity = EditPostActivity.this; String path = MediaUtils.getRealPathFromURI(activity, mediaUri); if (path == null) { return false; } final boolean isVideo = MediaUtils.isVideo(mediaUri.toString()); Uri optimizedMedia = WPMediaUtils.getOptimizedMedia(activity, path, isVideo); if (optimizedMedia != null) { mediaUri = optimizedMedia; } else if (mShowNewEditor || mShowAztecEditor) { if (!mSite.isWPCom()) { Uri rotatedMedia = WPMediaUtils.fixOrientationIssue(activity, path, isVideo); if (rotatedMedia != null) { mediaUri = rotatedMedia; } } else { if (mShowNewEditor) { Uri rotatedMedia = WPMediaUtils.fixOrientationIssue(activity, path, isVideo); if (rotatedMedia != null) { path = MediaUtils.getRealPathFromURI(activity, rotatedMedia); } } } } if (isInterrupted()) { return false; } trackAddMediaFromDeviceEvents(isNew, isVideo, mediaUri); postProcessMedia(mediaUri, path, isVideo); return true; }
Source:
private void dataCenterWithClusterSelectedItemChanged(Object sender, EventArgs args) { String selectedTimeZone = null; Integer selectedOsId = null; if (getTimeZone().getSelectedItem() != null) { selectedTimeZone = getTimeZone().getSelectedItem().getTimeZoneKey().toString(); } if (getOSType().getSelectedItem() != null) { selectedOsId = getOSType().getSelectedItem(); } behavior.dataCenterWithClusterSelectedItemChanged(); refreshMigrationPolicies(); updateMigrationRelatedFields(); DataCenterWithCluster dataCenterWithCluster = getDataCenterWithClustersList().getSelectedItem(); if (dataCenterWithCluster != null && dataCenterWithCluster.getDataCenter() != null) { getDisksAllocationModel().setQuotaEnforcementType(dataCenterWithCluster.getDataCenter() .getQuotaEnforcementType()); } updateMigrationOptions(); handleQxlClusterLevel(); updateWatchdogModels(); updateBootMenu(); getInstanceImages().updateActionsAvailability(); initGraphicsConsoles(); updateSoundCard(); updateResumeBehavior(); updateBiosType(); if (selectedOsId != null) { getOSType().setSelectedItem(selectedOsId); } if (selectedTimeZone != null && !selectedTimeZone.isEmpty()) { getBehavior().updateTimeZone(selectedTimeZone); } }

Target:
private void dataCenterWithClusterSelectedItemChanged(Object sender, EventArgs args) { String selectedTimeZone = ""; Integer selectedOsId = null; if (getTimeZone().getSelectedItem() != null) { selectedTimeZone = getTimeZone().getSelectedItem().getTimeZoneKey().toString(); } if (getOSType().getSelectedItem() != null) { selectedOsId = getOSType().getSelectedItem(); } behavior.dataCenterWithClusterSelectedItemChanged(); refreshMigrationPolicies(); updateMigrationRelatedFields(); DataCenterWithCluster dataCenterWithCluster = getDataCenterWithClustersList().getSelectedItem(); if (dataCenterWithCluster != null && dataCenterWithCluster.getDataCenter() != null) { getDisksAllocationModel().setQuotaEnforcementType(dataCenterWithCluster.getDataCenter() .getQuotaEnforcementType()); } updateMigrationOptions(); handleQxlClusterLevel(); updateWatchdogModels(); updateBootMenu(); getInstanceImages().updateActionsAvailability(); initGraphicsConsoles(); updateSoundCard(); updateResumeBehavior(); updateBiosType(); if (selectedOsId != null) { getOSType().setSelectedItem(selectedOsId); } if (!selectedTimeZone.isEmpty()) { getBehavior().updateTimeZone(selectedTimeZone); } }
Source:
private void showMultiLingualOnboarding() { if (Prefs.getShowSearchTutorial()) { FeedbackUtil.showTapTargetView(getActivity(), langButton, R.string.empty, R.string.tool_tip_lang_button, null); } Prefs.setShowSearchOnboarding(false); }

Target:
private void showMultiLingualOnboarding() { if (Prefs.getShowSearchTutorial()) { FeedbackUtil.showTapTargetView(requireActivity(), langButton, R.string.empty, R.string.tool_tip_lang_button, null); Prefs.setShowSearchOnboarding(false); } }
Source:
public static void deleteFileOrDirectory(File file) throws IOException { Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); }

Target:
public static void deleteFileOrDirectory(File file) throws IOException { if (file.exists()) { Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); return FileVisitResult.CONTINUE; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { Files.delete(dir); return FileVisitResult.CONTINUE; } }); } }
Source:
public void testEncryptDecryptKeyVersion(AESKeyVersion keyVersion) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String testinput = "weak"; byte[] encTxt = keyVersion.encryptString(testinput); String result = keyVersion.decryptString(encTxt); assertEquals(testinput, result); testinput = ""; encTxt = keyVersion.encryptString(testinput); result = keyVersion.decryptString(encTxt); assertEquals(testinput, result); }

Target:
public void testEncryptDecryptKeyVersion(AESKeyVersion keyVersion) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String testinput = "weak"; byte[] encTxt = encryptString(keyVersion, testinput); String result = decryptString(keyVersion, encTxt); assertEquals(testinput, result); testinput = ""; encTxt = encryptString(keyVersion, testinput); result = decryptString(keyVersion, encTxt); assertEquals(testinput, result); }
Source:
private boolean checkIfListenersHaveDataToSendOnly() { synchronized (DataList.this) { for (DataListener dl : all_listeners) { try { if (dl.addedData(true)) { return true; } } catch (RuntimeException e) { logger.error("{}: removing DataListener due to exception", DataList.this, dl, e); removeDataListener(dl); return checkIfListenersHaveDataToSendOnly(); } } return false; } }

Target:
private boolean checkIfListenersHaveDataToSendOnly() { for (DataListener dl : all_listeners) { try { if (dl.addedData(true)) { return true; } } catch (RuntimeException e) { logger.error("{}: removing DataListener due to exception", DataList.this, dl, e); removeDataListener(dl); return checkIfListenersHaveDataToSendOnly(); } } return false; }
Source:
private Issue createJiraIssue(AbstractBuild<?, ?> build, String filename) throws IOException, InterruptedException { EnvVars vars = build.getEnvironment(TaskListener.NULL); String summary = String.format("Build %s failed", getBuildName(vars)); String checkDescription = (this.testDescription.equals("")) ? "No description is provided" : this.testDescription; String description = String.format("%s\n\nThe build %s has failed.\nFirst failed run: %s", checkDescription, getBuildName(vars), getBuildDetailsString(vars)); List<BasicComponent> components = getJiraComponents(build, this.component); JiraSession session = getJiraSession(build); Issue issue = session.createIssue(projectKey, description, assignee, components, summary); writeInFile(filename, issue); return issue; }

Target:
private Issue createJiraIssue(AbstractBuild<?, ?> build, String filename) throws IOException, InterruptedException { EnvVars vars = build.getEnvironment(TaskListener.NULL); String buildName = getBuildName(vars); String summary = String.format("Build %s failed", buildName); String description = String.format( "%s\n\nThe build %s has failed.\nFirst failed run: %s", (this.testDescription.equals("")) ? "No description is provided" : this.testDescription, buildName, getBuildDetailsString(vars) ); List<BasicComponent> components = getJiraComponents(build, this.component); JiraSession session = getJiraSession(build); Issue issue = session.createIssue(projectKey, description, assignee, components, summary); writeInFile(filename, issue); return issue; }
Source:
public void onShowTimeDateTimePicker() { view.showTimeDate(false); String value = view.getTimeDate(); try { Date date = view.parseFromISO(value); view.setTimeDateTimePickerValue(date); } catch (Exception e) { view.setTimeDateTimePickerValue(value); } view.showTimeDateTimePicker(true); }

Target:
public void onShowTimeDateTimePicker() { view.showTimeDate(false); String value = view.getTimeDate(); try { Date date = view.parseFromISO(value); view.setTimeDateTimePickerValue(date); } catch (IllegalArgumentException e) { view.setTimeDateTimePickerValue(value); } view.showTimeDateTimePicker(true); }
Source:
public void testStateTransferWithRequestorsForNonExistentL1Value() throws Exception { L1Manager l1Manager = c1.getAdvancedCache().getComponentRegistry().getComponent(L1Manager.class); l1Manager.addRequestor(key, c3.getCacheManager().getAddress()); assertNull(c3.get(key)); CheckPoint checkPoint = new CheckPoint(); waitUntilToplogyInstalled(c3, checkPoint); waitUntilBeforeTopologyInstalled(c1, checkPoint); waitUntilBeforeTopologyInstalled(c2, checkPoint); factory.setMembersTouse(new boolean[]{true, false, true, false}); EmbeddedCacheManager cm = addClusterEnabledCacheManager(configuration); Future<Void> join = fork(new Callable<Void>() { @Override public Void call() throws Exception { waitForClusterToForm(cacheName); log.debug("4th has joined"); return null; } }); checkPoint.awaitStrict("post_topology_installed_invoked_" + c3, 10, TimeUnit.SECONDS); checkPoint.awaitStrict("pre_topology_installed_invoked_" + c1, 10, TimeUnit.SECONDS); checkPoint.awaitStrict("pre_topology_installed_invoked_" + c2, 10, TimeUnit.SECONDS); assertNull(c1.put(key, newValue)); checkPoint.triggerForever("post_topology_installed_released_" + c3); checkPoint.triggerForever("pre_topology_installed_released_" + c1); checkPoint.triggerForever("pre_topology_installed_released_" + c2); join.get(10, TimeUnit.SECONDS); assertIsInContainerImmortal(c1, key); assertIsNotInL1(c2, key); assertIsInContainerImmortal(c3, key); assertIsNotInL1(cm.getCache(cacheName), key); }

Target:
public void testStateTransferWithRequestorsForNonExistentL1Value() throws Exception { L1Manager l1Manager = c1.getAdvancedCache().getComponentRegistry().getComponent(L1Manager.class); l1Manager.addRequestor(key, c3.getCacheManager().getAddress()); assertNull(c3.get(key)); CheckPoint checkPoint = new CheckPoint(); waitUntilToplogyInstalled(c3, checkPoint); waitUntilBeforeTopologyInstalled(c1, checkPoint); waitUntilBeforeTopologyInstalled(c2, checkPoint); factory.setMembersToUse(new boolean[]{true, false, true, false}); EmbeddedCacheManager cm = addClusterEnabledCacheManager(configuration); Future<Void> join = fork(new Callable<Void>() { @Override public Void call() throws Exception { waitForClusterToForm(cacheName); log.debug("4th has joined"); return null; } }); checkPoint.awaitStrict("post_topology_installed_invoked_" + c3, 10, TimeUnit.SECONDS); checkPoint.awaitStrict("pre_topology_installed_invoked_" + c1, 10, TimeUnit.SECONDS); checkPoint.awaitStrict("pre_topology_installed_invoked_" + c2, 10, TimeUnit.SECONDS); assertNull(c1.put(key, newValue)); checkPoint.triggerForever("post_topology_installed_released_" + c3); checkPoint.triggerForever("pre_topology_installed_released_" + c1); checkPoint.triggerForever("pre_topology_installed_released_" + c2); join.get(10, TimeUnit.SECONDS); assertIsInContainerImmortal(c1, key); assertIsNotInL1(c2, key); assertIsInContainerImmortal(c3, key); assertIsNotInL1(cm.getCache(cacheName), key); assertTrue(DistributionTestHelper.isOwner(c1, key)); assertFalse(DistributionTestHelper.isOwner(c2, key)); assertTrue(DistributionTestHelper.isOwner(c3, key)); assertFalse(DistributionTestHelper.isOwner(cm.getCache(cacheName), key)); }
Source:
public void testPublishWithSameName() throws IOException { MetricsSystem metrics = DefaultMetricsSystem.instance(); metrics.init("test"); PrometheusMetricsSink sink = new PrometheusMetricsSink(); metrics.register("Prometheus", "Prometheus", sink); metrics.register("FooBar", "fooBar", (MetricsSource) (collector, all) -> { collector.addRecord("RpcMetrics").add(new MetricsTag(PORT_INFO, "1234")) .addGauge(COUNTER_INFO, 123).endRecord(); collector.addRecord("RpcMetrics").add(new MetricsTag( PORT_INFO, "2345")).addGauge(COUNTER_INFO, 234).endRecord(); }); metrics.start(); metrics.publishMetricsNow(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(stream, UTF_8); sink.writeMetrics(writer); writer.flush(); String writtenMetrics = stream.toString(UTF_8.name()); System.out.println(writtenMetrics); Assert.assertTrue( "The expected metric line is missing from prometheus metrics output", writtenMetrics.contains( "rpc_metrics_counter{port=\"2345\"")); Assert.assertTrue( "The expected metric line is missing from prometheus metrics " + "output", writtenMetrics.contains( "rpc_metrics_counter{port=\"1234\"")); metrics.stop(); metrics.shutdown(); }

Target:
public void testPublishWithSameName() throws IOException { MetricsSystem metrics = DefaultMetricsSystem.instance(); metrics.init("test"); PrometheusMetricsSink sink = new PrometheusMetricsSink(); metrics.register("Prometheus", "Prometheus", sink); metrics.register("FooBar", "fooBar", (MetricsSource) (collector, all) -> { collector.addRecord("RpcMetrics").add(new MetricsTag(PORT_INFO, "1234")) .addGauge(COUNTER_INFO, 123).endRecord(); collector.addRecord("RpcMetrics").add(new MetricsTag( PORT_INFO, "2345")).addGauge(COUNTER_INFO, 234).endRecord(); }); metrics.start(); metrics.publishMetricsNow(); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(stream, UTF_8); sink.writeMetrics(writer); writer.flush(); String writtenMetrics = stream.toString(UTF_8.name()); Assert.assertTrue( "The expected metric line is missing from prometheus metrics output", writtenMetrics.contains( "rpc_metrics_counter{port=\"2345\"")); Assert.assertTrue( "The expected metric line is missing from prometheus metrics " + "output", writtenMetrics.contains( "rpc_metrics_counter{port=\"1234\"")); metrics.stop(); metrics.shutdown(); }
Source:
public Assertion validate(final String ticketId, final String service) { final org.apereo.cas.validation.Assertion ass = cas.validateServiceTicket(ticketId, () -> service); return new AssertionImpl(new AttributePrincipalImpl( ass.getPrimaryAuthentication().getPrincipal().getId(), ass.getPrimaryAuthentication().getPrincipal().getAttributes())); }

Target:
public Assertion validate(final String ticketId, final String service) { val assertion = cas.validateServiceTicket(ticketId, () -> service); val principal = assertion.getPrimaryAuthentication().getPrincipal(); return new AssertionImpl(new AttributePrincipalImpl(principal.getId(), principal.getAttributes())); }
Source:
private Observable.Transformer<BoundStatement, Integer> applyMicroBatching() { return tObservable -> tObservable .groupBy(b -> { ByteBuffer routingKey = b.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED, codecRegistry); Token token = metadata.newToken(routingKey); for (TokenRange tokenRange : session.getCluster().getMetadata().getTokenRanges()) { if (tokenRange.contains(token)) { return tokenRange; } } throw new RuntimeException("Unable to find any Cassandra node to insert token " + token.toString()); }) .flatMap(g -> g.compose(new BoundBatchStatementTransformer())) .flatMap(batch -> rxSession .execute(batch) .compose(applyInsertRetryPolicy()) .map(resultSet -> batch.size()) ); }

Target:
private Observable.Transformer<BoundStatement, Integer> applyMicroBatching() { return tObservable -> tObservable .groupBy(b -> { ByteBuffer routingKey = b.getRoutingKey(ProtocolVersion.NEWEST_SUPPORTED, codecRegistry); Token token = metadata.newToken(routingKey); for (TokenRange tokenRange : session.getCluster().getMetadata().getTokenRanges()) { if (tokenRange.contains(token)) { return tokenRange; } } log.warn("Unable to find any Cassandra node to insert token " + token.toString()); return session.getCluster().getMetadata().getTokenRanges().iterator().next(); }) .flatMap(g -> g.compose(new BoundBatchStatementTransformer())) .flatMap(batch -> rxSession .execute(batch) .compose(applyInsertRetryPolicy()) .map(resultSet -> batch.size()) ); }
Source:
public Variant(int index, String name, String url, int bitrate, String codecs, int width, int height) { this.url = url; if (name != null) { format = new Format(name, MimeTypes.APPLICATION_M3U8, width, height, -1, -1, -1, bitrate, null, codecs); } else { format = new Format(Integer.toString(index), MimeTypes.APPLICATION_M3U8, width, height, -1, -1, -1, bitrate, null, codecs); } }

Target:
public Variant(int index, String name, String url, int bitrate, String codecs, int width, int height) { this.url = url; this.name = name; String formatName = name != null ? name : Integer.toString(index); format = new Format(formatName, MimeTypes.APPLICATION_M3U8, width, height, -1, -1, -1, bitrate, null, codecs); }
Source:
private JsonElement evaluate(LDUser user, FeatureStore featureStore, List<FeatureRequestEvent> events, Set<String> visited) { boolean prereqOk = true; for (Prerequisite prereq : prerequisites) { visited.add(key); if (visited.contains(prereq.getKey())) { logger.error("Prerequisite cycle detected when evaluating feature flag: " + key); return null; } FeatureFlag prereqFeatureFlag = featureStore.get(prereq.getKey()); JsonElement prereqEvalResult = null; if (prereqFeatureFlag == null) { logger.error("Could not retrieve prerequisite flag: " + prereq.getKey() + " when evaluating: " + key); return null; } else if (prereqFeatureFlag.isOn()) { prereqEvalResult = prereqFeatureFlag.evaluate(user, featureStore, events, visited); if (prereqEvalResult == null || !prereqEvalResult.equals(prereqFeatureFlag.getVariation(prereq.getVariation()))) { prereqOk = false; } } else { prereqOk = false; } events.add(new FeatureRequestEvent(prereqFeatureFlag.getKey(), user, prereqEvalResult, null)); } if (prereqOk) { return getVariation(evaluateIndex(user)); } return null; }

Target:
private JsonElement evaluate(LDUser user, FeatureStore featureStore, List<FeatureRequestEvent> events, Set<String> visited) { boolean prereqOk = true; visited.add(key); for (Prerequisite prereq : prerequisites) { if (visited.contains(prereq.getKey())) { logger.error("Prerequisite cycle detected when evaluating feature flag: " + key); return null; } FeatureFlag prereqFeatureFlag = featureStore.get(prereq.getKey()); JsonElement prereqEvalResult = null; if (prereqFeatureFlag == null) { logger.error("Could not retrieve prerequisite flag: " + prereq.getKey() + " when evaluating: " + key); return null; } else if (prereqFeatureFlag.isOn()) { prereqEvalResult = prereqFeatureFlag.evaluate(user, featureStore, events, visited); if (prereqEvalResult == null || !prereqEvalResult.equals(prereqFeatureFlag.getVariation(prereq.getVariation()))) { prereqOk = false; } } else { prereqOk = false; } events.add(new FeatureRequestEvent(prereqFeatureFlag.getKey(), user, prereqEvalResult, null)); } if (prereqOk) { return getVariation(evaluateIndex(user)); } return null; }
Source:
public boolean isArticleTextDisplayed() { scrollToSelector(".article-content p"); return articleContent.isDisplayed(); }

Target:
public boolean isArticleTextDisplayed() { wait.forElementPresent(By.cssSelector(".article-content p")); scrollToSelector(".article-content p"); return articleContent.isDisplayed(); }
Source:
void giveBack(V object) { Preconditions.checkNotNull(object, "object"); synchronized (this) { if (closed) { log.info(String.format("giveBack called after being closed. key[%s]", key)); factory.close(object); return; } if (resourceHolderList.size() >= maxSize) { if (resourceHolderList.stream().filter(a -> a.getResource().equals(object)).findAny().isPresent()) { log.warn( String.format( "Returning object[%s] at key[%s] that has already been returned!? Skipping", object, key ), new Exception("Exception for stacktrace") ); } else { log.warn( String.format( "Returning object[%s] at key[%s] even though we already have all that we can hold[%s]!? Skipping", object, key, resourceHolderList ), new Exception("Exception for stacktrace") ); } return; } resourceHolderList.addLast(new ResourceHolder<>(System.currentTimeMillis(), object)); this.notifyAll(); } }

Target:
void giveBack(V object) { Preconditions.checkNotNull(object, "object"); synchronized (this) { if (closed) { log.info(String.format("giveBack called after being closed. key[%s]", key)); factory.close(object); return; } if (resourceHolderList.size() >= maxSize) { if (holderListContains(object)) { log.warn( String.format( "Returning object[%s] at key[%s] that has already been returned!? Skipping", object, key ), new Exception("Exception for stacktrace") ); } else { log.warn( String.format( "Returning object[%s] at key[%s] even though we already have all that we can hold[%s]!? Skipping", object, key, resourceHolderList ), new Exception("Exception for stacktrace") ); } return; } resourceHolderList.addLast(new ResourceHolder<>(System.currentTimeMillis(), object)); this.notifyAll(); } }
Source:
public int hashCode() { int hash = 7; hash = 89 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; }

Target:
public int hashCode() { return name.hashCode(); }
Source:
public PushdownSubfieldsIntoConnector(Metadata metadata) { this.metadata = metadata; }

Target:
public PushdownSubfieldsIntoConnector(Metadata metadata) { this.metadata = requireNonNull(metadata, "metadata is null"); }
Source:
public @NonNull String @NonNull getFullAttribute() { LinkedList<String> list = new LinkedList<>(); Attribute curNode = this; while (curNode.parent != null) { list.addFirst(curNode.getName()); curNode = curNode.parent; } return list.toArray(new @NonNull String[0]); }

Target:
public @NonNull String @NonNull getFullAttribute() { LinkedList<String> list = new LinkedList<>(); Attribute curNode = this; while (curNode.parent != null) { list.addFirst(curNode.getName()); curNode = curNode.parent; } return list.toArray(new @NonNull String[list.size()]); }
Source:
public boolean refreshBpTaskList() { boolean changed = false; LOG.debug("Running Back Pressure status change check"); for (Iterator<Entry<Integer, JCQueue>> itr = bpTasks.entrySet().iterator(); itr.hasNext(); ) { Entry<Integer, JCQueue> entry = itr.next(); if (entry.getValue().isEmptyOverflow()) { nonBpTasks.add(entry.getKey()); itr.remove(); changed = true; } } return changed; }

Target:
public boolean refreshBpTaskList() { boolean changed = false; LOG.debug("Running Back Pressure status change check"); for ( Entry<Integer, JCQueue> entry : tasks.entrySet()) { if (entry.getValue() != NONE && entry.getValue().isEmptyOverflow()) { recordNoBackPressure(entry.getKey()); changed = true; } } return changed; }
Source:
public Blob getBlob(String key) { TransientStore store = Framework.getService(TransientStoreService.class).getStore(CSVExportAction.ACTION_NAME); List<Blob> blobs = store.getBlobs(key); Blob blob = blobs == null || blobs.isEmpty() ? null : blobs.get(0); if (blob == null) { log.error("[%s] Could not retrieve blob for key {}", metadata.name(), key); } return blob; }

Target:
public Blob getBlob(String key) { TransientStore store = Framework.getService(TransientStoreService.class).getStore(CSVExportAction.ACTION_NAME); List<Blob> blobs = store.getBlobs(key); Blob blob = blobs == null || blobs.isEmpty() ? null : blobs.get(0); if (blob == null) { log.error("[{}] Could not retrieve blob for key {}", metadata.name(), key); } return blob; }
Source:
public ASTNode visit(org.kframework.kil.Variable node, Void _) { String name = node.getName(); if (node.isFreshVariable()) { name = "?" + name; } else if (node.isFreshConstant()) { name = "!" + name; } if (node.getSort().equals(org.kframework.kil.Sort.BAG)) { return new Variable(name, Kind.CELL_COLLECTION.asSort()); } if (node.getSort().equals(org.kframework.kil.Sort.K)) { return new Variable(name, Sort.KSEQUENCE); } if (node.getSort().equals(org.kframework.kil.Sort.KLIST)) { return new Variable(name, Sort.KLIST); } DataStructureSort dataStructureSort = context.dataStructureSortOf(node.getSort()); if (dataStructureSort != null) { Sort sort = null; if (dataStructureSort.type().equals(org.kframework.kil.Sort.LIST)) { sort = Sort.LIST; } else if (dataStructureSort.type().equals(org.kframework.kil.Sort.MAP)) { sort = Sort.MAP; } else if (dataStructureSort.type().equals(org.kframework.kil.Sort.SET)) { sort = Sort.SET; } else { assert false: "unexpected data structure " + dataStructureSort.type(); } if (concreteCollectionSize.containsKey(node)) { return new ConcreteCollectionVariable( name, sort, concreteCollectionSize.get(node)); } else { return new Variable(name, sort); } } return new Variable(name, node.getSort().toBackendJava()); }

Target:
public ASTNode visit(org.kframework.kil.Variable node, Void _) { String name = node.fullName(); if (node.getSort().equals(org.kframework.kil.Sort.BAG)) { return new Variable(name, Kind.CELL_COLLECTION.asSort()); } if (node.getSort().equals(org.kframework.kil.Sort.K)) { return new Variable(name, Sort.KSEQUENCE); } if (node.getSort().equals(org.kframework.kil.Sort.KLIST)) { return new Variable(name, Sort.KLIST); } DataStructureSort dataStructureSort = context.dataStructureSortOf(node.getSort()); if (dataStructureSort != null) { Sort sort = null; if (dataStructureSort.type().equals(org.kframework.kil.Sort.LIST)) { sort = Sort.LIST; } else if (dataStructureSort.type().equals(org.kframework.kil.Sort.MAP)) { sort = Sort.MAP; } else if (dataStructureSort.type().equals(org.kframework.kil.Sort.SET)) { sort = Sort.SET; } else { assert false: "unexpected data structure " + dataStructureSort.type(); } if (concreteCollectionSize.containsKey(node)) { return new ConcreteCollectionVariable( name, sort, concreteCollectionSize.get(node)); } else { return new Variable(name, sort); } } return new Variable(name, node.getSort().toBackendJava()); }
Source:
private void removeSplitItemViews(){ final int childCount = mDetailTableLayout.getChildCount(); for (int i = 0; i < childCount; i++) { if (mDetailTableLayout.getChildAt(0).getId() == R.id.row_split_amount_info) { mDetailTableLayout.removeViewAt(0); } else { break; } } mDebitBalance.setText(""); mCreditBalance.setText(""); }

Target:
private void removeSplitItemViews(){ mDetailTableLayout.removeViews(0, mDetailTableLayout.getChildCount() - mDetailTableRows); mDebitBalance.setText(""); mCreditBalance.setText(""); }
Source:
public ItemDefinition build() { if( !AEConfig.instance().areFeaturesEnabled( this.features ) ) { return new ItemDefinition( this.registryName, null ); } Item item = this.itemSupplier.get(); item.setRegistryName( AppEng.MOD_ID, this.registryName ); ItemDefinition definition = new ItemDefinition( this.registryName, item ); item.setUnlocalizedName( "appliedenergistics2." + this.registryName ); item.setCreativeTab( this.creativeTab ); this.preInitCallbacks.forEach( consumer -> this.factory.<IPreInitComponent>addBootstrapComponent( side -> consumer.accept( item ) ) ); this.initCallbacks.forEach( consumer -> this.factory.<IInitComponent>addBootstrapComponent( side -> consumer.accept( item ) ) ); this.modelRegCallbacks .forEach( consumer -> this.factory.<IModelRegistrationComponent>addBootstrapComponent( ( side, reg ) -> consumer.accept( item ) ) ); this.postInitCallbacks.forEach( consumer -> this.factory.<IPostInitComponent>addBootstrapComponent( side -> consumer.accept( item ) ) ); if( this.dispenserBehaviorSupplier != null ) { this.factory.<IPostInitComponent>addBootstrapComponent( side -> { IBehaviorDispenseItem behavior = this.dispenserBehaviorSupplier.get(); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject( item, behavior ); } ); } this.factory.<IItemRegistrationComponent>addBootstrapComponent( ( side, reg ) -> reg.register( item ) ); if( Platform.isClient() ) { this.itemRendering.apply( this.factory, item ); } return definition; }

Target:
public ItemDefinition build() { if( !AEConfig.instance().areFeaturesEnabled( this.features ) ) { return new ItemDefinition( this.registryName, null ); } Item item = this.itemSupplier.get(); item.setRegistryName( AppEng.MOD_ID, this.registryName ); ItemDefinition definition = new ItemDefinition( this.registryName, item ); item.setUnlocalizedName( "appliedenergistics2." + this.registryName ); item.setCreativeTab( this.creativeTab ); this.boostrapComponents.forEach( component -> component.apply( item ) ); if( this.dispenserBehaviorSupplier != null ) { this.factory.addBootstrapComponent( (IPostInitComponent) side -> { IBehaviorDispenseItem behavior = this.dispenserBehaviorSupplier.get(); BlockDispenser.DISPENSE_BEHAVIOR_REGISTRY.putObject( item, behavior ); } ); } this.factory.addBootstrapComponent( (IItemRegistrationComponent) ( side, reg ) -> reg.register( item ) ); if( Platform.isClient() ) { this.itemRendering.apply( this.factory, item ); } return definition; }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((deleted == null) ? 0 : deleted.hashCode()); result = prime * result + ((developerId == null) ? 0 : developerId.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((reason == null) ? 0 : reason.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); result = prime * result + ((statusDate == null) ? 0 : statusDate.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); return result; }
Source:
public PagarMeModel getMovementObjectAsPagarmeObject() { PagarMeModel movementObjectAsPagarMeModel = null; switch (this.type) { case ANTICIPATION: movementObjectAsPagarMeModel = new BulkAnticipation(); break; case PAYABLE: movementObjectAsPagarMeModel = new Payable(); break; case TRANSFER: movementObjectAsPagarMeModel = new Transfer(); break; } return JSONUtils.getAsObject((JsonObject) movementObject, movementObjectAsPagarMeModel.getClass()); }

Target:
public PagarMeModel getMovementObjectAsPagarmeObject() { PagarMeModel movementObjectAsPagarMeModel = null; if(this.type.equals("anticipation")) movementObjectAsPagarMeModel = new BulkAnticipation(); else if(this.type.equals("payable")) movementObjectAsPagarMeModel = new Payable(); else if(this.type.equals("transfer")) movementObjectAsPagarMeModel = new Transfer(); else movementObjectAsPagarMeModel = new MovementObject(); return JSONUtils.getAsObject((JsonObject) movementObject, movementObjectAsPagarMeModel.getClass()); }
Source:
FeatureStateConsumer(Builder builder, BiConsumer<String, FeatureStateStorageWrapper> updateHandler) { Properties properties = new Properties(); properties.setProperty(BOOTSTRAP_SERVERS_CONFIG, requireNonNull(builder.bootstrapServers)); properties.setProperty(KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); properties.setProperty(VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); properties.setProperty(ENABLE_AUTO_COMMIT_CONFIG, "false"); this.kafkaConsumer = new KafkaConsumer<>(properties); this.updateHandler = updateHandler; this.inboundTopic = requireNonNull(builder.inboundTopic); this.pollingTimeout = requireNonNull(builder.pollingTimeout); this.offsets = new ConcurrentHashMap<>(); this.initializationLatch = new CountDownLatch(1); this.initializationTimeout = requireNonNull(builder.initializationTimeout); this.shutdownLatch = new CountDownLatch(1); running = false; consumerLag = Long.MAX_VALUE; }

Target:
private FeatureStateConsumer(Builder builder, BiConsumer<String, FeatureStateStorageWrapper> updateHandler) { Properties properties = new Properties(); properties.setProperty(BOOTSTRAP_SERVERS_CONFIG, requireNonNull(builder.bootstrapServers)); properties.setProperty(KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); properties.setProperty(VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName()); properties.setProperty(ENABLE_AUTO_COMMIT_CONFIG, "false"); this.kafkaConsumer = new KafkaConsumer<>(properties); this.updateHandler = updateHandler; this.inboundTopic = requireNonNull(builder.inboundTopic); this.pollingTimeout = requireNonNull(builder.pollingTimeout); this.offsets = new ConcurrentHashMap<>(); this.initializationLatch = new CountDownLatch(1); this.initializationTimeout = requireNonNull(builder.initializationTimeout); this.shutdownLatch = new CountDownLatch(1); running = false; consumerLag = Long.MAX_VALUE; }
Source:
@Test public void testMkdirsShouldReturnFalseWhenFallbackFSNotAvailable() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(Constants.CONFIG_VIEWFS_MOUNT_LINKS_AS_SYMLINKS, false); ConfigUtil.addLink(conf, "/user1/test", new Path(targetTestRoot.toString()).toUri()); Path fallbackTarget = new Path(targetTestRoot, "fallbackDir"); fsTarget.mkdirs(fallbackTarget); ConfigUtil.addLinkFallback(conf, fallbackTarget.toUri()); try (FileSystem vfs = FileSystem.get(viewFsDefaultClusterUri, conf)) { Path nextLevelToInternalDir = new Path("/user1/test1"); Path test = Path.mergePaths(fallbackTarget, nextLevelToInternalDir); assertFalse(fsTarget.exists(test)); assertNotNull(vfs.getFileStatus(new Path("/user1"))); assertFalse(fsTarget.exists(test.getParent())); cluster.shutdownNameNodes(); assertFalse(vfs.mkdirs(nextLevelToInternalDir)); cluster.restartNameNodes(); assertTrue(vfs.mkdirs(nextLevelToInternalDir)); assertTrue(fsTarget.exists(test)); } }

Target:
public void testMkdirsShouldReturnFalseWhenFallbackFSNotAvailable() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(Constants.CONFIG_VIEWFS_MOUNT_LINKS_AS_SYMLINKS, false); ConfigUtil.addLink(conf, "/user1/test", new Path(targetTestRoot.toString()).toUri()); Path fallbackTarget = new Path(targetTestRoot, "fallbackDir"); fsTarget.mkdirs(fallbackTarget); ConfigUtil.addLinkFallback(conf, fallbackTarget.toUri()); try (FileSystem vfs = FileSystem.get(viewFsDefaultClusterUri, conf)) { Path nextLevelToInternalDir = new Path("/user1/test1"); Path test = Path.mergePaths(fallbackTarget, nextLevelToInternalDir); assertFalse(fsTarget.exists(test)); assertNotNull(vfs.getFileStatus(new Path("/user1"))); assertFalse(fsTarget.exists(test.getParent())); cluster.shutdownNameNodes(); assertFalse(vfs.mkdirs(nextLevelToInternalDir)); cluster.restartNameNodes(); assertTrue(vfs.mkdirs(nextLevelToInternalDir)); assertTrue(fsTarget.exists(test)); } }
Source:
public Map<String, ImmutableWorkerInfo> getWorkersEligibleToRunTasks() { return Maps.transformEntries( Maps.filterEntries( workers, input -> !lazyWorkers.containsKey(input.getKey()) && !workersWithUnacknowledgedTask.containsKey(input.getKey()) && !blackListedWorkers.containsKey(input.getKey()) && input.getValue().isInitialized() && input.getValue().isEnabled() ), (String key, WorkerHolder value) -> value.toImmutable() ); }

Target:
Map<String, ImmutableWorkerInfo> getWorkersEligibleToRunTasks() { return Maps.transformEntries( Maps.filterEntries( workers, input -> !lazyWorkers.containsKey(input.getKey()) && !workersWithUnacknowledgedTask.containsKey(input.getKey()) && !blackListedWorkers.containsKey(input.getKey()) && input.getValue().isInitialized() && input.getValue().isEnabled() ), (String key, WorkerHolder value) -> value.toImmutable() ); }