auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testClusterManagerUpgradeNotNeeded() { Image currentImmage = createImage(CURRENT_BUILD_NUMBER, CURRENT_BUILD_NUMBER); StatedImage currentImage = StatedImage.statedImage(currentImmage, null, null); StatedImage targetImage = StatedImage.statedImage(currentImmage, null, null); boolean actualResult = underTest.upgradeClusterManager(STACK_ID, currentImage, targetImage); Assertions.assertFalse(actualResult); verify(flowMessageService).fireEventAndLog(STACK_ID, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_MANAGER_UPGRADE_NOT_NEEDED, CURRENT_BUILD_NUMBER); verify(flowMessageService, times(0)).fireEventAndLog(STACK_ID, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_MANAGER_UPGRADE); }

Target:
public void testClusterManagerUpgradeNotNeeded() { Image currImage = createImage(CURRENT_BUILD_NUMBER, CURRENT_BUILD_NUMBER); StatedImage currentImage = StatedImage.statedImage(currImage, null, null); StatedImage targetImage = StatedImage.statedImage(currImage, null, null); boolean actualResult = underTest.upgradeClusterManager(STACK_ID, currentImage, targetImage); Assertions.assertFalse(actualResult); verify(flowMessageService).fireEventAndLog(STACK_ID, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_MANAGER_UPGRADE_NOT_NEEDED, CURRENT_BUILD_NUMBER); verify(flowMessageService, times(0)).fireEventAndLog(STACK_ID, Status.UPDATE_IN_PROGRESS.name(), CLUSTER_MANAGER_UPGRADE); }
Source:
public void dispose() { cm.unregisterForAvailable(this); cm.unregisterForRadioStateChanged(this); cm.unregisterForNetworkStateChanged(this); cm.unregisterForRUIMReady(this); phone.unregisterForNvLoaded(this); phone.mRuimRecords.unregisterForRecordsLoaded(this); cm.unSetOnSignalStrengthUpdate(this); this.removeCallbacksAndMessages(null); cr.unregisterContentObserver(this.mAutoTimeObserver); this.phone = null; this.cm = null; this.ss = null; this.newSS = null; this.cellLoc = null; this.newCellLoc = null; this.cr = null; this.mAutoTimeObserver = null; this.cdmaDataConnectionAttachedRegistrants = null; this.cdmaDataConnectionDetachedRegistrants = null; }

Target:
public void dispose() { cm.unregisterForAvailable(this); cm.unregisterForRadioStateChanged(this); cm.unregisterForNetworkStateChanged(this); cm.unregisterForRUIMReady(this); phone.unregisterForNvLoaded(this); phone.mRuimRecords.unregisterForRecordsLoaded(this); cm.unSetOnSignalStrengthUpdate(this); cr.unregisterContentObserver(this.mAutoTimeObserver); }
Source:
private ValidationResult validateMinimumVersionSupport() { return FeatureSupported.momPolicyOnHost(Version.v3_3) ? ValidationResult.VALID : new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_VDS_VERSION); }

Target:
private ValidationResult validateMinimumVersionSupport() { return FeatureSupported.momPolicyOnHost(getVdsGroup().getcompatibility_version()) ? ValidationResult.VALID : new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_MOM_UPDATE_VDS_VERSION); }
Source:
public void testNotEnoughResourcesAvailableFailsPendingRequests() throws Exception { final SlotRequestId slotRequestId = new SlotRequestId(); final TestingDeclarativeSlotPoolFactory declarativeSlotPoolFactory = new TestingDeclarativeSlotPoolFactory(TestingDeclarativeSlotPool.builder()); try (DeclarativeSlotPoolBridge declarativeSlotPoolBridge = createDeclarativeSlotPoolBridge(declarativeSlotPoolFactory)) { declarativeSlotPoolBridge.start(jobMasterId, "localhost", mainThreadExecutor); CompletableFuture<PhysicalSlot> slotAllocationFuture = CompletableFuture .supplyAsync(() -> declarativeSlotPoolBridge.requestNewAllocatedSlot(slotRequestId, ResourceProfile.UNKNOWN, Time.minutes(5)), mainThreadExecutor) .get(); mainThreadExecutor.execute(() -> declarativeSlotPoolBridge.notifyNotEnoughResourcesAvailable(Collections.emptyList())); try { slotAllocationFuture.join(); Assert.fail(); } catch (Exception e) { Optional<NoResourceAvailableException> expectedException = ExceptionUtils.findThrowable(e, NoResourceAvailableException.class); assertThat(expectedException.isPresent(), is(true)); } } }

Target:
public void testNotEnoughResourcesAvailableFailsPendingRequests() throws Exception { final SlotRequestId slotRequestId = new SlotRequestId(); final TestingDeclarativeSlotPoolFactory declarativeSlotPoolFactory = new TestingDeclarativeSlotPoolFactory(TestingDeclarativeSlotPool.builder()); try (DeclarativeSlotPoolBridge declarativeSlotPoolBridge = createDeclarativeSlotPoolBridge(declarativeSlotPoolFactory)) { declarativeSlotPoolBridge.start(jobMasterId, "localhost", mainThreadExecutor); CompletableFuture<PhysicalSlot> slotAllocationFuture = CompletableFuture .supplyAsync(() -> declarativeSlotPoolBridge.requestNewAllocatedSlot(slotRequestId, ResourceProfile.UNKNOWN, Time.minutes(5)), mainThreadExecutor) .get(); mainThreadExecutor.execute(() -> declarativeSlotPoolBridge.notifyNotEnoughResourcesAvailable(Collections.emptyList())); assertThat( slotAllocationFuture, FlinkMatchers.futureWillCompleteExceptionally( NoResourceAvailableException.class, Duration.ofSeconds(10))); } }
Source:
public Void call() throws Exception { RemoteCache<Integer, String> remote = client(0).getCache(); for (int i = 2; i < 100 ; i++) remote.put(i, "v" + i); return null; }

Target:
public Void call() throws Exception { RemoteCache<Integer, String> remote = client(0).getCache(); int i = 2; while (!rehashCompleted) { remote.put(i, "v" + i); i += 1; } for (int j = i + 1; j < i + 100 ; j++) remote.put(j, "v" + j); return null; }
Source:
public String toString() { StringBuilder sb = new StringBuilder("TmfVisibleRangeUpdatedSignal [source="); if (getSource() != null) { sb.append(getSource().toString()); } else { sb.append("null"); } sb.append(", range="); if (fCurrentRange != null) { sb.append(fCurrentRange.toString()); } else { sb.append("null"); } sb.append(']'); return sb.toString(); }

Target:
public String toString() { StringBuilder sb = new StringBuilder(getClass().getSimpleName() + " [source="); if (getSource() != null) { sb.append(getSource().toString()); } else { sb.append("null"); } sb.append(", range="); if (fCurrentRange != null) { sb.append(fCurrentRange.toString()); } else { sb.append("null"); } sb.append(']'); return sb.toString(); }
Source:
public void testNewInstance() { Optional<String> description = getDescriptionForCallable(new String("abc")::toString); assertTrue(description.isPresent()); assertNameMatch("new String()::toString", "testNewInstance", CLASSNAME, description.get().toString()); }

Target:
public void testNewInstance() { Optional<String> description = getDescriptionForCallable(new String("abc")::toString); assertTrue(description.isPresent()); assertNameMatch("::toString", "testNewInstance", CLASSNAME, description.get()); }
Source:
default @NonNull String getLabel() { if (getUnits() == null) { return getName(); } return (getName() + " (" + getUnits() + ')'); }

Target:
default String getLabel() { String name = getName(); String units = getUnits(); if (units == null) { return name; } return (name + " (" + units + ')'); }
Source:
static Set<Set<CandidateFact>> findCoveringSets(List<CandidateFact> cfactsPassed, Set<String> msrs) { Set<Set<CandidateFact>> cfactset = new HashSet<Set<CandidateFact>>(); List<CandidateFact> cfacts = new ArrayList<CandidateFact>(cfactsPassed); for (Iterator<CandidateFact> i = cfacts.iterator(); i.hasNext();) { CandidateFact cfact = i.next(); i.remove(); if (!checkForColumnExists(cfact, msrs)) { } else if (cfact.getColumns().containsAll(msrs)) { Set<CandidateFact> one = new LinkedHashSet<CandidateFact>(); one.add(cfact); cfactset.add(one); } else { Set<String> remainingMsrs = new HashSet<String>(msrs); remainingMsrs.removeAll(cfact.getColumns()); Set<Set<CandidateFact>> coveringSets = findCoveringSets(cfacts, remainingMsrs); if (!coveringSets.isEmpty()) { for (Set<CandidateFact> set : coveringSets) { set.add(cfact); cfactset.add(set); } } else { LOG.info("Couldnt find any set containing remaining measures:" + remainingMsrs); } } } return cfactset; }

Target:
static Set<Set<CandidateFact>> findCoveringSets(List<CandidateFact> cfactsPassed, Set<String> msrs) { Set<Set<CandidateFact>> cfactset = new HashSet<Set<CandidateFact>>(); List<CandidateFact> cfacts = new ArrayList<CandidateFact>(cfactsPassed); for (Iterator<CandidateFact> i = cfacts.iterator(); i.hasNext();) { CandidateFact cfact = i.next(); i.remove(); if (!checkForColumnExists(cfact, msrs)) { continue; } else if (cfact.getColumns().containsAll(msrs)) { Set<CandidateFact> one = new LinkedHashSet<CandidateFact>(); one.add(cfact); cfactset.add(one); } else { Set<String> remainingMsrs = new HashSet<String>(msrs); remainingMsrs.removeAll(cfact.getColumns()); Set<Set<CandidateFact>> coveringSets = findCoveringSets(cfacts, remainingMsrs); if (!coveringSets.isEmpty()) { for (Set<CandidateFact> set : coveringSets) { set.add(cfact); cfactset.add(set); } } else { LOG.info("Couldnt find any set containing remaining measures:" + remainingMsrs); } } } return cfactset; }
Source:
public ImapClientRespReader(final int maxLineLength) { super(maxLineLength, false, Delimiters.lineDelimiter()); }

Target:
public ImapClientRespReader(final int maxLineLength) { super(maxLineLength, false, DELIMITER); }
Source:
private Boolean doDelete( final ProjectName projectName ) { final DeleteRepositoryParams params = DeleteRepositoryParams.from( projectName.getRepoId() ); final RepositoryId deletedRepositoryId = this.repositoryService.deleteRepository( params ); return deletedRepositoryId != null; }

Target:
private boolean doDelete( final ProjectName projectName ) { final DeleteRepositoryParams params = DeleteRepositoryParams.from( projectName.getRepoId() ); final RepositoryId deletedRepositoryId = this.repositoryService.deleteRepository( params ); return deletedRepositoryId != null; }
Source:
public void analyse(Project project, SensorContext sensorContext) { File workDir = new File(fileSystem.baseDir(), "/pylint/"); prepareWorkDir(workDir); int i = 0; for (File file : fileSystem.files(fileSystem.predicates().hasLanguage(Python.KEY))) { try { File out = new File(workDir, i + ".out"); analyzeFile(file, out, project); i++; } catch (Exception e) { String msg = new StringBuilder() .append("Cannot analyse the file '") .append(file.getAbsolutePath()) .append("', details: '") .append(e) .append("'") .toString(); throw new IllegalStateException(msg, e); } } }

Target:
public void analyse(Project project, SensorContext sensorContext) { File workDir = new File(fileSystem.workDir(), "/pylint/"); prepareWorkDir(workDir); int i = 0; FilePredicates p = fileSystem.predicates(); Iterable<File> files = fileSystem.files(p.and(p.hasType(InputFile.Type.MAIN), p.hasLanguage(Python.KEY))); for (File file : files) { try { File out = new File(workDir, i + ".out"); analyzeFile(file, out, project); i++; } catch (Exception e) { String msg = new StringBuilder() .append("Cannot analyse the file '") .append(file.getAbsolutePath()) .append("', details: '") .append(e) .append("'") .toString(); throw new IllegalStateException(msg, e); } } }
Source:
private static AffMatchOrganizationAltNameFiller createAffMatchOrganizationAltNameFiller() throws IOException { AffMatchOrganizationAltNameFiller altNameFiller = new AffMatchOrganizationAltNameFiller(); List<String> altNamesCountryCodes = of( "at", "be", "bg", "cy", "cz", "de", "dk", "ee", "es", "fi", "fr", "gr", "hr", "hu", "it", "lt", "lu", "lv", "nl", "pl", "pt", "ro", "se", "si", "sk" ); List<String> alternativeNamesResources = altNamesCountryCodes.stream() .map(code -> "/eu/dnetlib/iis/wf/affmatching/universities/universities_" + code + ".csv").collect(toList()); List<List<String>> alternativeNamesDictionary = alternativeNamesFactory.createAlternativeNamesDictionary(alternativeNamesResources); altNameFiller.setAlternativeNamesDictionary(alternativeNamesDictionary); return altNameFiller; }

Target:
private static AffMatchOrganizationAltNameFiller createAffMatchOrganizationAltNameFiller() throws IOException { AffMatchOrganizationAltNameFiller altNameFiller = new AffMatchOrganizationAltNameFiller(); List<Set<String>> alternativeNamesDictionary = alternativeNamesFactory.createAlternativeNamesDictionary(OrganizationAltNameConst.CLASSPATH_ALTERNATIVE_NAMES_CSV_FILES); altNameFiller.setAlternativeNamesDictionary(alternativeNamesDictionary); return altNameFiller; }
Source:
private boolean createButtons(FormToolkit toolkit, Composite sectionClient) { String[] enabledSettings = getEnabledSettings(IDEWorkbenchPlugin .getDefault().getDialogSettings() .getSection(WORKBENCH_SETTINGS)); for (final IConfigurationElement setting : SettingsTransfer.getSettingsTransfers()) { final Button button = toolkit.createButton(sectionClient, setting.getAttribute(ATT_NAME), SWT.CHECK); String helpId = setting.getAttribute(ATT_HELP_CONTEXT); if (helpId != null) PlatformUI.getWorkbench().getHelpSystem().setHelp(button, helpId); if (enabledSettings != null && enabledSettings.length > 0) { String id = setting.getAttribute(ATT_ID); for (String enabledSetting : enabledSettings) { if (enabledSetting.equals(id)) { button.setSelection(true); selectedSettings.add(setting); break; } } } button.setBackground(sectionClient.getBackground()); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (button.getSelection()) selectedSettings.add(setting); else selectedSettings.remove(setting); } }); } return enabledSettings != null && enabledSettings.length > 0; }

Target:
private boolean createButtons(FormToolkit toolkit, Composite sectionClient) { String[] enabledSettings = getEnabledSettings(IDEWorkbenchPlugin .getDefault().getDialogSettings() .getSection(WORKBENCH_SETTINGS)); for (final IConfigurationElement settingsTransfer : SettingsTransfer.getSettingsTransfers()) { final Button button = toolkit.createButton(sectionClient, settingsTransfer.getAttribute(ATT_NAME), SWT.CHECK); String helpId = settingsTransfer.getAttribute(ATT_HELP_CONTEXT); if (helpId != null) PlatformUI.getWorkbench().getHelpSystem().setHelp(button, helpId); if (enabledSettings != null && enabledSettings.length > 0) { String id = settingsTransfer.getAttribute(ATT_ID); for (String enabledSetting : enabledSettings) { if (enabledSetting.equals(id)) { button.setSelection(true); selectedSettings.add(settingsTransfer); break; } } } button.setBackground(sectionClient.getBackground()); button.addSelectionListener(new SelectionAdapter() { @Override public void widgetSelected(SelectionEvent e) { if (button.getSelection()) selectedSettings.add(settingsTransfer); else selectedSettings.remove(settingsTransfer); } }); } return enabledSettings != null && enabledSettings.length > 0; }
Source:
public void interruptThreadAfterTimeout() { final AtomicLong real = new AtomicLong(); final long allowed = 1040; final CountDownLatch latch = new CountDownLatch(1); final Back timeBack = new BkTimeable( new Back() { @Override public void accept(final Socket socket) throws IOException { final long start = System.currentTimeMillis(); while (!Thread.currentThread().isInterrupted()) { real.set(System.currentTimeMillis() - start); } } }, 1000 ); final Thread caller = new Thread( new Runnable() { @Override public void run() { try { timeBack.accept(new Socket()); } catch (final IOException ex) { throw new IllegalArgumentException(ex); } } } ); caller.start(); try { latch.await(allowed, TimeUnit.MILLISECONDS); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } MatcherAssert.assertThat( "Thread run over allowed time limit.", real.get() <= allowed ); }

Target:
public void interruptThreadAfterTimeout() { final AtomicLong real = new AtomicLong(); final long allowed = 1040; final long sleep = 50; final CountDownLatch latch = new CountDownLatch(1); final Back back = new BkTimeable( new Back() { @Override public void accept(final Socket socket) throws IOException { final long start = System.currentTimeMillis(); while (!Thread.currentThread().isInterrupted()) { real.set(System.currentTimeMillis() - start); try { TimeUnit.MILLISECONDS.sleep(sleep); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); } } } }, 1000 ); final Thread caller = new Thread( new Runnable() { @Override public void run() { try { back.accept(new Socket()); } catch (final IOException ex) { throw new IllegalArgumentException(ex); } } } ); caller.start(); try { final boolean elapsed = latch.await(allowed, TimeUnit.MILLISECONDS); MatcherAssert.assertThat( "Thread run over allowed time limit.", !elapsed ); } catch (final InterruptedException ex) { Thread.currentThread().interrupt(); throw new IllegalStateException(ex); } }
Source:
public ExecRow call(ExecRow locatedRow) throws Exception { getOperation().setCurrentRow(locatedRow); getOperation().setCurrentRowLocation(new HBaseRowLocation(locatedRow.getKey())); getOperation().setCurrentBaseRowLocation(locatorFunction.call(operationContext)); StreamLogUtils.logOperationRecord(locatedRow, operationContext); return locatedRow; }

Target:
public ExecRow call(ExecRow locatedRow) throws Exception { getOperation().setCurrentRow(locatedRow); getOperation().setCurrentRowLocation(new HBaseRowLocation(locatedRow.getKey())); if(getOperation().isForUpdate()) { getOperation().setCurrentBaseRowLocation(locatorFunction.apply(operationContext)); } StreamLogUtils.logOperationRecord(locatedRow, operationContext); return locatedRow; }
Source:
protected void initializeConnection() { Assert.state(getDataSource() != null, "DataSource must not be null."); try { if (useSharedExtendedConnection) { if (!(getDataSource() instanceof ExtendedConnectionDataSourceProxy)) { throw new InvalidDataAccessApiUsageException( "You must use a ExtendedConnectionDataSourceProxy for the dataSource when " + "useSharedExtendedConnection is set to true."); } this.con = DataSourceUtils.getConnection(dataSource); ((ExtendedConnectionDataSourceProxy)dataSource).startCloseSuppression(this.con); } else { this.con = dataSource.getConnection(); } if (this.connectionAutoCommit != null && this.con.getAutoCommit() != this.connectionAutoCommit) { this.con.setAutoCommit(this.connectionAutoCommit); } } catch (SQLException se) { close(); throw getExceptionTranslator().translate("Executing query", getSql(), se); } }

Target:
protected void initializeConnection() { Assert.state(getDataSource() != null, "DataSource must not be null."); try { if (useSharedExtendedConnection) { if (!(getDataSource() instanceof ExtendedConnectionDataSourceProxy)) { throw new InvalidDataAccessApiUsageException( "You must use a ExtendedConnectionDataSourceProxy for the dataSource when " + "useSharedExtendedConnection is set to true."); } this.con = DataSourceUtils.getConnection(dataSource); ((ExtendedConnectionDataSourceProxy)dataSource).startCloseSuppression(this.con); } else { this.con = dataSource.getConnection(); } if (this.connectionAutoCommit != null && this.con.getAutoCommit() != this.connectionAutoCommit) { this.initialConnectionAutoCommit = this.con.getAutoCommit(); this.con.setAutoCommit(this.connectionAutoCommit); } } catch (SQLException se) { close(); throw getExceptionTranslator().translate("Executing query", getSql(), se); } }
Source:
public void addRemoteReplicaToLagMetrics(final RemoteReplicaInfo remoteReplicaInfo) { Gauge<Long> replicaLag = new Gauge<Long>() { @Override public Long getValue() { return remoteReplicaInfo.getReplicaLag(); } }; registry.register(MetricRegistry.name(ReplicationMetrics.class, remoteReplicaInfo.getReplicaId() + "-replicaLag"), replicaLag); replicaLags.add(replicaLag); }

Target:
public void addRemoteReplicaToLagMetrics(final RemoteReplicaInfo remoteReplicaInfo) { Gauge<Long> replicaLag = new Gauge<Long>() { @Override public Long getValue() { return remoteReplicaInfo.getReplicaLagInBytes(); } }; registry.register( MetricRegistry.name(ReplicationMetrics.class, remoteReplicaInfo.getReplicaId() + "-replicaLagInBytes"), replicaLag); replicaLagInBytes.add(replicaLag); }
Source:
public void testListSecurityGroupsInLocation() { HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("<LINK_0>")).headers( ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_list.json")).build(); Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder(); requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess); requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse); requestResponseMap.put(list, listResponse).build(); SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get(); Set<SecurityGroup> groups = extension.listSecurityGroupsInLocation(new LocationBuilder() .scope(LocationScope.ZONE) .id(zone) .description("zone") .build()); assertEquals(1, groups.size()); }

Target:
public void testListSecurityGroupsInLocation() { HttpRequest list = HttpRequest.builder().method("GET").endpoint( URI.create("<LINK_0>")).headers( ImmutableMultimap.<String, String> builder().put("Accept", "application/json").put("X-Auth-Token", authToken).build()).build(); HttpResponse listResponse = HttpResponse.builder().statusCode(200).payload( payloadFromResource("/securitygroup_list.json")).build(); Builder<HttpRequest, HttpResponse> requestResponseMap = ImmutableMap.<HttpRequest, HttpResponse> builder(); requestResponseMap.put(keystoneAuthWithUsernameAndPasswordAndTenantName, responseWithKeystoneAccess); requestResponseMap.put(extensionsOfNovaRequest, extensionsOfNovaResponse); requestResponseMap.put(list, listResponse).build(); SecurityGroupExtension extension = requestsSendResponses(requestResponseMap.build()).getSecurityGroupExtension().get(); Set<SecurityGroup> groups = extension.listSecurityGroupsInLocation(new LocationBuilder() .scope(LocationScope.ZONE) .id(zone) .description("zone") .build()); assertEquals(groups.size(), 1); }
Source:
public Fragment getFirstFragment() { return new MyCourseListFragment(); }

Target:
public Fragment getFirstFragment() { return new MyCoursesListFragment(); }
Source:
public void testVpnMsgOrLinkToBrowser() throws Exception { doReturn(mNetwork).when(sMockConnectivityManager).getActiveNetwork(); final NetworkCapabilities nc = new NetworkCapabilities(); doReturn(nc).when(sMockConnectivityManager).getNetworkCapabilities(mNetwork); final String continueMsg = mActivity.getString(R.string.ssl_error_continue); final String continueAnswer = " <a href=" + mActivity.mWebViewClient.mBrowserBailOutToken + ">" + continueMsg + "</a><br>"; assertEquals(continueAnswer, mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser()); nc.addTransportType(NetworkCapabilities.TRANSPORT_VPN); final String vpnWarning = mActivity.getString(R.string.ssl_error_vpnwarning); final String vpnAnswer = " <div class=vpnwarning>" + vpnWarning + "</div><br>"; assertEquals(vpnAnswer, mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser()); }

Target:
public void testVpnMsgOrLinkToBrowser() throws Exception { doReturn(mNetwork).when(sMockConnectivityManager).getActiveNetwork(); final NetworkCapabilities nonVpnCapabilities = new NetworkCapabilities(); doReturn(nonVpnCapabilities).when(sMockConnectivityManager).getNetworkCapabilities( mNetwork); final String continueMsg = mActivity.getString(R.string.ssl_error_continue); final String linkMatcher = ".*<a\\s+href.*"; assertTrue(mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser().matches(linkMatcher)); final NetworkCapabilities vpnCapabilities = new NetworkCapabilities(); vpnCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN); doReturn(vpnCapabilities).when(sMockConnectivityManager).getNetworkCapabilities(mNetwork); final String vpnWarning = mActivity.getString(R.string.ssl_error_vpnwarning); final String vpnMatcher = ".*<div.*vpnwarning.*"; assertTrue(mActivity.mWebViewClient.getVpnMsgOrLinkToBrowser().matches(vpnMatcher)); }
Source:
private void load() { if (loaded) { return; } System.out.println("--- loading sequence node " + getId() + " ---"); try (Transaction tx = service.beginTx()) { start = (int) node.getProperty(PropertyTypes.STARTREF.name()); end = (int) node.getProperty(PropertyTypes.ENDREF.name()); sequence = (String) node.getProperty(PropertyTypes.SEQUENCE.name()); rank = (int) node.getProperty(PropertyTypes.RANK.name()); node.getRelationships(RelTypes.SOURCE).forEach(e -> { sources.add((String) e.getEndNode().getProperty(PropertyTypes.SOURCE.name())); }); tx.success(); } loaded = true; }

Target:
private void load() { if (loaded) { return; } System.out.println("--- loading sequence node " + getId() + " ---"); try (Transaction tx = service.beginTx()) { start = (int) node.getProperty(PropertyTypes.STARTREF.name()); end = (int) node.getProperty(PropertyTypes.ENDREF.name()); sequence = (String) node.getProperty(PropertyTypes.SEQUENCE.name()); rank = (int) node.getProperty(PropertyTypes.RANK.name()); tx.success(); } loaded = true; }
Source:
SubscribedRepository(String name) { this.name = name; subscribeSpecs = new HashMap<String, SubscribeSpec>(); }

Target:
private SubscribedRepository(String name) { this.name = name; subscribeSpecs = new HashSet<SubscribeSpec>(); }
Source:
public EntityData.Event serialize(Event event) { EventMetadata<?> eventMetadata = eventLibrary.getMetadata(event.getClass()); if (eventMetadata == null) { throw new SerializationException("Unregistered event type: " + event.getClass()); } else if (!eventMetadata.isConstructable()) { throw new SerializationException("Cannot serialize event '" + eventMetadata + "' - lacks default constructor so cannot be deserialized"); } EntityData.Event.Builder eventData = EntityData.Event.newBuilder(); serializeEventType(event, eventData); Serializer eventSerializer = typeSerializationLibrary.getSerializerFor(eventMetadata); ByteString.Output fieldIds = ByteString.newOutput(); eventMetadata.getFields().stream().filter(field -> field.isReplicated()).forEach(field -> { EntityData.Value serializedValue = ((ProtobufPersistedData) eventSerializer.serialize(field, event, serializationContext)).getValue(); if (serializedValue != null) { eventData.addFieldValue(serializedValue); fieldIds.write(field.getId()); } }); eventData.setFieldIds(fieldIds.toByteString()); return eventData.build(); }

Target:
public EntityData.Event serialize(Event event) { EventMetadata<?> eventMetadata = eventLibrary.getMetadata(event.getClass()); if (eventMetadata == null) { throw new SerializationException("Unregistered event type: " + event.getClass()); } else if (!eventMetadata.isConstructable()) { throw new SerializationException("Cannot serialize event '" + eventMetadata + "' - lacks default constructor so cannot be deserialized"); } EntityData.Event.Builder eventData = EntityData.Event.newBuilder(); serializeEventType(event, eventData); Serializer eventSerializer = typeSerializationLibrary.getSerializerFor(eventMetadata); ByteString.Output fieldIds = ByteString.newOutput(); for (ReplicatedFieldMetadata field : eventMetadata.getFields()) { if (field.isReplicated()) { EntityData.Value serializedValue = ((ProtobufPersistedData) eventSerializer.serialize(field, event, serializationContext)).getValue(); if (serializedValue != null) { eventData.addFieldValue(serializedValue); fieldIds.write(field.getId()); } } } eventData.setFieldIds(fieldIds.toByteString()); return eventData.build(); }
Source:
private void initializeTopoSharedOffHeapNodeMemoryFlag(TopologyDetails td) { String topoId = td.getId(); topoSharedOffHeapMemoryNodeFlag.put(topoId, false); StormTopology topology = td.getTopology(); if (topology == null) { return; } if (topology.is_set_component_to_shared_memory()) { for (Set<String> sharedNames : topology.get_component_to_shared_memory().values()) { if (sharedNames != null) { for (String name : sharedNames) { double val = topology.get_shared_memory().get(name).get_off_heap_node(); if (val > 0.0) { topoSharedOffHeapMemoryNodeFlag.put(topoId, true); return; } } } } } }

Target:
private void initializeTopoSharedOffHeapNodeMemoryFlag(TopologyDetails td) { String topoId = td.getId(); topoSharedOffHeapMemoryNodeFlag.put(topoId, false); StormTopology topology = td.getTopology(); if (topology == null) { return; } if (topology.is_set_shared_memory()) { for (SharedMemory sharedMemory : topology.get_shared_memory().values()) { double val = sharedMemory.get_off_heap_node(); if (val > 0.0) { topoSharedOffHeapMemoryNodeFlag.put(topoId, true); return; } } } }
Source:
private void releaseFileChannel(long logId, CachedFileChannel cachedFileChannel) { lock.writeLock().lock(); try { if (cachedFileChannel.markDead()) { try { cachedFileChannel.fileChannel.close(); } catch (IOException e) { LOG.warn("Exception occurred in ReferenceCountedFileChannel" + " while closing channel for log file: {}", cachedFileChannel); } finally { IOUtils.close(LOG, cachedFileChannel.fileChannel); } fileChannels.remove(logId, cachedFileChannel); } } finally { lock.writeLock().unlock(); } }

Target:
private void releaseFileChannel(long logId, CachedFileChannel cachedFileChannel) { if (cachedFileChannel.markDead()) { fileChannels.remove(logId, cachedFileChannel); try { cachedFileChannel.fileChannel.close(); } catch (IOException e) { LOG.warn("Exception occurred in ReferenceCountedFileChannel" + " while closing channel for log file: {}", cachedFileChannel); } finally { IOUtils.close(LOG, cachedFileChannel.fileChannel); } } }
Source:
public <TElement extends Element> void updateElement(Graph graph, ExistingElementMutation<TElement> mutation, Authorizations authorizations) { TElement element = mutation.getElement(); if (MUTATION_LOGGER.isTraceEnabled()) { MUTATION_LOGGER.trace("updateElement: %s", element.getId()); } if (!getConfig().isIndexEdges() && element instanceof Edge) { return; } if (flushObjectQueue.containsElementId(element.getId())) { flushObjectQueue.flush(); } UpdateRequestBuilder updateRequestBuilder = prepareUpdateForMutation(graph, mutation); if (updateRequestBuilder != null) { IndexInfo indexInfo = addMutationPropertiesToIndex(graph, mutation); getIndexRefreshTracker().pushChange(indexInfo.getIndexName()); addActionRequestBuilderForFlush(element, updateRequestBuilder); ImmutableSet<String> extendedDataTableNames = mutation.getElement().getExtendedDataTableNames(); if (mutation.getNewElementVisibility() != null && extendedDataTableNames != null && !extendedDataTableNames.isEmpty() ) { extendedDataTableNames.forEach(tableName -> alterExtendedDataElementTypeVisibility( graph, element, element.getExtendedData(tableName), mutation.getOldElementVisibility(), mutation.getNewElementVisibility() )); } if (getConfig().isAutoFlush()) { flush(graph); } } }

Target:
public <TElement extends Element> void updateElement(Graph graph, ExistingElementMutation<TElement> mutation, Authorizations authorizations) { TElement element = mutation.getElement(); if (MUTATION_LOGGER.isTraceEnabled()) { MUTATION_LOGGER.trace("updateElement: %s", element.getId()); } if (!getConfig().isIndexEdges() && element instanceof Edge) { return; } if (flushObjectQueue.containsElementId(element.getId())) { flushObjectQueue.flush(); } UpdateRequestBuilder updateRequestBuilder = prepareUpdateForMutation(graph, mutation); if (updateRequestBuilder != null) { IndexInfo indexInfo = addMutationPropertiesToIndex(graph, mutation); getIndexRefreshTracker().pushChange(indexInfo.getIndexName()); addActionRequestBuilderForFlush(element, updateRequestBuilder); if (mutation.getNewElementVisibility() != null && element.getFetchHints().isIncludeExtendedDataTableNames()) { ImmutableSet<String> extendedDataTableNames = element.getExtendedDataTableNames(); if (extendedDataTableNames != null && !extendedDataTableNames.isEmpty()) { extendedDataTableNames.forEach(tableName -> alterExtendedDataElementTypeVisibility( graph, element, element.getExtendedData(tableName), mutation.getOldElementVisibility(), mutation.getNewElementVisibility() )); } } if (getConfig().isAutoFlush()) { flush(graph); } } }
Source:
public List<Phonenumber> getPhonenumbers() { if (isValidPatientId()) { return loadTestDataService.getAllPhonenumbersBy(getPatientId()); } else { return new ArrayList<>(); } }

Target:
public List<Phonenumber> getPhonenumbers() { return loadTestDataService.getAllPhonenumbersBy(getPatientId()); }
Source:
private boolean hasPermissionOnExternalPath( PathSupplier pathSupplier, String... actions ) throws RepositoryException { Connectors connectors = this.repository().runningState().connectors(); if (!connectors.hasConnectors() || !connectors.hasReadonlyConnectors()) { return true; } Path path = pathSupplier.getAbsolutePath(); if (connectors.isReadonlyPath(path, this)) { if (actions.length > ModeShapePermissions.READONLY_EXTERNAL_PATH_PERMISSIONS.size()) { return false; } List<String> actionsList = new ArrayList<String>(Arrays.asList(actions)); for (Iterator<String> actionsIterator = actionsList.iterator(); actionsIterator.hasNext();) { String action = actionsIterator.next(); if (!ModeShapePermissions.READONLY_EXTERNAL_PATH_PERMISSIONS.contains(action)) { return false; } actionsIterator.remove(); } return actionsList.isEmpty(); } return true; }

Target:
private boolean hasPermissionOnExternalPath( PathSupplier pathSupplier, String... actions ) throws RepositoryException { Connectors connectors = this.repository().runningState().connectors(); if (!connectors.hasConnectors() || !connectors.hasReadonlyConnectors()) { return true; } Path path = pathSupplier.getAbsolutePath(); if (path == null) return false; if (connectors.isReadonlyPath(path, this)) { if (actions.length > ModeShapePermissions.READONLY_EXTERNAL_PATH_PERMISSIONS.size()) { return false; } List<String> actionsList = new ArrayList<String>(Arrays.asList(actions)); for (Iterator<String> actionsIterator = actionsList.iterator(); actionsIterator.hasNext();) { String action = actionsIterator.next(); if (!ModeShapePermissions.READONLY_EXTERNAL_PATH_PERMISSIONS.contains(action)) { return false; } actionsIterator.remove(); } return actionsList.isEmpty(); } return true; }
Source:
public TextAnalyticsClientBuilder endpoint(String endpoint) { try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL")); } this.endpoint = endpoint; return this; }

Target:
public TextAnalyticsClientBuilder endpoint(String endpoint) { Objects.requireNonNull(endpoint, "'endpoint' cannot be null."); try { new URL(endpoint); } catch (MalformedURLException ex) { throw logger.logExceptionAsWarning(new IllegalArgumentException("'endpoint' must be a valid URL", ex)); } this.endpoint = endpoint; return this; }
Source:
public void testJenkinsNodeMetrics() throws Exception { DatadogClientStub client = new DatadogClientStub(); DatadogComputerPublisherTestWrapper computerPublisher = new DatadogComputerPublisherTestWrapper(); ((DatadogComputerPublisherTestWrapper)computerPublisher).setDatadogClient(client); String url = jenkins.getURL().toString(); String hostname = DatadogUtilities.getHostname(null); String nodeHostname = null; for (Computer computer: jenkins.jenkins.getComputers()){ nodeHostname = computer.getHostName(); } String[] expectedTags = new String[3]; expectedTags[0] = "node_name:master"; expectedTags[1] = "node_label:master"; expectedTags[2] = "jenkins_url:" + url; if (nodeHostname != null) { expectedTags = Arrays.copyOf(expectedTags, 4); expectedTags[3] = "node_hostname:" + nodeHostname; } computerPublisher.doRun(); client.assertMetric("jenkins.node_status.count", 1, hostname, expectedTags); client.assertMetric("jenkins.node_status.offline", 0, hostname, expectedTags); client.assertMetric("jenkins.node_status.online", 1, hostname, expectedTags); for (Computer computer: jenkins.jenkins.getComputers()){ computer.setTemporarilyOffline(true, OfflineCause.create(Messages._Hudson_Computer_DisplayName())); } computerPublisher.doRun(); client.assertMetric("jenkins.node_status.count", 1, hostname, expectedTags); client.assertMetric("jenkins.node_status.offline", 1, hostname, expectedTags); client.assertMetric("jenkins.node_status.online", 0, hostname, expectedTags); }

Target:
public void testJenkinsNodeMetrics() throws Exception { DatadogComputerPublisher computerPublisher = new DatadogComputerPublisher(); String url = jenkins.getURL().toString(); String hostname = DatadogUtilities.getHostname(null); String[] expectedTags = new String[3]; expectedTags[0] = "node_name:master"; expectedTags[1] = "node_label:master"; expectedTags[2] = "jenkins_url:" + url; String nodeHostname = jenkins.jenkins.getComputer("").getHostName(); if (nodeHostname != null) { expectedTags = Arrays.copyOf(expectedTags, 4); expectedTags[3] = "node_hostname:" + nodeHostname; } computerPublisher.doRun(); client.assertMetric("jenkins.node_status.count", 1, hostname, expectedTags); client.assertMetric("jenkins.node_status.up", 1, hostname, expectedTags); for (Computer computer: jenkins.jenkins.getComputers()){ computer.setTemporarilyOffline(true, OfflineCause.create(Messages._Hudson_Computer_DisplayName())); } computerPublisher.doRun(); client.assertMetric("jenkins.node_status.count", 1, hostname, expectedTags); client.assertMetric("jenkins.node_status.up", 0, hostname, expectedTags); }
Source:
private void updateConfiguration(final Map<String, Object> configuration) throws ConfigurationException { Set<String> keys = configuration.keySet(); Iterator<String> keysIt = keys.iterator(); while (keysIt.hasNext()) { String key = (String) keysIt.next(); Matcher matcher = EXTRACT_HORIZON_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.debug("given config key '" + key + "' does not follow the expected pattern '<id>.<host>'"); continue; } matcher.reset(); matcher.find(); String deviceId = matcher.group(1); String host = null; String configKey = matcher.group(2); String value = (String) configuration.get(key); if ("host".equals(configKey)) { host = value; } else { throw new ConfigurationException("The given configKey '" + configKey + "' is unknown"); } HorizonBox horizonBox = new HorizonBox(host, DEFAULT_HORIZON_PORT); deviceConfigCache.put(deviceId, horizonBox); } }

Target:
private void updateConfiguration(final Map<String, Object> configuration) throws ConfigurationException { Set<String> keys = configuration.keySet(); Iterator<String> keysIt = keys.iterator(); while (keysIt.hasNext()) { String key = keysIt.next(); if ("service.pid".equals(key)) { continue; } Matcher matcher = EXTRACT_HORIZON_CONFIG_PATTERN.matcher(key); if (!matcher.matches()) { logger.debug("given config key '" + key + "' does not follow the expected pattern '<id>.<host>'"); continue; } matcher.reset(); matcher.find(); String deviceId = matcher.group(1); String host = null; String configKey = matcher.group(2); String value = (String) configuration.get(key); if ("host".equals(configKey)) { host = value; } else { throw new ConfigurationException("The given configKey '" + configKey + "' is unknown"); } HorizonBox horizonBox = new HorizonBox(host, DEFAULT_HORIZON_PORT); deviceConfigCache.put(deviceId, horizonBox); } }
Source:
public Object execute(final ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); final Map parameters = event.getParameters(); final Object value = parameters.get(IWorkbenchCommandConstants.PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID); final String newWindow = (String) parameters .get(IWorkbenchCommandConstants.PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW); if (value == null) { openOther(window); } else { Object[] found = new Object[1]; BusyIndicator.showWhile(null, () -> { try { if (newWindow == null || newWindow.equalsIgnoreCase("false")) { openPerspective((String) value, window); } else { openNewWindowPerspective((String) value, window); } } catch (ExecutionException e) { found[0] = e; } }); if (found[0] instanceof ExecutionException) { throw ((ExecutionException) found[0]); } } return null; }

Target:
public Object execute(final ExecutionEvent event) throws ExecutionException { IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); final Map parameters = event.getParameters(); final Object value = parameters.get(IWorkbenchCommandConstants.PERSPECTIVES_SHOW_PERSPECTIVE_PARM_ID); final String newWindow = (String) parameters .get(IWorkbenchCommandConstants.PERSPECTIVES_SHOW_PERSPECTIVE_PARM_NEWWINDOW); if (value == null) { openOther(window); } else { ExecutionException[] exception = new ExecutionException[1]; BusyIndicator.showWhile(null, () -> { try { if (newWindow == null || newWindow.equalsIgnoreCase("false")) { openPerspective((String) value, window); } else { openNewWindowPerspective((String) value, window); } } catch (ExecutionException e) { exception[0] = e; } }); if (exception[0] != null) { throw exception[0]; } } return null; }
Source:
void addPrefix(String prefix) { assert !prefix.isEmpty(); terminal = false; char ch = prefix.charAt(0); if (!children.containsKey(ch)) { children.put(ch, new Node()); } if (prefix.length() > 1) { children.get(ch).addPrefix(prefix.substring(1)); } }

Target:
void addPrefix(String prefix) { terminal = false; char ch = prefix.charAt(0); children.putIfAbsent(ch, new Node()); if (prefix.length() > 1) { children.get(ch).addPrefix(prefix.substring(1)); } }
Source:
private static boolean isException(FunctionDef suspiciousMethod) { boolean hasDocString = suspiciousMethod.docstring() != null; StatementList suspiciousBody = suspiciousMethod.body(); int nbActualStatements = hasDocString ? suspiciousBody.statements().size() - 1 : suspiciousBody.statements().size(); if (nbActualStatements == 0 || isOnASingleLine(suspiciousBody, hasDocString)) { return true; } return nbActualStatements == 1 && suspiciousBody.statements().get(suspiciousBody.statements().size() - 1).is(Tree.Kind.RAISE_STMT); }

Target:
private static boolean isException(FunctionDef suspiciousMethod) { boolean hasDocString = suspiciousMethod.docstring() != null; StatementList suspiciousBody = suspiciousMethod.body(); List<Statement> statements = suspiciousBody.statements(); int nbActualStatements = hasDocString ? statements.size() - 1 : statements.size(); if (nbActualStatements == 0 || isOnASingleLine(suspiciousBody, hasDocString)) { return true; } return nbActualStatements == 1 && statements.get(statements.size() - 1).is(Tree.Kind.RAISE_STMT); }
Source:
private void flattenTuple(CComplexObject newObject, CAttributeTuple tuple) { CAttributeTuple matchingTuple = findMatchingTuple(newObject.getAttributeTuples(), tuple); CAttributeTuple tupleClone = (CAttributeTuple) tuple.clone(); if(matchingTuple == null) { newObject.addAttributeTuple(tupleClone); } else { newObject.getAttributeTuples().remove(matchingTuple); newObject.addAttributeTuple(tupleClone); } for(CAttribute attribute:tupleClone.getMembers()){ newObject.replaceAttribute(attribute); } }

Target:
private void flattenTuple(CComplexObject newObject, CAttributeTuple tuple) { CAttributeTuple matchingTuple = findMatchingTuple(newObject.getAttributeTuples(), tuple); CAttributeTuple tupleClone = (CAttributeTuple) tuple.clone(); if(matchingTuple == null) { newObject.addAttributeTuple(tupleClone); } else { newObject.getAttributeTuples().remove(matchingTuple); newObject.addAttributeTuple(tupleClone); } for(CAttribute attribute:tupleClone.getMembers()){ newObject.replaceAttribute(attribute); } for(CPrimitiveTuple primitiveTuple:tupleClone.getTuples()) { int i = 0; for(CPrimitiveObject object:primitiveTuple.getMembers()) { object.setSocParent(primitiveTuple); object.setParent((tupleClone.getMembers().get(i))); i++; } } }
Source:
public SafetyCommand() { super(); }

Target:
public SafetyCommand() { this("SafetyCommand"); }
Source:
public static void addSingletonToCount(final LibraryIdGenerator libraryIdGenerator){ addSingletonToCount(libraryIdGenerator.getDuplicateCountHist(), libraryIdGenerator.getNonOpticalDuplicateCountHist()); }

Target:
public static void addSingletonToCount(final LibraryIdGenerator libraryIdGenerator) { libraryIdGenerator.getDuplicateCountHist().increment(1.0); libraryIdGenerator.getNonOpticalDuplicateCountHist().increment(1.0); }
Source:
public void testConstantQuery() throws Exception { runQueryAndWaitForEvents("SELECT 1", 3); QueryCreatedEvent queryCreatedEvent = getOnlyElement(generatedEvents.getQueryCreatedEvents()); assertEquals(queryCreatedEvent.getContext().getServerVersion(), "testversion"); assertEquals(queryCreatedEvent.getContext().getServerAddress(), "127.0.0.1"); assertEquals(queryCreatedEvent.getContext().getEnvironment(), "testing"); assertEquals(queryCreatedEvent.getContext().getClientInfo().get(), "{\"clientVersion\":\"testVersion\"}"); assertEquals(queryCreatedEvent.getMetadata().getQuery(), "SELECT 1"); QueryCompletedEvent queryCompletedEvent = getOnlyElement(generatedEvents.getQueryCompletedEvents()); assertTrue(queryCompletedEvent.getContext().getResourceGroupName().isPresent()); assertEquals(queryCompletedEvent.getContext().getResourceGroupName().get(), "global.event-client-test"); assertEquals(queryCompletedEvent.getStatistics().getTotalRows(), 0L); assertEquals(queryCompletedEvent.getContext().getClientInfo().get(), "{\"clientVersion\":\"testVersion\"}"); assertEquals(queryCreatedEvent.getMetadata().getQueryId(), queryCompletedEvent.getMetadata().getQueryId()); List<SplitCompletedEvent> splitCompletedEvents = generatedEvents.getSplitCompletedEvents(); assertEquals(splitCompletedEvents.get(0).getQueryId(), queryCompletedEvent.getMetadata().getQueryId()); assertEquals(splitCompletedEvents.get(0).getStatistics().getCompletedPositions(), 1); }

Target:
public void testConstantQuery() throws Exception { runQueryAndWaitForEvents("SELECT 1", 3); QueryCreatedEvent queryCreatedEvent = getOnlyElement(generatedEvents.getQueryCreatedEvents()); assertEquals(queryCreatedEvent.getContext().getServerVersion(), "testversion"); assertEquals(queryCreatedEvent.getContext().getServerAddress(), "127.0.0.1"); assertEquals(queryCreatedEvent.getContext().getEnvironment(), "testing"); assertEquals(queryCreatedEvent.getContext().getClientInfo().get(), "{\"clientVersion\":\"testVersion\"}"); assertEquals(queryCreatedEvent.getMetadata().getQuery(), "SELECT 1"); QueryCompletedEvent queryCompletedEvent = getOnlyElement(generatedEvents.getQueryCompletedEvents()); assertTrue(queryCompletedEvent.getContext().getResourceGroupName().isPresent()); assertEquals(queryCompletedEvent.getContext().getResourceGroupName().get(), "global.user-user"); assertEquals(queryCompletedEvent.getStatistics().getTotalRows(), 0L); assertEquals(queryCompletedEvent.getContext().getClientInfo().get(), "{\"clientVersion\":\"testVersion\"}"); assertEquals(queryCreatedEvent.getMetadata().getQueryId(), queryCompletedEvent.getMetadata().getQueryId()); List<SplitCompletedEvent> splitCompletedEvents = generatedEvents.getSplitCompletedEvents(); assertEquals(splitCompletedEvents.get(0).getQueryId(), queryCompletedEvent.getMetadata().getQueryId()); assertEquals(splitCompletedEvents.get(0).getStatistics().getCompletedPositions(), 1); }
Source:
public KafkaPositionTracker(@NotNull final String datastreamTaskPrefix, @NotNull final String datastreamTaskName, @NotNull final Instant connectorTaskStartTime, final boolean enableBrokerOffsetFetcher, @NotNull final Supplier<Boolean> isConnectorTaskAlive, @NotNull final Supplier<Consumer<?, ?>> consumerSupplier) { _datastreamTaskPrefix = datastreamTaskPrefix; _datastreamTaskName = datastreamTaskName; _connectorTaskStartTime = connectorTaskStartTime; _consumerSupplier = consumerSupplier; if (enableBrokerOffsetFetcher) { _brokerOffsetFetcher = new BrokerOffsetFetcher(datastreamTaskName, this, isConnectorTaskAlive); _brokerOffsetFetcher.startAsync(); } else { _brokerOffsetFetcher = null; } }

Target:
private KafkaPositionTracker(@NotNull final String datastreamTaskPrefix, @NotNull final String datastreamTaskName, @NotNull final Instant connectorTaskStartTime, final boolean enableBrokerOffsetFetcher, @NotNull final Supplier<Boolean> isConnectorTaskAlive, @NotNull final Supplier<Consumer<?, ?>> consumerSupplier) { _datastreamTaskPrefix = datastreamTaskPrefix; _datastreamTaskName = datastreamTaskName; _connectorTaskStartTime = connectorTaskStartTime; _consumerSupplier = consumerSupplier; if (enableBrokerOffsetFetcher) { _brokerOffsetFetcher = new BrokerOffsetFetcher(datastreamTaskName, this, isConnectorTaskAlive); _brokerOffsetFetcher.startAsync(); } else { _brokerOffsetFetcher = null; } }