auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void includeStatsTrueShouldIncludeStatistics() { boolean includeStats = true; boolean calculateStats = true; boolean includeSample = false; Variant variant = buildVariant("12", 3, 4, "A", "T", fileId, studyId); variantToMongoDbObjectConverter = new VariantToMongoDbObjectConverter(includeStats, samplesPosition, calculateStats, includeSample, includeSrc); conversionService.addConverter(variantToMongoDbObjectConverter); DBObject dbObject = conversionService.convert(variant, DBObject.class); assertNotNull(dbObject); BasicDBObject addToSet = (BasicDBObject) dbObject.get("$addToSet"); BasicDBObject st = (BasicDBObject) addToSet.get("st"); assertNotNull(st); }

Target:
public void includeStatsTrueShouldIncludeStatistics() { Variant variant = buildVariant("12", 3, 4, "A", "T", fileId, studyId); variantToMongoDbObjectConverter = new VariantToMongoDbObjectConverter(true, samplesPosition, true, false, includeSrc); conversionService.addConverter(variantToMongoDbObjectConverter); DBObject dbObject = conversionService.convert(variant, DBObject.class); assertNotNull(dbObject); BasicDBObject addToSet = (BasicDBObject) dbObject.get("$addToSet"); BasicDBObject st = (BasicDBObject) addToSet.get("st"); assertNotNull(st); }
Source:
public static Properties processProperties(final String propertyFileName) throws IOException { final File propertyFile = new File(propertyFileName); if (!propertyFile.exists()) { throw new FileNotFoundException(propertyFile.toString()); } final Properties properties = new Properties(); final InputStream is = new FileInputStream(propertyFile); try { properties.load(is); } finally { if (is != null) { is.close(); } } return properties; }

Target:
private static Properties processProperties(final String propertyFileName) throws IOException { final File propertyFile = new File(propertyFileName); if (!propertyFile.exists()) { throw new FileNotFoundException(propertyFile.toString()); } final Properties properties = new Properties(); try (InputStream is = new FileInputStream(propertyFile)) { properties.load(is); } return properties; }
Source:
private void updateModel(final AttributeChange diff, final EAttribute eAttribute, final IEqualityHelper equalityHelper, final EObject eObject, final boolean isLeft) { final String oldValue = getStringValue(eObject, eAttribute); GetContentRunnable runnable = new GetContentRunnable(isLeft); Display.getDefault().syncExec(runnable); String newValue = (String)runnable.getResult(); final boolean oldAndNewEquals = equalityHelper.matchingAttributeValues(newValue, oldValue); if (eObject != null && !oldAndNewEquals && getCompareConfiguration().isLeftEditable()) { getCompareConfiguration().getEditingDomain().getCommandStack().execute( new UpdateModelAndRejectDiffCommand(getCompareConfiguration().getEditingDomain() .getChangeRecorder(), eObject, eAttribute, newValue, diff, isLeft)); } }

Target:
private void updateModel(final AttributeChange diff, final EAttribute eAttribute, final IEqualityHelper equalityHelper, final EObject eObject, final boolean isLeft) { final String oldValue = getStringValue(eObject, eAttribute); GetContentRunnable runnable = new GetContentRunnable(isLeft); Display.getDefault().syncExec(runnable); String newValue = (String)runnable.getResult(); final boolean oldAndNewEquals = equalityHelper.matchingAttributeValues(newValue, oldValue); if (eObject != null && !oldAndNewEquals && getCompareConfiguration().isEditable(isLeft)) { getCompareConfiguration().getEditingDomain().getCommandStack().execute( new UpdateModelAndRejectDiffCommand(getCompareConfiguration().getEditingDomain() .getChangeRecorder(), eObject, eAttribute, newValue, diff, isLeft)); } }
Source:
public <S extends NamedSnapshot> S getSingle(Class<S> type, String snapshotName, VersionCorrection versionCorrection) { return new TypedSnapshotSearcher<>(getMaster(), type, snapshotName, versionCorrection).search(); }

Target:
public <S extends NamedSnapshot> S getSingle(Class<S> type, String snapshotName, VersionCorrection versionCorrection) { TypedSnapshotSearcher<S> searcher = new TypedSnapshotSearcher<>(getMaster(), type, snapshotName, versionCorrection); return searcher.search(); }
Source:
public List<String> getUndeletedList() { return undeletedList; }

Target:
public List<File> getUndeletedList() { return undeletedList; }
Source:
public ExecutionResult execute(Item item) { if (item != null && item instanceof MDMServerDefItem) { MDMServerDef serverDef = ((MDMServerDefItem) item).getServerDef(); String algorithm = serverDef.getAlgorithm(); if (algorithm != null) { String decryptedPassword = null; if (algorithm.equals(PasswordUtil.ALGORITHM_COMMON)) { try { decryptedPassword = PasswordEncryptUtil.decryptPassword(serverDef.getPasswd()); } catch (Exception e) { return ExecutionResult.FAILURE; } } if (algorithm.equals(PasswordUtil.ALGORITHM_COMMON_V2)) { try { decryptedPassword = CryptoMigrationUtil.decrypt(serverDef.getPasswd()); } catch (Exception e) { return ExecutionResult.FAILURE; } } if (decryptedPassword != null) { serverDef.setPasswd(PasswordUtil.encryptPassword(decryptedPassword)); serverDef.setAlgorithm(PasswordUtil.ALGORITHM_COMMON_V3); try { factory.save(item, true); return ExecutionResult.SUCCESS_NO_ALERT; } catch (Exception e) { ExceptionHandler.process(e); return ExecutionResult.FAILURE; } } } } return ExecutionResult.NOTHING_TO_DO; }

Target:
public ExecutionResult execute(Item item) { if (item != null && item instanceof MDMServerDefItem) { MDMServerDef serverDef = ((MDMServerDefItem) item).getServerDef(); String algorithm = serverDef.getAlgorithm(); if (algorithm != null) { String decryptedPassword = null; if (algorithm.equals(PasswordUtil.ALGORITHM_COMMON)) { try { decryptedPassword = PasswordEncryptUtil.decryptPassword(serverDef.getPasswd()); } catch (Exception e) { return ExecutionResult.FAILURE; } } else if (algorithm.equals(PasswordUtil.ALGORITHM_COMMON_V2)) { try { decryptedPassword = CryptoMigrationUtil.decrypt(serverDef.getPasswd()); } catch (Exception e) { return ExecutionResult.FAILURE; } } if (decryptedPassword != null) { serverDef.setPasswd(PasswordUtil.encryptPassword(decryptedPassword)); serverDef.setAlgorithm(PasswordUtil.ALGORITHM_COMMON_V3); try { factory.save(item, true); return ExecutionResult.SUCCESS_NO_ALERT; } catch (Exception e) { ExceptionHandler.process(e); return ExecutionResult.FAILURE; } } } } return ExecutionResult.NOTHING_TO_DO; }
Source:
public void onConnect(WebInspector inspector) { inspector.sendCommand(Timeline.start()); }

Target:
public void onConnect(WebInspector inspector) { inspector.sendCommand(Network.enable()); inspector.sendCommand(Page.enable()); inspector.sendCommand(Timeline.start()); }
Source:
public String toString() { return "polygon (" + polygon.getGeometry().getNumPoints() + " points)"; }

Target:
public String toString() { return "polygon (" + prepPolygon.getGeometry().getNumPoints() + " points," + prepPolygon.getGeometry().getNumGeometries() + " geometries)"; }
Source:
public void clearCachingDirectory() { File cache = new File(getCachingDirectory()); if (cache.exists()) { try { FileUtils.deleteDirectory(cache); } catch (IOException e) { throw new RuntimeException("Cannot create cache dir " + cache, e); } } cache.mkdirs(); }

Target:
public void clearCachingDirectory() { File cache = new File(getCachingDirectory()); if (cache.exists()) { try { FileUtils.deleteDirectory(cache); } catch (IOException e) { throw new NuxeoException("Cannot create cache dir " + cache, e); } } cache.mkdirs(); }
Source:
public Publisher<CacheEntry<K, V>> localPublisher(int segment) { Set<K> seenKeys = new HashSet<>(cache.getAdvancedCache().getDataContainer().sizeIncludingExpired()); Flowable<CacheEntry<K, V>> inMemoryFlowable = Flowable.fromPublisher(cacheSet.localPublisher(segment)) .doOnNext(ce -> seenKeys.add(ce.getKey())); Flowable<CacheEntry<K, V>> loaderFlowable = Flowable.fromPublisher(persistenceManager.<K, V>publishEntries(IntSets.immutableSet(segment), k -> !seenKeys.contains(k), true, true, BOTH)) .map(me -> PersistenceUtil.convert(me, iceFactory)); return Flowable.concat(inMemoryFlowable, loaderFlowable); }

Target:
public Publisher<CacheEntry<K, V>> localPublisher(int segment) { Publisher<CacheEntry<K, V>> inMemorySource = cacheSet.localPublisher(segment); IntSet segments = IntSets.immutableSet(segment); return getCacheEntryPublisher(inMemorySource, segments); }
Source:
void execute() throws IOException { recvCommands(); if (hasCommands()) { for (ReceiveCommand c : getAllCommands()) c.setName(SubscribedRepository.getPubSubRefFromRemote( remote, c.getRefName())); Throwable unpackError = null; if (needPack()) { try { receivePackAndCheckConnectivity(); } catch (IOException err) { unpackError = err; } catch (RuntimeException err) { unpackError = err; } catch (Error err) { unpackError = err; } } if (unpackError == null) { validateCommands(); executeCommands(); } unlockPack(); if (unpackError != null) throw new UnpackException(unpackError); } }

Target:
private void execute() throws IOException { recvCommands(); if (hasCommands()) { for (ReceiveCommand c : getAllCommands()) c.setRefName(RefTranslator.getPubSubRefFromRemote( remote, c.getRefName())); Throwable unpackError = null; if (needPack()) { try { receivePackAndCheckConnectivity(); } catch (IOException err) { unpackError = err; } catch (RuntimeException err) { unpackError = err; } catch (Error err) { unpackError = err; } } if (unpackError == null) { validateCommands(); executeCommands(); } if (unpackError != null) throw new UnpackException(unpackError); } }
Source:
protected static void addGlobalResource(String category, String providerName, String resourcePath) { ResourceFactory resourceFactory = ResourceFactory.getInstance(); PageFactory pageFactory = Context.getRegisteredComponents(PageFactory.class).get(0); File resource = resourceFactory.getResource(providerName, resourcePath); if (resource != null) { GlobalResourceIncluder globalResourceIncluder = new GlobalResourceIncluder(); globalResourceIncluder.addResource(new Resource(category, providerName, resourcePath, -100)); pageFactory.getModelConfigurators().add(globalResourceIncluder); } }

Target:
protected static void addGlobalResource(String category, String providerName, String resourcePath) { ResourceFactory resourceFactory = ResourceFactory.getInstance(); PageFactory pageFactory = Context.getRegisteredComponents(PageFactory.class).get(0); File resource = resourceFactory.getResource(providerName, resourcePath); if (resource != null && pageFactory != null) { GlobalResourceIncluder globalResourceIncluder = new GlobalResourceIncluder(); int priority = -100; globalResourceIncluder.addResource(new Resource(category, providerName, resourcePath, priority)); pageFactory.getModelConfigurators().add(globalResourceIncluder); } }
Source:
private boolean shouldFlushL1(TxInvocationContext ctx) { return shouldInvokeRemoteTxCommand(ctx) || !ctx.isOriginLocal() && !ctx.getAffectedKeys().isEmpty(); }

Target:
private boolean shouldFlushL1(TxInvocationContext ctx) { return !ctx.getAffectedKeys().isEmpty(); }
Source:
private void determineRanking(List<SingleBenchmark> rankedSingleBenchmarkList) { Collections.sort(rankedSingleBenchmarkList, Collections.reverseOrder(new SingleBenchmarkRankingComparator())); int singleBenchmarkRanking = 0; SingleBenchmark previousSingleBenchmark = null; SingleBenchmarkRankingComparator singleBenchmarkRankingComparator = new SingleBenchmarkRankingComparator(); for(SingleBenchmark singleBenchmark : rankedSingleBenchmarkList) { if(previousSingleBenchmark!=null && singleBenchmarkRankingComparator.compare(previousSingleBenchmark, singleBenchmark)!=0) { singleBenchmarkRanking++; } singleBenchmark.setRanking(singleBenchmarkRanking); previousSingleBenchmark = singleBenchmark; } winningSingleBenchmark = rankedSingleBenchmarkList.isEmpty() ? null : rankedSingleBenchmarkList.get(0); worstSingleBenchmark = rankedSingleBenchmarkList.isEmpty() ? null : rankedSingleBenchmarkList.get(rankedSingleBenchmarkList.size() - 1); }

Target:
private void determineRanking(List<SingleBenchmark> rankedSingleBenchmarkList) { Comparator singleBenchmarkRankingComparator = new SingleBenchmarkRankingComparator(); Collections.sort(rankedSingleBenchmarkList, Collections.reverseOrder(singleBenchmarkRankingComparator)); int singleBenchmarkRanking = 0; int sameRankCount = 0; SingleBenchmark previousSingleBenchmark = null; for (SingleBenchmark singleBenchmark : rankedSingleBenchmarkList) { if (previousSingleBenchmark != null && singleBenchmarkRankingComparator.compare(previousSingleBenchmark, singleBenchmark) != 0) { singleBenchmarkRanking += sameRankCount; sameRankCount = 1; } else { sameRankCount++; } singleBenchmark.setRanking(singleBenchmarkRanking); previousSingleBenchmark = singleBenchmark; } winningSingleBenchmark = rankedSingleBenchmarkList.isEmpty() ? null : rankedSingleBenchmarkList.get(0); worstSingleBenchmark = rankedSingleBenchmarkList.isEmpty() ? null : rankedSingleBenchmarkList.get(rankedSingleBenchmarkList.size() - 1); }
Source:
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) { super.bridgeStatusChanged(bridgeStatusInfo); if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE) { scheduler.schedule(() -> { coapClient.startObserve(this); }, 3, TimeUnit.SECONDS); } }

Target:
public void bridgeStatusChanged(ThingStatusInfo bridgeStatusInfo) { super.bridgeStatusChanged(bridgeStatusInfo); if (bridgeStatusInfo.getStatus() == ThingStatus.ONLINE) { scheduler.schedule(() -> { coapClient.startObserve(this); }, 0, TimeUnit.SECONDS); } }
Source:
public float getLoad() { int machPort = SystemB.INSTANCE.mach_host_self(); int[] prevTicks = new int[SystemB.CPU_STATE_MAX]; HOST_CPU_LOAD_INFO cpuLoadInfo = new HOST_CPU_LOAD_INFO(); int ret = SystemB.INSTANCE.host_statistics(machPort, SystemB.HOST_CPU_LOAD_INFO, cpuLoadInfo, new IntByReference( SystemB.HOST_CPU_LOAD_INFO_COUNT)); if (ret == 0) { for (int i = 0; i < SystemB.CPU_STATE_MAX; i++) { prevTicks[i] = cpuLoadInfo.cpu_ticks[i]; } } try { Thread.sleep(1000); } catch (InterruptedException e) { } ret = SystemB.INSTANCE.host_statistics(machPort, SystemB.HOST_CPU_LOAD_INFO, cpuLoadInfo, new IntByReference( SystemB.HOST_CPU_LOAD_INFO_COUNT)); if (ret == 0) { int total = 0; for (int i = 0; i < SystemB.CPU_STATE_MAX; i++) { total += (cpuLoadInfo.cpu_ticks[i] - prevTicks[i]); } int idle = cpuLoadInfo.cpu_ticks[SystemB.CPU_STATE_IDLE] - prevTicks[SystemB.CPU_STATE_IDLE]; return 100f * (total - idle) / total; } return 0; }

Target:
public float getLoad() { int[] prevTicks = getCpuTicks(); try { Thread.sleep(500); } catch (InterruptedException e) { } int[] ticks = getCpuTicks(); int total = 0; for (int i = 0; i < SystemB.CPU_STATE_MAX; i++) { total += (ticks[i] - prevTicks[i]); } int idle = ticks[SystemB.CPU_STATE_IDLE] - prevTicks[SystemB.CPU_STATE_IDLE]; if (total > 0 && idle >= 0) return 100f * (total - idle) / total; else return 0f; }
Source:
public void onAdjustment( final FixedRateWalkerThrottleController controller ) { logger.info( "Current speed upgrades/sec, with average upgrade/sec (is limited to upgrades/sec), currently sleeping {}ms per upgrade.", new Object[] { controller.getLastSliceTps(), controller.getGlobalAverageTps(), controller.getLimiterTps(), controller.getCurrentSleepTime() } ); }

Target:
public void onAdjustment( final FixedRateWalkerThrottleController controller ) { logger.debug( "Current speed upgrades/sec, with average upgrade/sec (is limited to upgrades/sec), currently sleeping {}ms per upgrade.", new Object[] { controller.getLastSliceTps(), controller.getGlobalAverageTps(), controller.getLimiterTps(), controller.getCurrentSleepTime() } ); }
Source:
private static void validateTopics(Catalog catalog, DeploymentType deployment) { Pair<TopicDefaultsType, Map<String, TopicProfileType>> topics = getDeploymentTopics(deployment); TopicDefaultsType defaults = topics.getFirst(); Map<String, TopicProfileType> profileMap = topics.getSecond(); CompoundErrors errors = new CompoundErrors(); if (defaults != null) { validateRetention("topic defaults", defaults.getRetention(), errors); } if (profileMap != null) { for(TopicProfileType profile : profileMap.values()) { String what = "topic profile " + profile.getName(); validateRetention(what, profile.getRetention(), errors); } } if (errors.hasErrors()) { throw new RuntimeException(errors.getErrorMessage()); } hostLog.warn("FIXME: validate the topic references !!!"); }

Target:
private static void validateTopics(Catalog catalog, DeploymentType deployment) { CompoundErrors errors = new CompoundErrors(); Pair<TopicDefaultsType, Map<String, TopicProfileType>> topics = getDeploymentTopics(deployment, errors); TopicDefaultsType defaults = topics.getFirst(); Map<String, TopicProfileType> profileMap = topics.getSecond(); if (defaults != null) { validateRetention("topic defaults", defaults.getRetention(), errors); } if (profileMap != null) { for(TopicProfileType profile : profileMap.values()) { String what = "topic profile " + profile.getName(); validateRetention(what, profile.getRetention(), errors); } } if (errors.hasErrors()) { throw new RuntimeException(errors.getErrorMessage()); } hostLog.warn("FIXME: validate the topic references !!!"); }
Source:
public String toString() { return "VM [" + vmStatic.getvm_name() + "]"; }

Target:
public String toString() { return "VM [" + getName() + "]"; }
Source:
private void createSecurityToken(SoapVersion version, SOAPFactory soapFactory, SOAPElement securityHeader) { Subject subject = anonymousSubject; if (tokenAboutToExpire()) { AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(BaseAuthenticationToken.DEFAULT_REALM); LOGGER.debug("Getting new Anonymous user token"); synchronized (lock) { try { subject = securityManager.getSubject(token); anonymousSubject = subject; } catch (SecurityServiceException sse) { LOGGER.warn("Unable to request subject for anonymous user.", sse); } } } else { LOGGER.debug("Using cached Anonymous user token"); } if (subject != null) { PrincipalCollection principals = subject.getPrincipals(); if (principals != null) { SecurityAssertion securityAssertion = principals.oneByType(SecurityAssertion.class); if (securityAssertion != null) { SecurityToken securityToken = securityAssertion.getSecurityToken(); Element samlElement = securityToken.getToken(); SOAPElement samlAssertion = null; try { samlAssertion = soapFactory.createElement(samlElement); securityHeader.addChildElement(samlAssertion); } catch (SOAPException e) { LOGGER.error("Unable to convert SecurityToken to SOAPElement.", e); } } else { LOGGER.warn("Subject did not contain a security assertion, could not assertion" + "to security header."); } } else { LOGGER.warn("Subject did not contain any principals, could not create element."); } } }

Target:
private void createSecurityToken(SoapVersion version, SOAPFactory soapFactory, SOAPElement securityHeader) { Subject subject = getSubject(); if (subject != null) { PrincipalCollection principals = subject.getPrincipals(); if (principals != null) { SecurityAssertion securityAssertion = principals.oneByType(SecurityAssertion.class); if (securityAssertion != null) { SecurityToken securityToken = securityAssertion.getSecurityToken(); Element samlElement = securityToken.getToken(); SOAPElement samlAssertion = null; try { samlAssertion = soapFactory.createElement(samlElement); securityHeader.addChildElement(samlAssertion); } catch (SOAPException e) { LOGGER.error("Unable to convert SecurityToken to SOAPElement.", e); } } else { LOGGER.warn("Subject did not contain a security assertion, could not assertion" + "to security header."); } } else { LOGGER.warn("Subject did not contain any principals, could not create element."); } } }
Source:
public SeekableByteArrayInputStream(byte[] buf, int maxOffset) { this.buffer = buf; this.cur = 0; this.max = maxOffset; }

Target:
public SeekableByteArrayInputStream(byte[] buf, int maxOffset) { Preconditions.checkNotNull(buf, "bug argument was null"); this.buffer = buf; this.cur = 0; this.max = maxOffset; }
Source:
public ClassFileInfo getClassFileInfo(String className) { if (!jandexStaticCheckAvailable) { throw new ClassFileInfoException("Using old Jandex version."); } return new JandexClassFileInfo(className, index, annotationClassAnnotationsCache, classLoader); }

Target:
public ClassFileInfo getClassFileInfo(String className) { return new JandexClassFileInfo(className, index, annotationClassAnnotationsCache, classLoader); }
Source:
public void createInitialLayout(IPageLayout layout) { layout.setEditorAreaVisible(true); IFolderLayout topLeftFolder = layout.createFolder( "topLeftFolder", IPageLayout.LEFT, 0.15f, IPageLayout.ID_EDITOR_AREA); topLeftFolder.addView(PROJECT_VIEW_ID); IFolderLayout topFolders[] = new IFolderLayout[3]; topFolders[0] = layout.createFolder( "topFolder1", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[0].addView(CPU_VIEW_ID); topFolders[1] = layout.createFolder( "topFolder2", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[1].addView(DISK_VIEW_ID); topFolders[2] = layout.createFolder( "topFolders3", IPageLayout.TOP, 0.30f, IPageLayout.ID_EDITOR_AREA); topFolders[2].addView(MEMORY_VIEW_ID); IFolderLayout bottomRightFolder = layout.createFolder( "bottomRightFolder", IPageLayout.BOTTOM, 0.50f, IPageLayout.ID_EDITOR_AREA); bottomRightFolder.addView(HISTOGRAM_VIEW_ID); bottomRightFolder.addView(BOOKMARKS_VIEW_ID); layout.addNewWizardShortcut(NewTmfProjectWizard.ID); }

Target:
public void createInitialLayout(IPageLayout layout) { layout.setEditorAreaVisible(true); IFolderLayout topLeftFolder = layout.createFolder( "topLeftFolder", IPageLayout.LEFT, 0.15f, IPageLayout.ID_EDITOR_AREA); topLeftFolder.addView(PROJECT_VIEW_ID); IFolderLayout topFolders[] = new IFolderLayout[3]; topFolders[0] = layout.createFolder( "topFolder1", IPageLayout.TOP, 1.0f/5.0f, IPageLayout.ID_EDITOR_AREA); topFolders[0].addView(CPU_VIEW_ID); topFolders[1] = layout.createFolder( "topFolder2", IPageLayout.TOP, 1.0f/4.0f, IPageLayout.ID_EDITOR_AREA); topFolders[1].addView(DISK_VIEW_ID); topFolders[2] = layout.createFolder( "topFolders3", IPageLayout.TOP, 1.0f/3.0f, IPageLayout.ID_EDITOR_AREA); topFolders[2].addView(MEMORY_VIEW_ID); IFolderLayout bottomRightFolder = layout.createFolder( "bottomRightFolder", IPageLayout.BOTTOM, 0.50f, IPageLayout.ID_EDITOR_AREA); bottomRightFolder.addView(HISTOGRAM_VIEW_ID); bottomRightFolder.addView(BOOKMARKS_VIEW_ID); layout.addNewWizardShortcut(NewTmfProjectWizard.ID); }
Source:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("uuid"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); description.addRequiredProperty("voided"); return description; }

Target:
public DelegatingResourceDescription getCreatableProperties() throws ResourceDoesNotSupportOperationException { DelegatingResourceDescription description = new DelegatingResourceDescription(); description.addRequiredProperty("diagnosis"); description.addRequiredProperty("encounter"); description.addRequiredProperty("condition"); description.addRequiredProperty("certainty"); description.addRequiredProperty("patient"); description.addRequiredProperty("rank"); return description; }
Source:
public void updateFlatLighting() { full = state.isFullCube(); packed[0] = state.getPackedLightmapCoords(world, blockPos); for (EnumFacing side : EnumFacing.values()) { int i = side.ordinal() + 1; packed[i] = state.getPackedLightmapCoords(world, blockPos.offset(side)); } }

Target:
public void updateFlatLighting() { full = state.isFullCube(); packed[0] = state.getPackedLightmapCoords(world, blockPos); for (EnumFacing side : SIDES) { int i = side.ordinal() + 1; packed[i] = state.getPackedLightmapCoords(world, blockPos.offset(side)); } }
Source:
public void onMatch(RelOptRuleCall call) { VoltDBLLimit limitOffset = call.rel(0); RelNode input = limitOffset.getInput(); RelTraitSet convertedTraits = limitOffset.getTraitSet() .replace(VoltDBPRel.VOLTDB_PHYSICAL).simplify(); RelNode convertedInput = convert(input, input.getTraitSet().replace(VoltDBPRel.VOLTDB_PHYSICAL).simplify()); int splitCount = (convertedInput instanceof VoltDBPRel) ? ((VoltDBPRel) convertedInput).getSplitCount() : 1; call.transformTo(new VoltDBPLimit( limitOffset.getCluster(), convertedTraits, convertedInput, limitOffset.getOffset(), limitOffset.getLimit(), splitCount)); }

Target:
public void onMatch(RelOptRuleCall call) { VoltDBLLimit limitOffset = call.rel(0); RelNode input = limitOffset.getInput(); RelTraitSet convertedTraits = limitOffset.getTraitSet() .replace(VoltDBPRel.VOLTDB_PHYSICAL).simplify(); RelNode convertedInput = convert(input, input.getTraitSet().replace(VoltDBPRel.VOLTDB_PHYSICAL).simplify()); int splitCount = VoltDBRelUtil.decideSplitCount(convertedInput); call.transformTo(new VoltDBPLimit( limitOffset.getCluster(), convertedTraits, convertedInput, limitOffset.getOffset(), limitOffset.getLimit(), splitCount)); }
Source:
public static Thing createThing(ThingUID thingUID, Configuration configuration, Map<String, String> properties, ThingUID bridgeUID, ThingTypeUID thingTypeUID, List<ThingHandlerFactory> thingHandlerFactories) { for (ThingHandlerFactory thingHandlerFactory : thingHandlerFactories) { if (thingHandlerFactory.supportsThingType(thingTypeUID)) { Thing thing = thingHandlerFactory.createThing(thingTypeUID, configuration, thingUID, bridgeUID); if (thing != null && properties != null) { for (String key : properties.keySet()) { thing.setProperty(key, properties.get(key)); } } return thing; } } return null; }

Target:
public static Thing createThing(ThingUID thingUID, Configuration configuration, Map<String, String> properties, ThingUID bridgeUID, ThingTypeUID thingTypeUID, List<ThingHandlerFactory> thingHandlerFactories) { for (ThingHandlerFactory thingHandlerFactory : thingHandlerFactories) { if (thingHandlerFactory.supportsThingType(thingTypeUID)) { Thing thing = thingHandlerFactory.createThing(thingTypeUID, configuration, thingUID, bridgeUID); if (thing == null) { logger.error("Thing factory returned null when it reports to support the thing"); } else { if (properties != null) { for (String key : properties.keySet()) { thing.setProperty(key, properties.get(key)); } } } return thing; } } return null; }
Source:
public OAuthAuthenticatorProvider(final Set<OAuthAuthenticator> oAuthAuthenticators) { for (final OAuthAuthenticator oneOAuthAuthenticator : oAuthAuthenticators) { this.oAuthAuthenticators.put(oneOAuthAuthenticator.getOAuthProvider(), oneOAuthAuthenticator); } }

Target:
public OAuthAuthenticatorProvider(final Set<OAuthAuthenticator> oAuthAuthenticators) { oAuthAuthenticators.forEach(authenticator -> this.oAuthAuthenticators.put(authenticator.getOAuthProvider(), authenticator)); }
Source:
public Set<AccountGroup.UUID> getAllOwners() { Set<AccountGroup.UUID> result = new HashSet<AccountGroup.UUID>(); for (ProjectState p : tree()) { result.addAll(p.localOwners); } return result; }

Target:
public Set<AccountGroup.UUID> getAllOwners() { Set<AccountGroup.UUID> result = new HashSet<>(); for (ProjectState p : tree()) { result.addAll(p.localOwners); } return result; }
Source:
public JsonNode remove(String name) { return JsonNodeUtils.fromGsonElement(jsonObject.remove(name)); }

Target:
public JsonNode remove(String name) { JsonElement jsonElement = jsonObject.remove(name); return (jsonElement == null) ? null : JsonNodeUtils.fromGsonElement(jsonElement); }
Source:
public void substring() { assertThat( value.apply( "hello" ).substring( 2, 5 ), equalTo( value.apply( "llo" ) ) ); assertThat( value.apply( "hello" ).substring( 4, 5 ), equalTo( value.apply( "o" ) ) ); assertThat( value.apply( "hello" ).substring( 1, 3 ), equalTo( value.apply( "ell" ) ) ); assertThat( value.apply( "hello" ).substring( 8, 5 ), equalTo( StringValue.EMTPY ) ); assertThat( value.apply( "0123456789" ).substring( 1 ), equalTo( value.apply( "123456789" ) ) ); assertThat( value.apply( "0123456789" ).substring( 5 ), equalTo( value.apply( "56789" ) ) ); assertThat( value.apply( "0123456789" ).substring( 15 ), equalTo( StringValue.EMTPY ) ); assertThat( value.apply( "\uD83D\uDE21\uD83D\uDE21\uD83D\uDE21" ).substring( 1, 1 ), equalTo( value.apply( "\uD83D\uDE21" ) ) ); assertThat( value.apply( "\uD83D\uDE21\uD83D\uDE21\uD83D\uDE21" ).substring( 1, 2 ), equalTo( value.apply( "\uD83D\uDE21\uD83D\uDE21" ) ) ); exception.expect( IndexOutOfBoundsException.class ); value.apply( "hello" ).substring( -4, 2 ); }

Target:
public void substring() { assertThat( value.apply( "hello" ).substring( 2, 5 ), equalTo( value.apply( "llo" ) ) ); assertThat( value.apply( "hello" ).substring( 4, 5 ), equalTo( value.apply( "o" ) ) ); assertThat( value.apply( "hello" ).substring( 1, 3 ), equalTo( value.apply( "ell" ) ) ); assertThat( value.apply( "hello" ).substring( 8, 5 ), equalTo( StringValue.EMTPY ) ); assertThat( value.apply( "0123456789" ).substring( 1 ), equalTo( value.apply( "123456789" ) ) ); assertThat( value.apply( "0123456789" ).substring( 5 ), equalTo( value.apply( "56789" ) ) ); assertThat( value.apply( "0123456789" ).substring( 15 ), equalTo( StringValue.EMTPY ) ); assertThat( value.apply( "\uD83D\uDE21\uD83D\uDCA9\uD83D\uDC7B" ).substring( 1, 1 ), equalTo( value.apply( "\uD83D\uDCA9" ) ) ); assertThat( value.apply( "\uD83D\uDE21\uD83D\uDCA9\uD83D\uDC7B" ).substring( 1, 2 ), equalTo( value.apply( "\uD83D\uDCA9\uD83D\uDC7B" ) ) ); exception.expect( IndexOutOfBoundsException.class ); value.apply( "hello" ).substring( -4, 2 ); }
Source:
private void sendData(long timeStamp, Object[] data) { if (siddhiAppContext.isPlayback()) { (this.siddhiAppContext.getTimestampGenerator()) .setCurrentTimestamp(timeStamp); } if (throughputTracker != null && siddhiAppContext.isStatsEnabled()) { throughputTracker.eventIn(); } if (disruptor != null) { long sequenceNo = ringBuffer.next(); try { EventExchangeHolder eventExchangeHolder = ringBuffer.get(sequenceNo); eventExchangeHolder.getAndSetIsProcessed(false); eventExchangeHolder.getEvent().setTimestamp(timeStamp); eventExchangeHolder.getEvent().setIsExpired(false); System.arraycopy(data, 0, eventExchangeHolder.getEvent().getData(), 0, data.length); } finally { ringBuffer.publish(sequenceNo); } } else { for (Receiver receiver : receivers) { receiver.receive(timeStamp, data); } } }

Target:
private void sendData(long timeStamp, Object[] data) { if (siddhiAppContext.isPlayback()) { this.siddhiAppContext.getTimestampGenerator().setCurrentTimestamp(timeStamp); } if (throughputTracker != null && siddhiAppContext.isStatsEnabled()) { throughputTracker.eventIn(); } if (disruptor != null) { long sequenceNo = ringBuffer.next(); try { EventExchangeHolder eventExchangeHolder = ringBuffer.get(sequenceNo); eventExchangeHolder.getAndSetIsProcessed(false); eventExchangeHolder.getEvent().setTimestamp(timeStamp); eventExchangeHolder.getEvent().setIsExpired(false); System.arraycopy(data, 0, eventExchangeHolder.getEvent().getData(), 0, data.length); } finally { ringBuffer.publish(sequenceNo); } } else { for (Receiver receiver : receivers) { receiver.receive(timeStamp, data); } } }
Source:
public static int traverse(List<Task<? extends Serializable>> tasks, Function function) { List<Task<? extends Serializable>> listOfTasks = new ArrayList<>(tasks); int numTasks = 0; while (!listOfTasks.isEmpty()) { List<Task<? extends Serializable>> children = new ArrayList<>(); for (Task<? extends Serializable> task : listOfTasks) { if (function.skipProcessing(task)) { continue; } if (task.getDependentTasks() != null) { children.addAll(task.getDependentTasks()); } function.process(task); numTasks++; } listOfTasks = children; } return numTasks; }

Target:
public static void traverse(List<Task<? extends Serializable>> tasks, Function function) { List<Task<? extends Serializable>> listOfTasks = new ArrayList<>(tasks); while (!listOfTasks.isEmpty()) { List<Task<? extends Serializable>> children = new ArrayList<>(); for (Task<? extends Serializable> task : listOfTasks) { if (function.skipProcessing(task)) { continue; } if (task.getDependentTasks() != null) { children.addAll(task.getDependentTasks()); } function.process(task); } listOfTasks = children; } }
Source:
protected void build(UnitVmModel model, T vm) { vm.setMemSizeMb(model.getMemSize().getEntity()); vm.setMaxMemorySizeMb(model.getMaxMemorySize().getEntity()); if (model.getIoThreadsEnabled().getEntity()) { vm.setNumOfIoThreads(DEFAULT_NUM_OF_IOTHREADS); } else { vm.setNumOfIoThreads(0); } vm.setNumOfSockets(model.getNumOfSockets().getSelectedItem()); vm.setCpuPerSocket(model.getCoresPerSocket().getSelectedItem()); vm.setThreadsPerCpu(model.getThreadsPerCore().getSelectedItem()); vm.setDefaultDisplayType(model.getDisplayType().getSelectedItem()); vm.setNumOfMonitors(model.getNumOfMonitors().getSelectedItem()); vm.setSmartcardEnabled(model.getIsSmartcardEnabled().getEntity()); vm.setSsoMethod(model.extractSelectedSsoMethod()); vm.setMinAllocatedMem(model.getMinAllocatedMemory().getEntity()); vm.setDefaultBootSequence(model.getBootSequence()); vm.setSingleQxlPci(model.getIsSingleQxlEnabled().getEntity()); vm.setCustomEmulatedMachine(model.getEmulatedMachine().getSelectedItem()); vm.setBiosType(BiosType.I440FX_SEA_BIOS); vm.setCustomCpuName(model.getCustomCpu().getSelectedItem()); }

Target:
protected void build(UnitVmModel model, T vm) { vm.setMemSizeMb(model.getMemSize().getEntity()); vm.setMaxMemorySizeMb(model.getMaxMemorySize().getEntity()); if (model.getIoThreadsEnabled().getEntity()) { vm.setNumOfIoThreads(DEFAULT_NUM_OF_IOTHREADS); } else { vm.setNumOfIoThreads(0); } vm.setNumOfSockets(model.getNumOfSockets().getSelectedItem()); vm.setCpuPerSocket(model.getCoresPerSocket().getSelectedItem()); vm.setThreadsPerCpu(model.getThreadsPerCore().getSelectedItem()); vm.setDefaultDisplayType(model.getDisplayType().getSelectedItem()); vm.setNumOfMonitors(model.getNumOfMonitors().getSelectedItem()); vm.setSmartcardEnabled(model.getIsSmartcardEnabled().getEntity()); vm.setSsoMethod(model.extractSelectedSsoMethod()); vm.setMinAllocatedMem(model.getMinAllocatedMemory().getEntity()); vm.setDefaultBootSequence(model.getBootSequence()); vm.setSingleQxlPci(model.getIsSingleQxlEnabled().getEntity()); vm.setCustomEmulatedMachine(model.getEmulatedMachine().getSelectedItem()); vm.setCustomCpuName(model.getCustomCpu().getSelectedItem()); }
Source:
public void setFilterContext(boolean isSelectedInUse, int[] selected, int selectedSize) { this.currBatchIsSelectedInUse = isSelectedInUse; this.currBatchSelected = selected; this.currBatchSelectedSize = selectedSize; for (int i = 0; i < selectedSize-1; i++) assert selected[i] < selected[i+1]; }

Target:
public void setFilterContext(boolean isSelectedInUse, int[] selected, int selectedSize) { this.currBatchIsSelectedInUse = isSelectedInUse; this.currBatchSelected = selected; this.currBatchSelectedSize = selectedSize; assert isValidSelected() : "Selected array may not contain duplicates or unordered values"; }
Source:
public static <X, Y> Key<X, Y> create(ViewMetamodel metamodel, Class<X> sourceEntityViewClass, Class<Y> targetEntityViewClass, String constructorName, ConvertOption... convertOptions) { boolean ignoreMissingAttributes = false; boolean markNew = false; for (ConvertOption copyOption : convertOptions) { switch (copyOption) { case CREATE_NEW: markNew = true; break; case IGNORE_MISSING_ATTRIBUTES: ignoreMissingAttributes = true; break; default: break; } } return create(metamodel, sourceEntityViewClass, targetEntityViewClass, constructorName, ignoreMissingAttributes, markNew); }

Target:
public static <X, Y> Key<X, Y> create(ViewMetamodel metamodel, Class<X> sourceEntityViewClass, Class<Y> targetEntityViewClass, String constructorName, ConvertOption... convertOptions) { return createWithConvertOptions(metamodel, sourceEntityViewClass, targetEntityViewClass, constructorName, false, convertOptions); }
Source:
private void subscribeDataChange(String path, NotificationContext.Type callbackType) { if (callbackType == NotificationContext.Type.INIT || callbackType == NotificationContext.Type.CALLBACK) { if (logger.isDebugEnabled()) { logger.debug(_manager.getInstanceName() + " subscribe data-change. path: " + path + ", listener: " + _listener); } _zkClient.subscribeDataChanges(path, this, callbackType != Type.INIT); } else if (callbackType == NotificationContext.Type.FINALIZE) { logger.info(_manager.getInstanceName() + " unsubscribe data-change. path: " + path + ", listener: " + _listener); _zkClient.unsubscribeDataChanges(path, this); } }

Target:
private void subscribeDataChange(String path, NotificationContext.Type callbackType) { if (callbackType == NotificationContext.Type.INIT || callbackType == NotificationContext.Type.CALLBACK) { if (logger.isDebugEnabled()) { logger.debug(_manager.getInstanceName() + " subscribe data-change. path: " + path + ", listener: " + _listener); } boolean subStatus = _zkClient.subscribeDataChanges(path, this, callbackType != Type.INIT); logger.debug("CallbackHandler subscribe data path result {}", this, path, subStatus); if (!subStatus) { logger.info("CallbackHandler subscribe data path failed!", this, path); } } else if (callbackType == NotificationContext.Type.FINALIZE) { logger.info(_manager.getInstanceName() + " unsubscribe data-change. path: " + path + ", listener: " + _listener); _zkClient.unsubscribeDataChanges(path, this); } }
Source:
public String toString() { return "RestStoreConfiguration [connectionPool=" + connectionPool + ", key2StringMapper=" + key2StringMapper + ", metadataHelper=" + metadataHelper + ", host=" + host + ", port=" + port + ", path=" + path + ", appendCacheNameToPath=" + appendCacheNameToPath + ", rawValues=" + rawValues + ", toString()=" + super.toString() + "]"; }

Target:
public String toString() { return "RestStoreConfiguration [connectionPool=" + connectionPool + ", key2StringMapper=" + key2StringMapper + ", metadataHelper=" + metadataHelper + ", host=" + host + ", port=" + port + ", path=" + path + ", appendCacheNameToPath=" + appendCacheNameToPath + ", rawValues=" + rawValues + ", " + super.toString() + "]"; }
Source:
private void onRemove() { if (getWindow() != null) { return; } ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> vmTemplateImportExportParams = getSelectedItems() .stream() .map(item -> new VmTemplateImportExportParameters(item.getId(), getEntity().getId(), storagePool.getId())) .collect(Collectors.toList()); Frontend.getInstance().runMultipleAction( ActionType.RemoveUnregisteredVmTemplate, vmTemplateImportExportParams, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }

Target:
private void onRemove() { ConfirmationModel model = (ConfirmationModel) getWindow(); if (model.getProgress() != null) { return; } model.startProgress(); AsyncDataProvider.getInstance().getDataCentersByStorageDomain(new AsyncQuery<>(storagePools -> { if (storagePools != null && !storagePools.isEmpty()) { StoragePool storagePool = storagePools.get(0); List<ActionParametersBase> vmTemplateImportExportParams = getSelectedItems() .stream() .map(item -> new VmTemplateImportExportParameters(item.getId(), getEntity().getId(), storagePool.getId())) .collect(Collectors.toList()); Frontend.getInstance().runMultipleAction( ActionType.RemoveUnregisteredVmTemplate, vmTemplateImportExportParams, result -> { ConfirmationModel localModel = (ConfirmationModel) result.getState(); localModel.stopProgress(); cancel(); }, model); } }), getEntity().getId()); }
Source:
void launchServices(OperationContext context, String activeMQServerName, String acceptorName, ModelNode model) throws OperationFailedException { String httpConnectorName = HTTPAcceptorDefinition.HTTP_LISTENER.resolveModelAttribute(context, model).asString(); HTTPUpgradeService.installService(context, activeMQServerName, acceptorName, httpConnectorName); boolean upgradeLegacy = HTTPAcceptorDefinition.UPGRADE_LEGACY.resolveModelAttribute(context, model).asBoolean(); if (upgradeLegacy) { HTTPUpgradeService.LegacyHttpUpgradeService.installService(context, activeMQServerName, acceptorName, httpConnectorName); } }

Target:
void launchServices(OperationContext context, String activeMQServerName, String acceptorName, ModelNode model) throws OperationFailedException { String httpConnectorName = HTTPAcceptorDefinition.HTTP_LISTENER.resolveModelAttribute(context, model).asString(); HTTPUpgradeService.installService(context.getCapabilityServiceTarget(), activeMQServerName, acceptorName, httpConnectorName); boolean upgradeLegacy = HTTPAcceptorDefinition.UPGRADE_LEGACY.resolveModelAttribute(context, model).asBoolean(); if (upgradeLegacy) { HTTPUpgradeService.LegacyHttpUpgradeService.installService(context, activeMQServerName, acceptorName, httpConnectorName); } }
Source:
public EquivalenceUpdater<Channel> channelUpdater() { MultipleSourceChannelEquivalenceUpdater updaters = MultipleSourceChannelEquivalenceUpdater.create(); register(Publisher.BT_TV_CHANNELS, updaters); register(Publisher.BT_TV_CHANNELS_TEST1, updaters); register(Publisher.BT_TV_CHANNELS_TEST2, updaters); register(Publisher.BT_TV_CHANNELS_REFERENCE, updaters); return updaters; }

Target:
public EquivalenceUpdater<Channel> channelUpdater() { MultipleSourceChannelEquivalenceUpdater updaters = MultipleSourceChannelEquivalenceUpdater.create(); registerPublisherUpdaters( updaters, Publisher.BT_TV_CHANNELS, Publisher.BT_TV_CHANNELS_TEST1, Publisher.BT_TV_CHANNELS_TEST2, Publisher.BT_TV_CHANNELS_REFERENCE ); return updaters; }
Source:
private Response cloneVmFromSnapshot(VmStatic staticVm, VM vm, String snapshotId, HashMap<Guid, DiskImage> images) { Guid sourceSnapshotId = asGuid(snapshotId); AddVmFromSnapshotParameters params = new AddVmFromSnapshotParameters(staticVm, sourceSnapshotId); params.setDiskInfoDestinationMap(images); params.setMakeCreatorExplicitOwner(shouldMakeCreatorExplicitOwner()); if (vm.isSetConsoleDeviceEnabled()) { params.setConsoleEnabled(vm.isConsoleDeviceEnabled()); } return performCreate(VdcActionType.AddVmFromSnapshot, params, new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class)); }

Target:
private Response cloneVmFromSnapshot(VmStatic staticVm, VM vm, String snapshotId, HashMap<Guid, DiskImage> images) { Guid sourceSnapshotId = asGuid(snapshotId); AddVmFromSnapshotParameters params = new AddVmFromSnapshotParameters(staticVm, sourceSnapshotId); params.setDiskInfoDestinationMap(images); params.setMakeCreatorExplicitOwner(shouldMakeCreatorExplicitOwner()); params.setConsoleEnabled(vm.isSetConsole() && vm.getConsole().isSetEnabled() ? vm.getConsole().isEnabled() : !getConsoleDevicesForEntity(staticVm.getId()).isEmpty()); return performCreate(VdcActionType.AddVmFromSnapshot, params, new QueryIdResolver<Guid>(VdcQueryType.GetVmByVmId, IdQueryParameters.class)); }
Source:
public static void main(String[] args) { if(args.length!=4&&args.length!=5){ System.out.println("Usage1: ...ChunkerTrain traindata modeldir modelname round"); System.out.println("Usage2: ...ChunkerTrain traindata modeldir modelname max_round dev_ratio"); } ChunkerTrain trainer = new ChunkerTrain(Integer.parseInt(args[3])); if(args.length==4) { trainer.trainModels(args[0]); } else if(args.length==5){ trainer.trainModels(args[0], args[1],args[2],Double.parseDouble(args[4])); } trainer.writeModelsToDisk(args[1],args[2]); }

Target:
public static void main(String[] args) { if(args.length!=4&&args.length!=5){ System.out.println("Usage1: ...ChunkerTrain traindata modeldir modelname round"); System.out.println("Usage2: ...ChunkerTrain traindata modeldir modelname max_round dev_ratio"); System.exit(-1); } ChunkerTrain trainer = new ChunkerTrain(Integer.parseInt(args[3])); if(args.length==4) { trainer.trainModels(args[0]); } else if(args.length==5){ trainer.trainModels(args[0], args[1],args[2],Double.parseDouble(args[4])); } trainer.writeModelsToDisk(args[1],args[2]); }
Source:
public void retryTask(@PathVariable Long activityId) { TaskActivity activity = activityService.getTaskActivityById(activityId); taskTriggerHandler.handleTask(taskService.getTask(activity.getTask()), activity.getParameters()); }

Target:
public void retryTask(@PathVariable Long activityId) { Thread retryThread = new Thread(new Runnable() { @Override public void run() { taskTriggerHandler.retryTask(activityId); } }); retryThread.start(); }
Source:
public void testPRGatherCancellation() throws Throwable { final VM server1 = VM.getVM(0); final VM server2 = VM.getVM(1); final VM client = VM.getVM(2); final int numObjects = 200; final VM controller = VM.getController(); try { final int[] port = AvailablePortHelper.getRandomAvailableTCPPorts(2); startCacheServer(server1, port[0], false, -1, true); startCacheServer(server2, port[1], true, -1, true); startClient(client, port[0]); populateData(server2); server1.invoke("create latch test Hook", () -> { DefaultQuery.testHook = getPauseHook(true, controller); }); AsyncInvocation queryExecution1 = executeQueryOnClient(client); Thread.sleep(1000); setHeapToCriticalAndReleaseLatch(server1); assertThat(queryExecution1.get(60, SECONDS)).isEqualTo(0); verifyDroppedObjectsAndSetHeapToNormal(server1); client.invoke("Executing query when system is 'Normal'", () -> { try { Query query = getCache().getQueryService().newQuery("Select * From /" + "portfolios"); SelectResults results = (SelectResults) query.execute(); assertThat(results.size()).isEqualTo(numObjects); } catch (QueryInvocationTargetException | FunctionDomainException | TypeMismatchException | NameResolutionException e) { fail(""); } }); setHeapToCriticalAndReleaseLatch(server1); AsyncInvocation queryExecution = executeQueryOnClient(client); assertThat(queryExecution.get(60, SECONDS)).isEqualTo(0); verifyDroppedObjectsAndSetHeapToNormal(server1); } finally { stopServer(server1); stopServer(server2); } }

Target:
public void testPRGatherCancellation() throws Throwable { final VM server1 = VM.getVM(0); final VM server2 = VM.getVM(1); final VM client = VM.getVM(2); final int numObjects = 200; final VM controller = VM.getController(); try { final int[] port = AvailablePortHelper.getRandomAvailableTCPPorts(2); startCacheServer(server1, port[0], false, -1, true); startCacheServer(server2, port[1], true, -1, true); startClient(client, port[0]); populateData(server2); server1.invoke("create latch test Hook", () -> { DefaultQuery.testHook = getPauseHook(true, controller); }); AsyncInvocation queryExecution1 = executeQueryOnClient(client); Thread.sleep(1000); setHeapToCriticalAndReleaseLatch(server1); await().untilAsserted(() -> assertThat(queryExecution1.get()).isEqualTo(0)); verifyDroppedObjectsAndSetHeapToNormal(server1); client.invoke("Executing query when system is 'Normal'", () -> { Query query = getCache().getQueryService().newQuery("Select * From /" + "portfolios"); SelectResults results = (SelectResults) query.execute(); assertThat(results.size()).isEqualTo(numObjects); }); setHeapToCriticalAndReleaseLatch(server1); AsyncInvocation queryExecution = executeQueryOnClient(client); await().untilAsserted(() -> assertThat(queryExecution.get()).isEqualTo(0)); verifyDroppedObjectsAndSetHeapToNormal(server1); } finally { stopServer(server1); stopServer(server2); } }
Source:
private boolean sleep() { try { long sleepTime; if (retry == 1 && lastException != null && lastException instanceof ResourceNotFoundException) { sleepTime = WAIT_ON_FIRST_RESOURCE_NOT_FOUND_MILLIS; } else { sleepTime = WAIT_MILLIS_IN_RETRIES[retry]; } Thread.sleep(sleepTime); return true; } catch (InterruptedException e) { logger.error("Interrupted while writing data!"); return false; } }

Target:
private boolean sleep() { try { long sleepTime; if (retry == 1 && lastException != null && lastException instanceof ResourceNotFoundException) { sleepTime = WAIT_ON_FIRST_RESOURCE_NOT_FOUND_MILLIS; } else { sleepTime = WAIT_MILLIS_IN_RETRIES[retry]; } Thread.sleep(sleepTime); return true; } catch (InterruptedException e) { logger.debug("Interrupted while writing data!"); return false; } }