auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected boolean addVmImages() { if (getVmTemplate().getDiskTemplateMap().size() > 0) { if (getVm().getStatus() != VMStatus.Down) { log.error("Cannot add images. VM is not Down"); throw new EngineException(EngineError.IRS_IMAGE_STATUS_ILLEGAL); } VmHandler.lockVm(getVm().getDynamicData(), getCompensationContext()); Collection<DiskImage> templateDisks = getVmTemplate().getDiskTemplateMap().values(); List<DiskImage> diskImages = ImagesHandler.filterImageDisks(templateDisks, true, false, true); for (DiskImage disk : diskImages) { VdcReturnValueBase result = runInternalActionWithTasksContext( VdcActionType.CreateCloneOfTemplate, buildCreateCloneOfTemplateParameters(disk) ); if (!result.getSucceeded()) { throw new EngineException(result.getFault().getError()); } getTaskIdList().addAll(result.getInternalVdsmTaskIdList()); DiskImage newImage = (DiskImage) result.getActionReturnValue(); getSrcDiskIdToTargetDiskIdMapping().put(disk.getId(), newImage.getId()); } List<CinderDisk> cinderDisks = ImagesHandler.filterDisksBasedOnCinder(templateDisks); if (!cinderDisks.isEmpty()) { addVmCinderDisks(cinderDisks); } } return true; }

Target:
protected boolean addVmImages() { if (getVmTemplate().getDiskTemplateMap().size() > 0) { if (getVm().getStatus() != VMStatus.Down) { log.error("Cannot add images. VM is not Down"); throw new EngineException(EngineError.IRS_IMAGE_STATUS_ILLEGAL); } VmHandler.lockVm(getVm().getDynamicData(), getCompensationContext()); Collection<DiskImage> templateDisks = getVmTemplate().getDiskTemplateMap().values(); List<DiskImage> diskImages = ImagesHandler.filterImageDisks(templateDisks, true, false, true); for (DiskImage disk : diskImages) { VdcReturnValueBase result = runInternalActionWithTasksContext( VdcActionType.CreateCloneOfTemplate, buildCreateCloneOfTemplateParameters(disk) ); if (!result.getSucceeded()) { throw new EngineException(result.getFault().getError()); } getTaskIdList().addAll(result.getInternalVdsmTaskIdList()); DiskImage newImage = (DiskImage) result.getActionReturnValue(); getSrcDiskIdToTargetDiskIdMapping().put(disk.getId(), newImage.getId()); } addVmCinderDisks(templateDisks); } return true; }
Source:
public void undo(long tid, Master env) throws Exception { for (ImportedTableInfo.DirectoryMapping dm : tableInfo.directories) { env.getFileSystem().deleteRecursively(new Path(dm.importDir)); } }

Target:
public void undo(long tid, Master env) throws Exception { for (ImportedTableInfo.DirectoryMapping dm : tableInfo.directories) { env.getVolumeManager().deleteRecursively(new Path(dm.importDir)); } }
Source:
public Element(String locator) { this.locatorType = null; this.locator = locator; }

Target:
public Element(String locator) { this(null, locator); }
Source:
protected void captureThrowable(Runnable c) { try { c.run(); } catch (Throwable e) { e.printStackTrace(); asyncExceptions.add(e); } }

Target:
protected void captureThrowable(Runnable c) { try { c.run(); } catch (Throwable e) { LOG.error("Captured error: {}", e); asyncExceptions.add(e); } }
Source:
protected List<ShowRoomCategory> getShowRoomCategories() { Random random = new Random(); int recommendedPage; if (recommendedShowRoomPageCount > 0) { recommendedPage = random.nextInt(recommendedShowRoomPageCount) + 1; } else { recommendedPage = 1; } return Arrays.asList( new ShowRoomCategory(() -> mapService.getRecommendedMapsWithPageCount(TOP_ELEMENT_COUNT, recommendedPage), SearchType.RECOMMENDED, "mapVault.recommended"), new ShowRoomCategory(() -> mapService.getHighestRatedMapsWithPageCount(TOP_ELEMENT_COUNT, 1), SearchType.HIGHEST_RATED, "mapVault.mostLikedMaps"), new ShowRoomCategory(() -> mapService.getNewestMapsWithPageCount(TOP_ELEMENT_COUNT, 1), SearchType.NEWEST, "mapVault.newestMaps"), new ShowRoomCategory(() -> mapService.getMostPlayedMapsWithPageCount(TOP_ELEMENT_COUNT, 1), SearchType.PLAYED, "mapVault.mostPlayed"), new ShowRoomCategory(() -> mapService.getOwnedMapsWithPageCount(TOP_ELEMENT_COUNT, 1), SearchType.OWN, "mapVault.owned")); }

Target:
protected List<ShowRoomCategory> getShowRoomCategories() { Random random = new Random(); int recommendedPage; if (recommendedShowRoomPageCount != null && recommendedShowRoomPageCount > 0) { recommendedPage = random.nextInt(recommendedShowRoomPageCount) + 1; } else { recommendedPage = 1; } return Arrays.asList( new ShowRoomCategory(() -> mapService.getRecommendedMapsWithPageCount(TOP_ELEMENT_COUNT, recommendedPage), SearchType.RECOMMENDED, "mapVault.recommended"), new ShowRoomCategory(() -> mapService.getHighestRatedMapsWithPageCount(TOP_ELEMENT_COUNT, 1), SearchType.HIGHEST_RATED, "mapVault.mostLikedMaps"), new ShowRoomCategory(() -> mapService.getNewestMapsWithPageCount(TOP_ELEMENT_COUNT, 1), SearchType.NEWEST, "mapVault.newestMaps"), new ShowRoomCategory(() -> mapService.getMostPlayedMapsWithPageCount(TOP_ELEMENT_COUNT, 1), SearchType.PLAYED, "mapVault.mostPlayed"), new ShowRoomCategory(() -> mapService.getOwnedMapsWithPageCount(TOP_ELEMENT_COUNT, 1), SearchType.OWN, "mapVault.owned")); }
Source:
public long nextRequestSequence() { return this.requestSequence.get() + 1; }

Target:
public long nextRequestSequence() { return this.requestSequence + 1; }
Source:
public KeyInfo getKeyInfo(final PublicKey publicKey) throws SAMLComponentBuilderException { final KeyInfoBean keyInfoBean = new KeyInfoBean(); KeyInfo keyInfo = null; keyInfoBean.setPublicKey(publicKey); try { keyInfo = SAML1ComponentBuilder.createKeyInfo(keyInfoBean); } catch (org.opensaml.security.SecurityException | org.apache.wss4j.common.ext.WSSecurityException e) { LOG.error(e.getLocalizedMessage(), e); throw new SAMLComponentBuilderException(e.getLocalizedMessage(), e); } return keyInfo; }

Target:
public KeyInfo getKeyInfo(final PublicKey publicKey) throws SAMLComponentBuilderException { final KeyInfoBean keyInfoBean = new KeyInfoBean(); KeyInfo keyInfo = null; keyInfoBean.setPublicKey(publicKey); try { keyInfo = SAML1ComponentBuilder.createKeyInfo(keyInfoBean); } catch (SecurityException | WSSecurityException e) { LOG.error(e.getLocalizedMessage(), e); throw new SAMLComponentBuilderException(e.getLocalizedMessage(), e); } return keyInfo; }
Source:
public void testPolymorphicReturnSubclass() throws Exception { FlyingSheep flyingSheep = dao.get(FlyingSheep.class, "Fluffy"); assertEquals("Fluffy", flyingSheep.getName()); assertEquals(5, flyingSheep.getNumWings()); }

Target:
public void testPolymorphicReturnSubclass() throws Exception { FlyingSheep flyingSheep = dao.get(FlyingSheep.class, "Fluffy"); assertThat(flyingSheep.getName()).isEqualTo("Fluffy"); assertThat(flyingSheep.getNumWings()).isEqualTo(5); }
Source:
public boolean isRoot() { return parentResource == null && !(rawSource instanceof GraphQLContainer); }

Target:
public boolean isRoot() { return !(rawSource instanceof GraphQLContainer); }
Source:
public void beginWindow(long windowId) { currentWindowId = windowId; if (currentWindowId <= windowManager.getLargestRecoveryWindow()) { try { replay(currentWindowId); return; } catch (SQLException e) { LOG.error("Exception in replayed windows", e); throw new RuntimeException(e); } } if (isPollerPartition) { updatePollQuery(); isPolled = false; } lowerBound = lastEmittedRecord; }

Target:
public void beginWindow(long windowId) { currentWindowId = windowId; if (currentWindowId <= windowManager.getLargestRecoveryWindow()) { try { replay(currentWindowId); return; } catch (SQLException e) { LOG.error("Exception in replayed windows", e); throw new RuntimeException(e); } } if (isPollerPartition) { updatePollQuery(); isPolled = false; } lowerBound = lastEmittedRow; }
Source:
public void onStop() { super.onStop(); mGoogleApiClient.stopAutoManage(getActivity()); if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } }

Target:
public void onStop() { super.onStop(); if (mGoogleApiClient != null) { mGoogleApiClient.stopAutoManage(getActivity()); if (mGoogleApiClient.isConnected()) { mGoogleApiClient.disconnect(); } } }
Source:
public void testGetAllInterfacesByLabelForCluster() { List<VdsNetworkInterface> interfaces = dao.getAllInterfacesByLabelForCluster(CLUSTER_ID, LABEL); assertNotNull(interfaces); assertEquals(1, interfaces.size()); }

Target:
public void testGetAllInterfacesByLabelForCluster() { List<VdsNetworkInterface> interfaces = dao.getAllInterfacesByLabelForCluster(CLUSTER_ID, LABEL); assertNotNull(interfaces); assertFalse(interfaces.isEmpty()); for (VdsNetworkInterface nic : interfaces) { assertTrue(nic.getLabels().contains(LABEL)); } }
Source:
FNatsTransport(Connection conn, String subject, String inbox, boolean isTTransport) { super(NATS_MAX_MESSAGE_SIZE, FRAME_BUFFER_SIZE, LOGGER); this.conn = conn; this.subject = subject; this.inbox = inbox; this.isTTransport = isTTransport; }

Target:
FNatsTransport(Connection conn, String subject, String inbox, boolean isTTransport) { super(NATS_MAX_MESSAGE_SIZE, FRAME_BUFFER_SIZE); this.conn = conn; this.subject = subject; this.inbox = inbox; this.isTTransport = isTTransport; }
Source:
Map<WAL, Boolean> getWalNeedsRoll() { Map<WAL, Boolean> walNeedsRoll = new HashMap<>(); for (Map.Entry<WAL, RollController> entry : this.walNeedsRoll.entrySet()) { walNeedsRoll.put(entry.getKey(), entry.getValue().isRequestRoll()); } return walNeedsRoll; }

Target:
Map<WAL, RollController> getWalNeedsRoll() { return this.wals; }
Source:
private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException { if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Error occurred when loading extension class (interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + " is not subtype of interface."); } if (clazz.isAnnotationPresent(Adaptive.class)) { cacheAdaptiveClass(clazz); } else if (isWrapperClass(clazz)) { cacheWrapperClass(clazz); } else { clazz.getConstructor(); if (StringUtils.isEmpty(name)) { name = findAnnotationName(clazz); if (name.length() == 0) { throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL); } } String[] names = NAME_SEPARATOR.split(name); cacheActivateClass(clazz, names[0]); cacheNames(clazz, names); saveInExtensionClasses(extensionClasses, clazz, names); } }

Target:
private void loadClass(Map<String, Class<?>> extensionClasses, java.net.URL resourceURL, Class<?> clazz, String name) throws NoSuchMethodException { if (!type.isAssignableFrom(clazz)) { throw new IllegalStateException("Error occurred when loading extension class (interface: " + type + ", class line: " + clazz.getName() + "), class " + clazz.getName() + " is not subtype of interface."); } if (clazz.isAnnotationPresent(Adaptive.class)) { cacheAdaptiveClass(clazz); } else if (isWrapperClass(clazz)) { cacheWrapperClass(clazz); } else { clazz.getConstructor(); if (StringUtils.isEmpty(name)) { name = findAnnotationName(clazz); if (name.length() == 0) { throw new IllegalStateException("No such extension name for the class " + clazz.getName() + " in the config " + resourceURL); } } String[] names = NAME_SEPARATOR.split(name); if (ArrayUtils.isNotEmpty(names)) { cacheActivateClass(clazz, names[0]); for (String n : names) { cacheName(clazz, n); saveInExtensionClass(extensionClasses, clazz, name); } } } }
Source:
public ValidationResult supportedFirewallTypeForClusterVersion() { return ValidationResult .failWith( EngineMessage.UNSUPPORTED_FIREWALL_TYPE_FOR_CLUSTER_VERSION, String.format("$clusterVersion %s", cluster.getCompatibilityVersion()), String.format("$firewallType %s", cluster.getFirewallType()) ) .when(cluster.getCompatibilityVersion().equals(Version.v3_6) && FirewallType.FIREWALLD.equals(cluster.getFirewallType())); }

Target:
public ValidationResult supportedFirewallTypeForClusterVersion() { return ValidationResult .failWith( EngineMessage.UNSUPPORTED_FIREWALL_TYPE_FOR_CLUSTER_VERSION, ReplacementUtils.createSetVariableString("$clusterVersion", cluster.getCompatibilityVersion()), ReplacementUtils.createSetVariableString("$firewallType", cluster.getFirewallType()) ) .when(cluster.getCompatibilityVersion().lessOrEquals(Version.v3_6) && FirewallType.FIREWALLD.equals(cluster.getFirewallType())); }
Source:
public PosDataCode (byte[] b) { if (b != null) { int copyLen= Math.min(b.length, 16); System.arraycopy(b, 0, this.b, 0, copyLen); } }

Target:
private PosDataCode (byte[] b) { if (b != null) { int copyLen= Math.min(b.length, 16); System.arraycopy(b, 0, this.b, 0, copyLen); } }
Source:
public SchemaCompatibilityResult mergedWith(SchemaCompatibilityResult toMerge) { List<Incompatibility> mergedIncompatibilities = new ArrayList<Incompatibility>(mIncompatibilities); mergedIncompatibilities.addAll(toMerge.getIncompatibilities()); SchemaCompatibilityType compatibilityType = mCompatibilityType == SchemaCompatibilityType.COMPATIBLE && toMerge.mCompatibilityType == SchemaCompatibilityType.COMPATIBLE ? SchemaCompatibilityType.COMPATIBLE : SchemaCompatibilityType.INCOMPATIBLE; return new SchemaCompatibilityResult(compatibilityType, mergedIncompatibilities); }

Target:
public SchemaCompatibilityResult mergedWith(SchemaCompatibilityResult toMerge) { List<Incompatibility> mergedIncompatibilities = new ArrayList<Incompatibility>(mIncompatibilities); mergedIncompatibilities.addAll(toMerge.getIncompatibilities()); SchemaCompatibilityType compatibilityType = mCompatibilityType == SchemaCompatibilityType.COMPATIBLE ? toMerge.mCompatibilityType : SchemaCompatibilityType.INCOMPATIBLE; return new SchemaCompatibilityResult(compatibilityType, mergedIncompatibilities); }
Source:
public String toString() { return rejectionReasons.size() < 2 ? Iterables.getFirst(rejectionReasons, "") : Joiner.on(", ").join(rejectionReasons); }

Target:
public String toString() { return Joiner.on(", ").join(rejectionReasons); }
Source:
private static boolean hasSafeType( Object value ) { if ( value instanceof Value ) { return true; } else if ( value instanceof String ) { return true; } else if ( value instanceof Long ) { return true; } else if ( value instanceof Integer ) { return true; } else if ( value instanceof Boolean ) { return true; } else if ( value instanceof Double ) { return true; } else if ( value instanceof Float ) { return true; } else if ( value instanceof Short ) { return true; } else if ( value instanceof Byte ) { return true; } else if ( value.getClass().isArray() && value.getClass().getComponentType().isPrimitive() ) { return true; } else { return false; } }

Target:
private static boolean hasSafeType( Object value ) { return value instanceof Value || value instanceof String || value instanceof Long || value instanceof Integer || value instanceof Boolean || value instanceof Double || value instanceof Float || value instanceof Short || value instanceof Byte || (value.getClass().isArray() && value.getClass().getComponentType().isPrimitive()); }
Source:
public String takeElementScreenshot(String baseName, WebElement element) { String result = null; WebDriver d = driver(); if (!(d instanceof TakesScreenshot)) { d = new Augmenter().augment(d); } if (d instanceof TakesScreenshot) { TakesScreenshot ts = (TakesScreenshot) d; File screenshot = ts.getScreenshotAs(OutputType.FILE); try { BufferedImage fullWindow = ImageIO.read(screenshot); Point location = element.getLocation(); int w = element.getSize().getWidth(); int h = element.getSize().getHeight(); BufferedImage elementScreenshot = fullWindow.getSubimage(location.getX(), location.getY(), w, h); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(elementScreenshot, "png", baos); result = writeScreenshot(baseName, baos.toByteArray()); } catch (IOException e) { throw new SlimFixtureException(true, "Unable to create element screenshot"); } } return result; }

Target:
public String takeElementScreenshot(String baseName, WebElement element) { String result = null; TakesScreenshot ts = screenshotCapableDriver(); if (ts != null) { File screenshot = ts.getScreenshotAs(OutputType.FILE); try { BufferedImage fullWindow = ImageIO.read(screenshot); Point location = element.getLocation(); int w = element.getSize().getWidth(); int h = element.getSize().getHeight(); BufferedImage elementScreenshot = fullWindow.getSubimage(location.getX(), location.getY(), w, h); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(elementScreenshot, "png", baos); result = writeScreenshot(baseName, baos.toByteArray()); } catch (IOException e) { throw new SlimFixtureException(true, "Unable to create element screenshot"); } } return result; }
Source:
public List<VmNumaNode> getVmNumaNodes(VM vm) { int onlineCpus = vm.getNumOfCpus(); int vcpus = FeatureSupported.supportedInConfig(ConfigValues.HotPlugCpuSupported, vm.getCompatibilityVersion(), vm.getClusterArch()) ? VmCpuCountHelper.calcMaxVCpu(vm, vm.getClusterCompatibilityVersion()) : onlineCpus; int offlineCpus = vcpus - onlineCpus; List<VmNumaNode> vmNumaNodes = vmNumaNodeDao.getAllVmNumaNodeByVmId(vm.getId()); if (!vmNumaNodes.isEmpty()) { int totalCpusPerNode = 0; for (VmNumaNode vmNode : vmNumaNodes) { totalCpusPerNode += vmNode.getCpuIds().size(); } if (onlineCpus != totalCpusPerNode) { offlineCpus = vcpus - totalCpusPerNode; } if (offlineCpus > 0) { Comparator<VmNumaNode> compareBySize = Comparator.comparingInt(o -> o.getCpuIds().size()); Collections.sort(vmNumaNodes, compareBySize); int numaCount = vmNumaNodes.size(); int start = totalCpusPerNode-1; for (VmNumaNode vmNode : vmNumaNodes) { int index = start = start+1; if (numaCount <= 0) { break; } while (index < vcpus) { vmNode.getCpuIds().add(index); index += numaCount; } } } return vmNumaNodes; } if (offlineCpus > 0) { VmNumaNode vmNode = new VmNumaNode(); vmNode.setIndex(0); vmNode.setMemTotal(vm.getMemSizeMb()); for (int i = 0; i < vcpus; i++) { vmNode.getCpuIds().add(i); } return Collections.singletonList(vmNode); } return Collections.emptyList(); }

Target:
public List<VmNumaNode> getVmNumaNodes(VM vm) { int onlineCpus = vm.getNumOfCpus(); int vcpus = FeatureSupported.supportedInConfig(ConfigValues.HotPlugCpuSupported, vm.getCompatibilityVersion(), vm.getClusterArch()) ? VmCpuCountHelper.calcMaxVCpu(vm, vm.getClusterCompatibilityVersion()) : onlineCpus; int offlineCpus = vcpus - onlineCpus; List<VmNumaNode> vmNumaNodes = vmNumaNodeDao.getAllVmNumaNodeByVmId(vm.getId()); if (!vmNumaNodes.isEmpty()) { int totalCpusInNodes = 0; for (VmNumaNode vmNode : vmNumaNodes) { totalCpusInNodes += vmNode.getCpuIds().size(); } if (onlineCpus != totalCpusInNodes) { offlineCpus = vcpus - totalCpusInNodes; } if (offlineCpus > 0) { Comparator<VmNumaNode> compareBySize = Comparator.comparingInt(o -> o.getCpuIds().size()); Collections.sort(vmNumaNodes, compareBySize); int numaCount = vmNumaNodes.size(); int start = totalCpusInNodes-1; for (VmNumaNode vmNode : vmNumaNodes) { int index = start = start+1; while (index < vcpus) { vmNode.getCpuIds().add(index); index += numaCount; } } } return vmNumaNodes; } if (offlineCpus > 0) { VmNumaNode vmNode = new VmNumaNode(); vmNode.setIndex(0); vmNode.setMemTotal(vm.getMemSizeMb()); for (int i = 0; i < vcpus; i++) { vmNode.getCpuIds().add(i); } return Collections.singletonList(vmNode); } return Collections.emptyList(); }
Source:
public void addRule(Rule rule) { if (rule.containsAttribute(Attribute.FUNCTION_KEY)) { functionRules.put(rule.functionKLabel(), rule); if (rule.isSortPredicate()) { sortPredicateRules.put((KLabelConstant) rule.sortPredicateArgument().kLabel(), rule); } } else if (rule.containsAttribute(Attribute.MACRO_KEY)) { macros.add(rule); } else if (rule.containsAttribute(Attribute.ANYWHERE_KEY)) { if (!(rule.leftHandSide() instanceof KItem)) { GlobalSettings.kem.registerCriticalWarning( "The Java backend only supports [anywhere] rule that rewrites KItem; but found:\n\t" + rule, null, rule); return; } anywhereRules.put(rule.anywhereKLabel(), rule); } else { rules.add(rule); } }

Target:
public void addRule(Rule rule) { if (rule.containsAttribute(Attribute.FUNCTION_KEY)) { functionRules.put(rule.definedKLabel(), rule); if (rule.isSortPredicate()) { sortPredicateRules.put((KLabelConstant) rule.sortPredicateArgument().kLabel(), rule); } } else if (rule.containsAttribute(Attribute.PATTERN_KEY)) { patternRules.put(rule.definedKLabel(), rule); } else if (rule.containsAttribute(Attribute.MACRO_KEY)) { macros.add(rule); } else if (rule.containsAttribute(Attribute.ANYWHERE_KEY)) { if (!(rule.leftHandSide() instanceof KItem)) { GlobalSettings.kem.registerCriticalWarning( "The Java backend only supports [anywhere] rule that rewrites KItem; but found:\n\t" + rule, rule); return; } anywhereRules.put(rule.anywhereKLabel(), rule); } else { rules.add(rule); } }
Source:
public IndexDiffCacheEntry(Repository repository) { this.repository = repository; repository.getListenerList().addIndexChangedListener( new IndexChangedListener() { public void onIndexChanged(IndexChangedEvent event) { refreshIndexDelta(); } }); repository.getListenerList().addRefsChangedListener( new RefsChangedListener() { public void onRefsChanged(RefsChangedEvent event) { scheduleReloadJob("RefsChanged"); } }); scheduleReloadJob("IndexDiffCacheEntry construction"); createResourceChangeListener(); if (!repository.isBare()) { try { lastIndex = repository.readDirCache(); } catch(IOException ex) { Activator.error(String.format(CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository), ex); } } }

Target:
public IndexDiffCacheEntry(Repository repository) { this.repository = repository; repository.getListenerList().addIndexChangedListener( new IndexChangedListener() { public void onIndexChanged(IndexChangedEvent event) { refreshIndexDelta(); } }); repository.getListenerList().addRefsChangedListener( new RefsChangedListener() { public void onRefsChanged(RefsChangedEvent event) { scheduleReloadJob("RefsChanged"); } }); scheduleReloadJob("IndexDiffCacheEntry construction"); createResourceChangeListener(); if (!repository.isBare()) { try { lastIndex = repository.readDirCache(); } catch (IOException ex) { Activator.error(MessageFormat.format(CoreText.IndexDiffCacheEntry_errorCalculatingIndexDelta, repository), ex); } } }
Source:
public void verifyTrackingForSingletonLatencyRecords() throws Exception { final int numTasks = 100; AbfsPerfTracker abfsPerfTracker = new AbfsPerfTracker(accountName, filesystemName, true); String latencyDetails = abfsPerfTracker.getClientLatency(); assertThat(latencyDetails).describedAs("AbfsPerfTracker should be empty").isNull(); List<Callable<Integer>> tasks = new ArrayList<>(); AbfsHttpOperation httpOperation = new AbfsHttpOperation(url, "GET", new ArrayList<>()); for (int i=0; i < numTasks; i++) { tasks.add(() -> { try (AbfsPerfInfo tracker = new AbfsPerfInfo(abfsPerfTracker, "oneOperationCaller", "oneOperationCallee")) { tracker.registerResult(httpOperation).registerSuccess(true); return 0; } }); } for (Future<Integer> fr: executorService.invokeAll(tasks)) { fr.get(); } for (int i=0; i < numTasks; i++) { latencyDetails = abfsPerfTracker.getClientLatency(); assertThat(latencyDetails).describedAs("AbfsPerfTracker should return non-null record").isNotNull(); assertThat(Pattern.matches( "h=[^ ]* t=[^ ]* a=bogusFilesystemName c=bogusAccountName cr=oneOperationCaller ce=oneOperationCallee r=Succeeded l=[0-9]+" + " s=0 e= ci=[^ ]* ri=[^ ]* ct=[0-9]+ st=[0-9]+ rt=[0-9]+ bs=0 br=0 m=GET u=http%3A%2F%2Fwww.microsoft.com%2FbogusFile", latencyDetails)) .describedAs("Latency record should be in the correct format").isTrue(); } latencyDetails = abfsPerfTracker.getClientLatency(); assertThat(latencyDetails).describedAs("AbfsPerfTracker should return no record").isNull(); }

Target:
public void verifyTrackingForSingletonLatencyRecords() throws Exception { final int numTasks = 100; AbfsPerfTracker abfsPerfTracker = new AbfsPerfTracker(accountName, filesystemName, true); String latencyDetails = abfsPerfTracker.getClientLatency(); assertThat(latencyDetails).describedAs("AbfsPerfTracker should be empty").isNull(); List<Callable<Integer>> tasks = new ArrayList<>(); AbfsHttpOperation httpOperation = new AbfsHttpOperation(url, "GET", new ArrayList<>()); for (int i = 0; i < numTasks; i++) { tasks.add(() -> { try (AbfsPerfInfo tracker = new AbfsPerfInfo(abfsPerfTracker, "oneOperationCaller", "oneOperationCallee")) { tracker.registerResult(httpOperation).registerSuccess(true); return 0; } }); } for (Future<Integer> fr: executorService.invokeAll(tasks)) { fr.get(); } for (int i = 0; i < numTasks; i++) { latencyDetails = abfsPerfTracker.getClientLatency(); assertThat(latencyDetails).describedAs("AbfsPerfTracker should return non-null record").isNotNull(); assertThat(latencyDetails).describedAs("Latency record should be in the correct format") .containsPattern("h=[^ ]* t=[^ ]* a=bogusFilesystemName c=bogusAccountName cr=oneOperationCaller" + " ce=oneOperationCallee r=Succeeded l=[0-9]+ s=0 e= ci=[^ ]* ri=[^ ]* bs=0 br=0 m=GET" + " u=http%3A%2F%2Fwww.microsoft.com%2FbogusFile"); } latencyDetails = abfsPerfTracker.getClientLatency(); assertThat(latencyDetails).describedAs("AbfsPerfTracker should return no record").isNull(); }
Source:
public void sourcePrepare(FlowProcess<JobConf> flowProcess, SourceCall<Object[], RecordReader> sourceCall) throws IOException { super.sourcePrepare(flowProcess, sourceCall); Object[] context = new Object[4]; context[0] = sourceCall.getInput().createKey(); context[1] = sourceCall.getInput().createValue(); Settings settings = loadSettings(flowProcess.getConfigCopy(), true); context[2] = CascadingUtils.alias(settings); context[3] = settings.getOutputAsJson(); sourceCall.setContext(context); }

Target:
public void sourcePrepare(FlowProcess<JobConf> flowProcess, SourceCall<Object[], RecordReader> sourceCall) throws IOException { super.sourcePrepare(flowProcess, sourceCall); Object[] context = new Object[SRC_CTX_SIZE]; context[SRC_CTX_KEY] = sourceCall.getInput().createKey(); context[SRC_CTX_VALUE] = sourceCall.getInput().createValue(); Settings settings = loadSettings(flowProcess.getConfigCopy(), true); context[SRC_CTX_ALIASES] = CascadingUtils.alias(settings); context[SRC_CTX_OUTPUT_JSON] = settings.getOutputAsJson(); sourceCall.setContext(context); }
Source:
public List<ITmfCallsite> getCallsites(String traceId, String device, long time) { ITmfStateSystem ss = getStateSystem(); if (ss == null) { return Collections.emptyList(); } int quark = ss.optQuarkAbsolute(CallsiteStateProvider.DEVICES, traceId, device); int invalidAttribute = ITmfStateSystem.INVALID_ATTRIBUTE; if (quark == invalidAttribute) { return Collections.emptyList(); } int stringPool = ss.optQuarkAbsolute(CallsiteStateProvider.STRING_POOL); int fileQuark = ss.optQuarkRelative(quark, CallsiteStateProvider.FILES); int lineQuark = ss.optQuarkRelative(quark, CallsiteStateProvider.LINES); if (fileQuark == ITmfStateSystem.INVALID_ATTRIBUTE || lineQuark == ITmfStateSystem.INVALID_ATTRIBUTE || stringPool == ITmfStateSystem.INVALID_ATTRIBUTE) { return Collections.emptyList(); } List<Integer> files = ss.getSubAttributes(fileQuark, false); List<Integer> lines = ss.getSubAttributes(lineQuark, false); int size = files.size(); if (size != lines.size()) { return Collections.emptyList(); } List<ITmfCallsite> retVal = new ArrayList<>(); try { List<ITmfStateInterval> values = ss.queryFullState(time); Object stringIntern = values.get(fileQuark).getValue(); int lineNo = values.get(lineQuark).getValueInt(); if (lineNo != CallsiteStateProvider.UNKNOWN_LINE_NO && stringIntern instanceof Integer) { String fileName = fSSInterner.resolve(ss, (Integer) stringIntern + ss.getStartTime(), stringPool); if (fileName != null) { retVal.add(new TmfCallsite(fileName, (long) lineNo)); } } } catch (StateSystemDisposedException e) { } return retVal; }

Target:
public List<ITmfCallsite> getCallsites(String traceId, String device, long time) { ITmfCallsiteIterator iterator = iterator(traceId, device, time); if (iterator.hasNext()) { return Collections.singletonList(iterator.next().getCallsite()); } return Collections.emptyList(); }
Source:
public void setMBeanAttribute(ObjectName objectName, String type, String name, String value) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException, MBeanException, InvalidAttributeValueException, AttributeNotFoundException { Object attributeValue; switch (type.toLowerCase()) { case "int": attributeValue = Integer.valueOf(value); break; case "string": attributeValue = value; break; default: return; } this.jmxClient.getConnector().getMBeanServerConnection().setAttribute(objectName, new Attribute(name, attributeValue)); }

Target:
public void setMBeanAttribute(ObjectName objectName, String type, String name, String value) throws InstanceNotFoundException, IntrospectionException, ReflectionException, IOException, MBeanException, InvalidAttributeValueException, AttributeNotFoundException, IllegalArgumentException { Object attributeValue = MBeanAttributeType.valueOf(type.toUpperCase()).convert(value); this.jmxClient.getConnector().getMBeanServerConnection().setAttribute(objectName, new Attribute(name, attributeValue)); }
Source:
public void onMessage(ClientMessage message) { String body = ""; try { message.acknowledge(); body = message.getBodyBuffer().readString(); log.debug("Got event: {}", body); JobMessage jobMessage = mapper.readValue(body, JobMessage.class); log.debug("ActiveMQ message received for async job: {}.", message.getMessageID(), jobMessage); AsyncJobStatus jobStatus = manager.executeJob(jobMessage); } catch (JobException e) { } catch (Exception e) { String messageId = (message == null) ? "" : Long.toString(message.getMessageID()); String reason = (e.getCause() == null) ? e.getMessage() : e.getCause().getMessage(); log.warn("Job message processing failed! {}: {}", messageId, reason); log.debug("Unable to process message. Rolling back client session.\n{}", body, e); try { session.rollback(); } catch (ActiveMQException amqe) { log.error("Unable to roll back client session.", amqe); } } finally { try { session.commit(); } catch (ActiveMQException amqe) { log.error("Unable to commit client session", amqe); } } }

Target:
public void onMessage(ClientMessage message) { String body = ""; try { message.acknowledge(); body = message.getBodyBuffer().readString(); log.debug("Got event: {}", body); JobMessage jobMessage = mapper.readValue(body, JobMessage.class); log.debug("ActiveMQ message received for async job: {}.", message.getMessageID(), jobMessage); AsyncJobStatus jobStatus = manager.executeJob(jobMessage); this.commitSession(); } catch (JobExecutionException e) { this.commitSession(); } catch (JobStateManagementException e) { JobState intendedState = e.getIntendedState(); if (intendedState != null && !intendedState.isTerminal()) { log.error("Job processing failed; rolling back job message to retry later: {}", body); this.rollbackSession(); } else { log.error("Job processing failed terminally; committing job message as acknowledged: {}", body); this.commitSession(); } } catch (JobMessageDispatchException e) { log.error("Failed to dispatch job message during job execution; rolling back job message " + "to retry later: {}", body); this.rollbackSession(); } catch (JobException e) { if (e.isTerminal()) { log.error("Job processing failed terminally; committing job message as acknowledged: {}", body); this.commitSession(); } else { log.error("Job processing failed; rolling back job message to retry later: {}", body); this.rollbackSession(); } } catch (Exception e) { String messageId = (message == null) ? "" : Long.toString(message.getMessageID()); String reason = (e.getCause() == null) ? e.getMessage() : e.getCause().getMessage(); log.warn("Job message processing failed! {}: {}", messageId, reason); log.debug("Unable to process message. Rolling back client session.\n{}", body, e); this.rollbackSession(); } }
Source:
private org.openmrs.module.emrapi.conditionslist.contract.Concept convertCoreConceptToEmrapiConcept(Concept coreConcept) { if (coreConcept != null) { ConceptName fullySpecifiedName = coreConcept.getFullySpecifiedName(Context.getLocale()); if (fullySpecifiedName == null) { fullySpecifiedName = coreConcept.getFullySpecifiedName(getDefaultLocale()); } org.openmrs.module.emrapi.conditionslist.contract.Concept concept = new org.openmrs.module.emrapi.conditionslist.contract.Concept(coreConcept.getUuid(), fullySpecifiedName.getName()); ConceptName shortName = coreConcept.getShortNameInLocale(Context.getLocale()); if (shortName != null) { concept.setShortName(shortName.getName()); } return concept; } return null; }

Target:
private org.openmrs.module.emrapi.conditionslist.contract.Concept convertCoreConceptToEmrapiConcept(Concept coreConcept) { ConceptName fullySpecifiedName = coreConcept.getFullySpecifiedName(Context.getLocale()); if (fullySpecifiedName == null) { fullySpecifiedName = coreConcept.getFullySpecifiedName(getDefaultLocale()); } org.openmrs.module.emrapi.conditionslist.contract.Concept concept = new org.openmrs.module.emrapi.conditionslist.contract.Concept(coreConcept.getUuid(), fullySpecifiedName.getName()); ConceptName shortName = coreConcept.getShortNameInLocale(Context.getLocale()); if (shortName != null) { concept.setShortName(shortName.getName()); } return concept; }
Source:
private static void triggerBlockingRegisterNativeAllocation() throws Exception { final long startTime = System.currentTimeMillis(); final long finalizerTimeoutMs = VMRuntime.getRuntime().getFinalizerTimeoutMs(); final long quittingTime = startTime + finalizerTimeoutMs - 2 * MAX_EXPECTED_GC_DURATION_MS; long maxMem = Runtime.getRuntime().maxMemory(); int size = (int)(maxMem / 5); int allocationCount = 10; long total = 0; for (int i = 0; i < allocationCount && System.currentTimeMillis() < quittingTime; ++i) { runtime.registerNativeAllocation(size); total += size; } while (total > 0) { runtime.registerNativeFree(size); total -= size; } }

Target:
private static void triggerBlockingRegisterNativeAllocation() throws Exception { final long startTime = System.currentTimeMillis(); final long finalizerTimeoutMs = VMRuntime.getRuntime().getFinalizerTimeoutMs(); final long quittingTime = startTime + finalizerTimeoutMs - MAX_EXPECTED_GC_DURATION_MS; long maxMem = Runtime.getRuntime().maxMemory(); int size = (int)(maxMem / 5); int allocationCount = 10; long total = 0; for (int i = 0; i < allocationCount && System.currentTimeMillis() < quittingTime; ++i) { runtime.registerNativeAllocation(size); total += size; } while (total > 0) { runtime.registerNativeFree(size); total -= size; } }
Source:
private int getAvailableSize(Object inputStream, int expectedReadSize) throws IOException, InternalException { RandomAccessFile file = null; BufferedInputStream stream = null; if (inputStream instanceof RandomAccessFile) { file = (RandomAccessFile) inputStream; } else if (inputStream instanceof BufferedInputStream) { stream = (BufferedInputStream) inputStream; } else { throw new InternalException("Unknown input stream. This should not happen. Please report"); } long pos = 0; if (file != null) { pos = file.getFilePointer(); } else { stream.mark(expectedReadSize); } byte[] buf = new byte[16384]; int bytesToRead = buf.length; int bytesRead = 0; int totalBytesRead = 0; while (totalBytesRead < expectedReadSize) { if ((expectedReadSize - totalBytesRead) < bytesToRead) { bytesToRead = expectedReadSize - totalBytesRead; } if (file != null) { bytesRead = file.read(buf, 0, bytesToRead); } else { bytesRead = stream.read(buf, 0, bytesToRead); } if (bytesRead < 0) { break; } totalBytesRead += bytesRead; } if (file != null) { file.seek(pos); } else { stream.reset(); } return totalBytesRead; }

Target:
private int getAvailableSize(Object inputStream, int expectedReadSize) throws IOException, InternalException { RandomAccessFile file = null; BufferedInputStream stream = null; if (inputStream instanceof RandomAccessFile) { file = (RandomAccessFile) inputStream; } else if (inputStream instanceof BufferedInputStream) { stream = (BufferedInputStream) inputStream; } else { throw new InternalException("Unknown input stream. This should not happen. " + "Please report to <LINK_0>"); } long pos = 0; if (file != null) { pos = file.getFilePointer(); } else { stream.mark(expectedReadSize); } byte[] buf = new byte[16384]; int bytesToRead = buf.length; int bytesRead = 0; int totalBytesRead = 0; while (totalBytesRead < expectedReadSize) { if ((expectedReadSize - totalBytesRead) < bytesToRead) { bytesToRead = expectedReadSize - totalBytesRead; } if (file != null) { bytesRead = file.read(buf, 0, bytesToRead); } else { bytesRead = stream.read(buf, 0, bytesToRead); } if (bytesRead < 0) { break; } totalBytesRead += bytesRead; } if (file != null) { file.seek(pos); } else { stream.reset(); } return totalBytesRead; }
Source:
public void start() { regionNormalizerTracker.start(); if (worker != null) { pool.submit(worker); } }

Target:
public void start() { synchronized (startStopLock) { if (started) { return; } regionNormalizerTracker.start(); if (worker != null) { pool.submit(worker); } started = true; } }
Source:
public ModelAndView handleList( @RequestParam(value = REQUEST_PARAMETER_QUERY, required = false) String query, @RequestParam(value = REQUEST_PARAMETER_LIMIT, required = false) Integer limit, @RequestParam(value = REQUEST_PARAMETER_OFFSET, required = false) Long offset, @RequestParam(value = REQUEST_PARAMETER_ORDER_BY, required = false) String orderBy, @RequestParam(value = REQUEST_PARAMETER_ASCENDING, required = false) Boolean ascending) { ModelAndView modelAndView = new ModelAndView("user/list"); final String attributes = "userName, name.givenName, name.familyName"; if (limit == null) { limit = DEFAULT_LIMIT; } if (orderBy == null) { orderBy = DEFAULT_SORT_BY; ascending = DEFAULT_SORT_DIRECTION; } SCIMSearchResult<User> userList = userService.searchUser(query, limit, offset, orderBy, ascending, attributes); PagingLinks pagingLinks = generatePagingLinks(userList, query, orderBy, ascending); modelAndView.addObject(MODEL_USER_LIST, userList); modelAndView.addObject(MODEL_SESSION_DATA, session); modelAndView.addObject(MODEL_PAGING_LINKS, pagingLinks); session.setQuery(query); session.setLimit(limit); session.setOffset(offset); session.setOrderBy(orderBy); session.setAscending(ascending); return modelAndView; }

Target:
public ModelAndView handleList( @RequestParam(value = REQUEST_PARAMETER_QUERY, required = false) String query, @RequestParam(value = REQUEST_PARAMETER_LIMIT, required = false) Integer limit, @RequestParam(value = REQUEST_PARAMETER_OFFSET, required = false) Long offset, @RequestParam(value = REQUEST_PARAMETER_ORDER_BY, required = false) String orderBy, @RequestParam(value = REQUEST_PARAMETER_ASCENDING, required = false) Boolean ascending) { ModelAndView modelAndView = new ModelAndView("user/list"); final String attributes = "userName, name.givenName, name.familyName"; limit = limit == null ? DEFAULT_LIMIT : limit; orderBy = orderBy == null ? DEFAULT_SORT_BY : orderBy; ascending = ascending == null ? DEFAULT_SORT_DIRECTION : ascending; SCIMSearchResult<User> userList = userService.searchUser(query, limit, offset, orderBy, ascending, attributes); PagingLinks pagingLinks = generatePagingLinks(userList, query, orderBy, ascending); modelAndView.addObject(MODEL_USER_LIST, userList); modelAndView.addObject(MODEL_SESSION_DATA, session); modelAndView.addObject(MODEL_PAGING_LINKS, pagingLinks); session.setQuery(query); session.setLimit(limit); session.setOffset(offset); session.setOrderBy(orderBy); session.setAscending(ascending); return modelAndView; }
Source:
private void assertInvalid(LockToken token) { LeasedLockToken leasedLockToken = (LeasedLockToken) token; assertFalse(leasedLockToken.isValid(getIdentifiedTime())); }

Target:
private void assertInvalid(LockToken token) { LeasedLockToken leasedLockToken = (LeasedLockToken) token; assertThat(leasedLockToken.isValid(getIdentifiedTime())).isFalse(); }
Source:
protected void channelRead0( ChannelHandlerContext ctx, T request ) throws Exception { log.debug( "Handling request %s", request ); StoreCopyFinishedResponse.Status responseStatus = StoreCopyFinishedResponse.Status.E_UNKNOWN; try { NeoStoreDataSource neoStoreDataSource = dataSource.get(); if ( !hasSameStoreId( request.expectedStoreId(), neoStoreDataSource ) ) { responseStatus = StoreCopyFinishedResponse.Status.E_STORE_ID_MISMATCH; } else if ( !isTransactionWithinReach( request.requiredTransactionId() ) ) { responseStatus = StoreCopyFinishedResponse.Status.E_TOO_FAR_BEHIND; asyncCheckpoint(); } else { File storeDir = neoStoreDataSource.getStoreDir(); try ( ResourceIterator<StoreFileMetadata> resourceIterator = files( request, neoStoreDataSource ) ) { while ( resourceIterator.hasNext() ) { StoreFileMetadata storeFileMetadata = resourceIterator.next(); storeFileStreamingProtocol.stream( ctx, new StoreResource( storeFileMetadata.file(), relativePath( storeDir, storeFileMetadata.file() ), storeFileMetadata.recordSize(), pageCache, fs ) ); } } responseStatus = StoreCopyFinishedResponse.Status.SUCCESS; } } finally { storeFileStreamingProtocol.end( ctx, responseStatus ); protocol.expect( CatchupServerProtocol.State.MESSAGE_TYPE ); } }

Target:
protected void channelRead0( ChannelHandlerContext ctx, T request ) throws Exception { log.debug( "Handling request %s", request ); StoreCopyFinishedResponse.Status responseStatus = StoreCopyFinishedResponse.Status.E_UNKNOWN; try { NeoStoreDataSource neoStoreDataSource = dataSource.get(); if ( !hasSameStoreId( request.expectedStoreId(), neoStoreDataSource ) ) { responseStatus = StoreCopyFinishedResponse.Status.E_STORE_ID_MISMATCH; } else if ( !isTransactionWithinReach( request.requiredTransactionId() ) ) { responseStatus = StoreCopyFinishedResponse.Status.E_TOO_FAR_BEHIND; checkPointerService.tryAsyncCheckpoint( e -> log.error( "Failed to do a checkpoint that was invoked after a too far behind error on store copy request", e ) ); } else { File storeDir = neoStoreDataSource.getStoreDir(); try ( ResourceIterator<StoreFileMetadata> resourceIterator = files( request, neoStoreDataSource ) ) { while ( resourceIterator.hasNext() ) { StoreFileMetadata storeFileMetadata = resourceIterator.next(); storeFileStreamingProtocol.stream( ctx, new StoreResource( storeFileMetadata.file(), relativePath( storeDir, storeFileMetadata.file() ), storeFileMetadata.recordSize(), pageCache, fs ) ); } } responseStatus = StoreCopyFinishedResponse.Status.SUCCESS; } } finally { storeFileStreamingProtocol.end( ctx, responseStatus ); protocol.expect( CatchupServerProtocol.State.MESSAGE_TYPE ); } }
Source:
public String toString() { return String.format("[name=%s, container=%s, uri=%s, bytes=%s, contentType=%s, lastModified=%s, hash=%s]", name, container, uri, bytes, contentType, lastModified, Arrays.toString(hash)); }

Target:
public String toString() { return String.format("[name=%s, container=%s, uri=%s, bytes=%s, contentType=%s, lastModified=%s, hash=%s, objectManifest=%s]", name, container, uri, bytes, contentType, lastModified, Arrays.toString(hash), objectManifest); }
Source:
private boolean evict() { evictionObserver.begin(); Set<Map.Entry<K, ValueHolder<V>>> values = map.getRandomValues(new Random(), 8, evictionVeto); if (values.isEmpty()) { return false; } else { Map.Entry<K, ValueHolder<V>> evict = Collections.max(values, evictionPrioritizer); if (map.remove(evict.getKey(), evict.getValue())) { evictionObserver.end(EvictionOutcome.SUCCESS); return true; } else { return false; } } }

Target:
private boolean evict() { Set<Map.Entry<K, ValueHolder<V>>> values = map.getRandomValues(new Random(), 8, evictionVeto); if (values.isEmpty()) { return false; } else { Map.Entry<K, ValueHolder<V>> evict = Collections.max(values, evictionPrioritizer); if (map.remove(evict.getKey(), evict.getValue())) { return true; } else { return false; } } }
Source:
public void helixInitiatedIdealStateChangeTest() throws Exception { assumeTrue(!useComposite && !overrideEnabled); verifyInitialClusterChanges((HelixClusterManager) clusterManager, helixCluster, dcs); String resourceName = "newResource"; String partitionName = String.valueOf(helixCluster.getAllPartitions().size()); IdealState idealState = new IdealState(resourceName); idealState.setPreferenceList(partitionName, new ArrayList<>()); helixCluster.addNewResource(resourceName, idealState, localDc); verifyInitialClusterChanges((HelixClusterManager) clusterManager, helixCluster, new String[]{localDc}); Map<String, ConcurrentHashMap<String, String>> partitionToResource = ((HelixClusterManager) clusterManager).getPartitionToResourceMap(); assertEquals("localDc should have one more partition", partitionToResource.get(localDc).size(), partitionToResource.get(remoteDc).size() + 1); assertTrue(partitionToResource.get(localDc).containsKey(partitionName) && !partitionToResource.get(remoteDc) .containsKey(partitionName)); }

Target:
public void helixInitiatedIdealStateChangeTest() throws Exception { assumeTrue(!useComposite && !overrideEnabled); HelixClusterManager helixClusterManager = (HelixClusterManager) clusterManager; verifyInitialClusterChanges(helixClusterManager, helixCluster, dcs); String resourceName = "newResource"; String partitionName = String.valueOf(helixCluster.getAllPartitions().size()); IdealState idealState = new IdealState(resourceName); idealState.setPreferenceList(partitionName, new ArrayList<>()); helixCluster.addNewResource(resourceName, idealState, localDc); verifyInitialClusterChanges(helixClusterManager, helixCluster, new String[]{localDc}); Map<String, ConcurrentHashMap<String, String>> partitionToResource = (helixClusterManager).getPartitionToResourceMap(); assertEquals("localDc should have one more partition", partitionToResource.get(localDc).size(), partitionToResource.get(remoteDc).size() + 1); assertTrue(partitionToResource.get(localDc).containsKey(partitionName) && !partitionToResource.get(remoteDc) .containsKey(partitionName)); }
Source:
private void clusterRestart(boolean withAnotherClient, boolean allowOverwrite) throws Exception { try { startGrid(0); clientMode = true; Ignite client = startGrid(1); if (withAnotherClient) { startGrid(2); stopGrid(2); } clientMode = false; try (IgniteDataStreamer<String, String> streamer = client.dataStreamer("test")) { streamer.allowOverwrite(allowOverwrite); streamer.addData("k1", "v1"); } stopGrid(0); U.sleep(2_000); startGrid(0); U.sleep(1_000); for (int i = 0; i < 3; i++) { try (IgniteDataStreamer<String, String> streamer = client.dataStreamer("test")) { streamer.allowOverwrite(allowOverwrite); streamer.addData("k2", "v2"); return; } catch (CacheException ce) { assert ce.getCause() instanceof IgniteClientDisconnectedException; ((IgniteClientDisconnectedException)ce.getCause()).reconnectFuture().get(); } catch (IgniteClientDisconnectedException icde) { icde.reconnectFuture().get(); } } assert false : "Failed to wayt for reconnect!"; } finally { stopAllGrids(); } }

Target:
private void clusterRestart(boolean withAnotherClient, boolean allowOverwrite) throws Exception { CountDownLatch disconnect = new CountDownLatch(1); CountDownLatch reconnect = new CountDownLatch(1); try { startGrid(0); clientMode = true; Ignite client = startGrid(1); if (withAnotherClient) { startGrid(2); stopGrid(2); } clientMode = false; try (IgniteDataStreamer<String, String> streamer = client.dataStreamer("test")) { streamer.allowOverwrite(allowOverwrite); streamer.addData("k1", "v1"); } client.events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event event) { reconnect.countDown(); return false; } }, EventType.EVT_CLIENT_NODE_RECONNECTED); client.events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event event) { disconnect.countDown(); return false; } }, EventType.EVT_CLIENT_NODE_DISCONNECTED); stopGrid(0); disconnect.await(); startGrid(0); reconnect.await(); try (IgniteDataStreamer<String, String> streamer = client.dataStreamer("test")) { streamer.allowOverwrite(allowOverwrite); streamer.addData("k2", "v2"); return; } } finally { stopAllGrids(); } }