auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void checkIfCommentContainsPattern(XmlFile file) { XPath xpath = XPathFactory.newInstance().newXPath(); String expression = " try { XPathExpression xPathExpression = xpath.compile(expression); NodeList nodes = (NodeList) xPathExpression.evaluate(file.getNamespaceUnawareDocument(), XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); if (null != node) { String comment = node.getNodeValue().toLowerCase(Locale.ENGLISH); if (comment.contains(pattern) && !isLetterAround(comment, pattern)) { check.reportIssue(node, message); } } } } catch (XPathExpressionException e) { throw new IllegalStateException("Failed to run XPath expression", e); } }

Target:
public void checkIfCommentContainsPattern(XmlFile file) { try { NodeList nodes = (NodeList) xPathExpression.evaluate(file.getNamespaceUnawareDocument(), XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { Node node = nodes.item(i); String comment = node.getNodeValue().toLowerCase(Locale.ENGLISH); if (comment.contains(pattern) && !isLetterAround(comment, pattern)) { check.reportIssue(node, message); } } } catch (XPathExpressionException e) { throw new IllegalStateException("Failed to run XPath expression", e); } }
Source:
protected Void visitShowFunctions(ShowFunctions node, Integer context) { builder.append("SHOW FUNCTIONS"); node.getLikePattern().ifPresent((value) -> builder.append(" LIKE ") .append(formatStringLiteral(value))); node.getEscape().ifPresent((value) -> builder.append(" ESCAPE ") .append(formatStringLiteral(value))); return null; }

Target:
protected Void visitShowFunctions(ShowFunctions node, Integer context) { builder.append("SHOW FUNCTIONS"); node.getLikePattern().ifPresent(value -> builder.append(" LIKE ") .append(formatStringLiteral(value))); node.getEscape().ifPresent(value -> builder.append(" ESCAPE ") .append(formatStringLiteral(value))); return null; }
Source:
public void onModuleLoad() { if (canLoadInIFrame(GWT.getModuleBaseURL() + GWT.getModuleName())) { UserAgent.assertNotInIFrame(); } KeyUtil.setEncoderImpl(new KeyUtil.Encoder() { @Override public String encode(String e) { e = URL.encodeQueryString(e); e = fixPathImpl(e); e = fixColonImpl(e); e = fixDoubleQuote(e); return e; } @Override public String decode(final String e) { return URL.decodeQueryString(e); } private native String fixPathImpl(String path) ; private native String fixColonImpl(String path) ; private native String fixDoubleQuote(String path) ; }); initHostname(); Window.setTitle(M.windowTitle1(myHost)); final HostPageDataService hpd = GWT.create(HostPageDataService.class); hpd.load(new GerritCallback<HostPageData>() { @Override public void onSuccess(final HostPageData result) { Document.get().getElementById("gerrit_hostpagedata").removeFromParent(); myConfig = result.config; myTheme = result.theme; if (result.account != null) { myAccount = result.account; xGerritAuth = result.xGerritAuth; } if (result.accountDiffPref != null) { myAccountDiffPref = result.accountDiffPref; applyUserPreferences(); } onModuleLoad2(result); } }); }

Target:
public void onModuleLoad() { if (!canLoadInIFrame(GWT.getModuleBaseURL() + GWT.getModuleName())) { UserAgent.assertNotInIFrame(); } KeyUtil.setEncoderImpl(new KeyUtil.Encoder() { @Override public String encode(String e) { e = URL.encodeQueryString(e); e = fixPathImpl(e); e = fixColonImpl(e); e = fixDoubleQuote(e); return e; } @Override public String decode(final String e) { return URL.decodeQueryString(e); } private native String fixPathImpl(String path) ; private native String fixColonImpl(String path) ; private native String fixDoubleQuote(String path) ; }); initHostname(); Window.setTitle(M.windowTitle1(myHost)); final HostPageDataService hpd = GWT.create(HostPageDataService.class); hpd.load(new GerritCallback<HostPageData>() { @Override public void onSuccess(final HostPageData result) { Document.get().getElementById("gerrit_hostpagedata").removeFromParent(); myConfig = result.config; myTheme = result.theme; if (result.account != null) { myAccount = result.account; xGerritAuth = result.xGerritAuth; } if (result.accountDiffPref != null) { myAccountDiffPref = result.accountDiffPref; applyUserPreferences(); } onModuleLoad2(result); } }); }
Source:
public void clickOnDecrementMemoryButton(String machineName) { seleniumWebDriverHelper.waitAndClick(By.xpath(format(DECREMENT_MEMORY_BUTTON, machineName))); WaitUtils.sleepQuietly(1); }

Target:
public void clickOnDecrementMemoryButton(String machineName) { seleniumWebDriverHelper.waitAndClick(By.xpath(format(DECREMENT_MEMORY_BUTTON, machineName))); }
Source:
private void loadPlugins(HostPageData hpd, final String token) { if (hpd.plugins != null) { for (final String url : hpd.plugins) { ScriptInjector.fromUrl(url) .setWindow(ScriptInjector.TOP_WINDOW) .setCallback(new Callback<Void, Exception>() { @Override public void onSuccess(Void result) { } @Override public void onFailure(Exception reason) { ErrorDialog d = new ErrorDialog(reason); d.setTitle(M.pluginFailed(url)); d.center(); } }).inject(); } } CallbackHandle<Boolean> cb = new CallbackHandle<Boolean>( new ResultDeserializer<Boolean>() { @Override public Boolean fromResult(JavaScriptObject responseObject) { return true; } }, new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(Boolean result) { display(token); } }); cb.install(); ScriptInjector.fromString(cb.getFunctionName() + "(true);").inject(); }

Target:
private void loadPlugins(HostPageData hpd, final String token) { if (hpd.plugins != null) { for (final String url : hpd.plugins) { ScriptInjector.fromUrl(url) .setWindow(ScriptInjector.TOP_WINDOW) .setCallback(new Callback<Void, Exception>() { @Override public void onSuccess(Void result) { } @Override public void onFailure(Exception reason) { ErrorDialog d = new ErrorDialog(reason); d.setTitle(M.pluginFailed(url)); d.center(); } }).inject(); } } CallbackHandle<Boolean> cb = new CallbackHandle<Boolean>( new ResultDeserializer<Boolean>() { @Override public Boolean fromResult(JavaScriptObject responseObject) { return true; } }, new AsyncCallback<Boolean>() { @Override public void onFailure(Throwable caught) { } @Override public void onSuccess(Boolean result) { display(token); } }); cb.install(); ScriptInjector.fromString(cb.getFunctionName() + "(true);") .setWindow(ScriptInjector.TOP_WINDOW) .inject(); }
Source:
private void printAnyOperator(Function function, SymbolPrinterContext context) { List<Symbol> args = function.arguments(); assert args.size() == 2 : "function's number of arguments must be 2"; context.builder.append(PAREN_OPEN); args.get(0).accept(this, context); boolean ignoreCase = LikeOperators.extractIgnoreCase(function); String functionName = function.info().ident().name(); String operatorName = caseSensitiveOperatorName(anyOperatorName(functionName), ignoreCase); context.builder .append(WS) .append(operatorName) .append(WS); context.builder.append(ANY).append(PAREN_OPEN); args.get(1).accept(this, context); context.builder.append(PAREN_CLOSE) .append(PAREN_CLOSE); }

Target:
private void printAnyOperator(Function function, SymbolPrinterContext context) { List<Symbol> args = function.arguments(); assert args.size() == 2 : "function's number of arguments must be 2"; context.builder.append(PAREN_OPEN); args.get(0).accept(this, context); String operatorName = anyOperatorName(function.info().ident().name()); context.builder .append(WS) .append(operatorName) .append(WS); context.builder.append(ANY).append(PAREN_OPEN); args.get(1).accept(this, context); context.builder.append(PAREN_CLOSE) .append(PAREN_CLOSE); }
Source:
public Object[] factory() { return new Object[]{ new ExpirationFunctionalTest().withStorage(StorageType.OBJECT), new ExpirationFunctionalTest().withStorage(StorageType.OFF_HEAP) }; }

Target:
public Object[] factory() { return new Object[]{ new ExpirationFunctionalTest().withStorage(StorageType.BINARY), new ExpirationFunctionalTest().withStorage(StorageType.OBJECT), new ExpirationFunctionalTest().withStorage(StorageType.OFF_HEAP) }; }
Source:
public static void storeUnhandledException(Throwable exception) { SharedPreferences.Editor prefsEditor = preferences.edit(); if (isCrashReportEnabled) { Gson gson = new Gson(); String check = preferences.getString(EXCEPTION_FOR_REPORT, ""); if (check.isEmpty()) { String json = gson.toJson(exception); prefsEditor.putString(EXCEPTION_FOR_REPORT, json); prefsEditor.commit(); } } preferences.edit().putBoolean(RECOVERED_FROM_CRASH, true).commit(); }

Target:
public static void storeUnhandledException(Throwable exception) { SharedPreferences.Editor prefsEditor = preferences.edit(); if (isReportingEnabled()) { Gson gson = new Gson(); String check = preferences.getString(EXCEPTION_FOR_REPORT, ""); if (check.isEmpty()) { String json = gson.toJson(exception); prefsEditor.putString(EXCEPTION_FOR_REPORT, json); prefsEditor.commit(); } } preferences.edit().putBoolean(RECOVERED_FROM_CRASH, true).commit(); }
Source:
public static void setParameterStyle(Parameter parameter, io.swagger.oas.annotations.Parameter p) { if (isExplodable(p)) { if (StringUtils.isNotBlank(p.style())) { parameter.setStyle(Parameter.StyleEnum.valueOf(p.style())); } else { if (HEADER.equals(p.in()) || PATH.equals(p.in())) { parameter.setStyle(Parameter.StyleEnum.SIMPLE); } else if (QUERY.equals(p.in()) || COOKIE.equals(p.in())) { parameter.setStyle(Parameter.StyleEnum.FORM); } } } }

Target:
public static void setParameterStyle(Parameter parameter, io.swagger.oas.annotations.Parameter p) { if (StringUtils.isNotBlank(p.style())) { parameter.setStyle(Parameter.StyleEnum.valueOf(p.style().toUpperCase())); } }
Source:
public void saveOrUpdateShouldNotDeleteOldestPasswordWhenPasswordHistoryEqualToLimit() { List<PasswordHistoryEntity> passwordHistoryEntityList = getPasswordHistoryEntitylistWithElements(PASSWORD_HISTORY_LIMIT); given(this.userRepository.findOne(USER_ID)).willReturn(userEntityWithId); given(this.passwordHistoryRepository.save(passwordHistoryEntityWithUserEntity)).willReturn(passwordHistoryEntityWithUserEntity); given(this.passwordHistoryRepository.findByUserEntity(userEntityWithId)).willReturn(passwordHistoryEntityList); given(this.passwordHistoryRepository.findOldestPassword(USER_ID)).willReturn(passwordHistoryEntityList.get(0)); this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); then(this.passwordHistoryRepository).should(never()).delete(passwordHistoryEntityList.get(0)); }

Target:
public void saveOrUpdateShouldNotDeleteOldestPasswordWhenPasswordHistoryEqualToLimit() { List<PasswordHistoryEntity> passwordHistoryEntityList = getPasswordHistoryEntitylistWithElements(PASSWORD_HISTORY_LIMIT); given(this.userRepository.findOne(USER_ID)).willReturn(userEntityWithId); given(this.passwordHistoryRepository.save(passwordHistoryEntityWithUserEntity)).willReturn(passwordHistoryEntityWithUserEntity); given(this.passwordHistoryRepository.findByUserEntity(userEntityWithId)).willReturn(passwordHistoryEntityList); this.passwordChangeService.saveOrUpdate(passwordHistoryDtoWithUserId); then(this.passwordHistoryRepository).should(never()).delete(passwordHistoryEntityList.get(0)); then(this.userRepository).should().findOne(USER_ID); then(this.passwordHistoryRepository).should().save(passwordHistoryEntityWithUserEntity); then(this.passwordHistoryRepository).should().findByUserEntity(userEntityWithId); }
Source:
private static String colorizeHitString(final Object hitsString) { final String color = LookAndFeel.isCurrentLookAndFeelDark() ? "red" : "#8B0000"; return "<font color='" + color + "'>" + hitsString + "</font>"; }

Target:
private static String colorizeHitString(final Object hitsString) { final String color = LookAndFeel.isCurrentLookAndFeelDark() ? "red" : DARKER_RED; return "<font color='" + color + "'>" + hitsString + "</font>"; }
Source:
public int hashCode() { return name.hashCode() ^ parameterTypes.hashCode(); }

Target:
public final int hashCode() { return name.hashCode() ^ parameterTypes.hashCode(); }
Source:
public List<VariableReferenceExpression> getOriginalDistinctAggregateArgs() { return aggregations.values().stream() .filter(aggregation -> aggregation.getMask().isPresent()) .flatMap(aggregation -> aggregation.getArguments().stream()) .distinct() .map(symbol -> getVariable(symbol, types).get()) .collect(Collectors.toList()); }

Target:
public List<VariableReferenceExpression> getOriginalDistinctAggregateArgs() { return aggregations.values().stream() .filter(aggregation -> aggregation.getMask().isPresent()) .flatMap(aggregation -> aggregation.getArguments().stream()) .distinct() .map(symbol -> toVariableReference(Symbol.from(castToExpression(symbol)), types)) .collect(Collectors.toList()); }
Source:
private AsyncJobStatus processJobFailure(AsyncJobStatus status, EventSink eventSink, Throwable throwable, boolean retry) throws JobStateManagementException, JobMessageDispatchException { status.setEndTime(new Date()); eventSink.rollback(); Object result = null; if (throwable != null) { if (throwable.getCause() instanceof CandlepinException) { result = ((CandlepinException) throwable.getCause()).message(); } else { result = throwable.toString(); } } if (retry) { status = this.updateJobStatus(status, JobState.FAILED_WITH_RETRY, result); log.warn("Job \"{}\" failed in {}ms; retrying...", status.getName(), this.getJobRuntime(status), throwable); this.postJobStatusMessage(status); } else { status = this.updateJobStatus(status, JobState.FAILED, result); log.error("Job \"{}\" failed in {}ms", status.getName(), this.getJobRuntime(status), throwable); } return status; }

Target:
private AsyncJobStatus processJobFailure(AsyncJobStatus status, EventSink eventSink, Throwable throwable, boolean retry) throws JobStateManagementException, JobMessageDispatchException { status.setEndTime(new Date()); eventSink.rollback(); String result = throwable != null ? throwable.toString() : null; if (retry) { status = this.updateJobStatus(status, JobState.FAILED_WITH_RETRY, result); log.warn("Job \"{}\" failed in {}ms; retrying...", status.getName(), this.getJobRuntime(status), throwable); this.postJobStatusMessage(status); } else { status = this.updateJobStatus(status, JobState.FAILED, result); log.error("Job \"{}\" failed in {}ms", status.getName(), this.getJobRuntime(status), throwable); } return status; }
Source:
public void testSupplierIsPolled() throws Exception { entity = app.addChild(EntitySpec.create(DataEntity.class) .configure(DataEntity.POLL_PERIOD, 100l) .configure(DataEntity.SENSOR_SUPPLIER_MAP, MutableMap.<AttributeSensor<?>, Supplier<?>>of(longSensor, currentTimeMillis))); Entities.startManagement(entity); app.start(ImmutableList.of(loc)); Thread.sleep(200l); Long first = entity.getAttribute(longSensor); Thread.sleep(200l); Long second = entity.getAttribute(longSensor); assertNotNull(first); assertNotNull(second); assertTrue(second.longValue() > first.longValue()); }

Target:
public void testSupplierIsPolled() throws Exception { entity = app.createAndManageChild(EntitySpec.create(DataEntity.class) .configure(DataEntity.POLL_PERIOD, 50L) .configure(DataEntity.SENSOR_SUPPLIER_MAP, MutableMap.<AttributeSensor<?>, Supplier<?>>of(longSensor, currentTimeMillis))); app.start(ImmutableList.of(loc)); Asserts.eventually(Entities.attributeSupplier(entity, longSensor), Predicates.notNull()); final Long first = entity.getAttribute(longSensor); assertNotNull(first); Asserts.succeedsEventually(new Runnable() { @Override public void run() { Long second = entity.getAttribute(longSensor); assertNotNull(second); assertTrue(second.longValue() > first.longValue()); } }); }
Source:
public void lockDelegatesToLockService() throws InterruptedException { LockRequest legacyRequest = LockRequest.builder(buildLockMap(LockMode.WRITE)).build(); when(lockService.lock(LockClient.ANONYMOUS.getClientId(), legacyRequest)).thenReturn(LOCK_REFRESH_TOKEN); assertEquals(LOCK_REFRESH_TOKEN, timelock.lock(LockRequestV2.of(ImmutableSet.of(LOCK_A, LOCK_B)))); verify(lockService).lock(LockClient.ANONYMOUS.getClientId(), legacyRequest); }

Target:
public void lockDelegatesToLockService() throws InterruptedException { LockRequest legacyRequest = LockRequest.builder(buildLockMap(LockMode.WRITE)).build(); when(lockService.lock(LockClient.ANONYMOUS.getClientId(), legacyRequest)).thenReturn(LOCK_REFRESH_TOKEN); assertEquals(LOCK_TOKEN_V2, timelock.lock(LockRequestV2.of(ImmutableSet.of(LOCK_A, LOCK_B)))); verify(lockService).lock(LockClient.ANONYMOUS.getClientId(), legacyRequest); }
Source:
public static void tearDown() throws InterruptedException, IOException, TimeoutException { operations.remove(SERVLET_SESSIONS_ADDRESS); administration.reloadIfRequired(); administration.restartIfRequired(); }

Target:
public static void tearDown() throws InterruptedException, IOException, TimeoutException { operations.remove(SERVLET_SESSIONS_ADDRESS); }
Source:
public void testNull() { final AdministrativeStatusType administrativeStatusType = null; final AdministrativeStatusTypeDto administrativeStatusTypeDto = this.configurationMapper.map( administrativeStatusType, AdministrativeStatusTypeDto.class); assertNull(administrativeStatusType); assertNull(administrativeStatusTypeDto); }

Target:
public void testNull() { final AdministrativeStatusType administrativeStatusType = null; final AdministrativeStatusTypeDto administrativeStatusTypeDto = this.configurationMapper.map( administrativeStatusType, AdministrativeStatusTypeDto.class); assertNull(administrativeStatusTypeDto); }
Source:
public void beginSpan(SpanType type, Attributes attributes) { String elementName = getElementName(type); if (elementName == null) { throw new IllegalStateException(type.name()); } writer.writeStartElement(htmlNsUri, elementName); if (type == SpanType.LINK && attributes instanceof LinkAttributes) { String href = ((LinkAttributes) attributes).getHref(); emitAnchorHref(href); applyLinkAttributes(attributes, href); } else if (!isSubstitutedSpan(type)) { applyAttributes(attributes); } }

Target:
public void beginSpan(SpanType type, Attributes attributes) { String elementName = spanTypeToElementNameSubstitutions.get(type); if (elementName == null) { throw new IllegalStateException(type.name()); } writer.writeStartElement(htmlNsUri, elementName); if (type == SpanType.LINK && attributes instanceof LinkAttributes) { String href = ((LinkAttributes) attributes).getHref(); emitAnchorHref(href); applyLinkAttributes(attributes, href); } else { applyAttributes(attributes); } }
Source:
public void getMavenLocalRepoDirTest() { String testRepo = MavenUtils.getMavenRepoDir(MavenRepos.LOCAL); File mavenRepository = FileUtils.getFile(testRepo); SoftAssertions.assertSoftly(softly -> { softly.assertThat(mavenRepository).isNotNull(); softly.assertThat(mavenRepository).isDirectory(); softly.assertAll(); }); }

Target:
public void getMavenLocalRepoDirTest() { String testRepo = MavenUtils.getMavenRepoDir(MavenRepos.LOCAL); assertThat(Files.isDirectory(Paths.get(testRepo))).isTrue(); }
Source:
protected ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (thingTypeUID.equals(THING_TYPE_SAMPLE)) { return new CoAPConnectedLightingHandler(thing); } return null; }

Target:
protected ThingHandler createHandler(Thing thing) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); if (thingTypeUID.equals(THING_TYPE)) { return new CoAPConnectedLightingHandler(thing); } return null; }
Source:
public void buildObject() throws Exception { ProjectToOrganizationConverter converter = new ProjectToOrganizationConverter( defaultApprover, relationColumnFamilyBytes); String projectId = "someProjectId"; String organization1Id = "someOrg1Id"; String organization2Id = "someOrg2Id"; NavigableMap<byte[],byte[]> navigableMap = new TreeMap<byte[],byte[]>( UnsignedBytes.lexicographicalComparator()); navigableMap.put(organization1Id.getBytes(), createOafObject(projectId, organization1Id).toByteArray()); navigableMap.put(organization2Id.getBytes(), createOafObject(projectId, organization2Id).toByteArray()); when(result.getFamilyMap(relationColumnFamilyBytes)).thenReturn(navigableMap); Collection<ProjectToOrganization> projOrgs = converter.buildObject(result, oaf); assertNotNull(projOrgs); assertEquals(2, projOrgs.size()); Iterator<ProjectToOrganization> projOrgIt = projOrgs.iterator(); ProjectToOrganization projOrg = projOrgIt.next(); assertNotNull(projOrg); assertEquals(projectId, projOrg.getProjectId()); assertEquals(organization1Id, projOrg.getOrganizationId()); projOrg = projOrgIt.next(); assertNotNull(projOrg); assertEquals(projectId, projOrg.getProjectId()); assertEquals(organization2Id, projOrg.getOrganizationId()); assertFalse(projOrgIt.hasNext()); }

Target:
public void buildObject() throws Exception { ProjectToOrganizationConverter converter = new ProjectToOrganizationConverter(defaultApprover, relationColumnFamilyBytes); String projectId = "someProjectId"; String organization1Id = "someOrg1Id"; String organization2Id = "someOrg2Id"; NavigableMap<byte[], byte[]> navigableMap = new TreeMap<byte[], byte[]>( UnsignedBytes.lexicographicalComparator()); navigableMap.put(organization1Id.getBytes(), createOafObject(projectId, organization1Id).toByteArray()); navigableMap.put(organization2Id.getBytes(), createOafObject(projectId, organization2Id).toByteArray()); when(result.getFamilyMap(relationColumnFamilyBytes)).thenReturn(navigableMap); List<ProjectToOrganization> projOrgs = converter.buildObject(result, oaf); assertNotNull(projOrgs); assertEquals(2, projOrgs.size()); assertNotNull(projOrgs.get(0)); assertEquals(projectId, projOrgs.get(0).getProjectId()); assertEquals(organization1Id, projOrgs.get(0).getOrganizationId()); assertNotNull(projOrgs.get(1)); assertEquals(projectId, projOrgs.get(1).getProjectId()); assertEquals(organization2Id, projOrgs.get(1).getOrganizationId()); }
Source:
public void shouldFindAllByExample() { Party party = new Party(); party.setName("party"); Example<Party> sample = Example.of(party, ExampleMatcher.matching() .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreNullValues().withIgnorePaths("attendees")); Iterable<Party> parties = repository.findAll(sample); int count = 0; for(Party p:parties) { count +=1; } assertTrue(count == 14); }

Target:
public void shouldFindAllByExample() { Party party = new Party(); party.setName("party"); Example<Party> sample = Example.of(party, ExampleMatcher.matching() .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreNullValues().withIgnorePaths("attendees")); Iterable<Party> parties = repository.findAll(sample); int count = 0; for(Party p:parties) { count +=1; } assertEquals("Count mismatch", 15, count); }
Source:
private void createFBInstance(final ResourceDeploymentData resDepData, final IDeviceManagementInteractor executor) throws DeploymentException { Resource res = resDepData.res; for (FBDeploymentData fb : resDepData.fbs) { if (!fb.fb.isResourceTypeFB()) { executor.createFBInstance(fb, res); curMonitor.worked(1); InterfaceList interfaceList = fb.fb.getInterface(); if (interfaceList != null) { for (VarDeclaration varDecl : interfaceList.getInputVars()) { String val = DeploymentHelper.getVariableValue(varDecl, res.getAutomationSystem()); if (null != val) { executor.writeFBParameter(res, val, fb, varDecl); curMonitor.worked(1); } } } } } }

Target:
private void createFBInstance(final ResourceDeploymentData resDepData, final IDeviceManagementInteractor executor) throws DeploymentException { Resource res = resDepData.res; for (FBDeploymentData fbDepData : resDepData.fbs) { if (!fbDepData.fb.isResourceTypeFB()) { executor.createFBInstance(fbDepData, res); curMonitor.worked(1); InterfaceList interfaceList = fbDepData.fb.getInterface(); if (interfaceList != null) { for (VarDeclaration varDecl : interfaceList.getInputVars()) { String val = DeploymentHelper.getVariableValue(varDecl, res.getAutomationSystem()); if (null != val) { executor.writeFBParameter(res, val, fbDepData, varDecl); curMonitor.worked(1); } } } } } }
Source:
int recover() throws URISyntaxException { try (Response response = ClientBuilder.newClient().target(new URI(recoveryUrl)) .request() .get()) { Assert.assertEquals("Unexpected status from reovery call:", 200, response.getStatus()); String recoveringLRAs = response.readEntity(String.class); return recoveringLRAs.length() - recoveringLRAs.replace(".", "").length(); } }

Target:
int recover() throws URISyntaxException { Client client = ClientBuilder.newClient(); try (Response response = client.target(new URI(recoveryUrl)) .request() .get()) { Assert.assertEquals("Unexpected status from reovery call:", 200, response.getStatus()); String recoveringLRAs = response.readEntity(String.class); return recoveringLRAs.length() - recoveringLRAs.replace(".", "").length(); } finally { client.close(); } }
Source:
private static Options parseCommandLineOrExit(List<String> args) { Options options = new Options(); CustomJCommander jCommander = new CustomJCommander("start-tc-server", options); jCommander.parse(args.toArray(new String[0])); if (options.isHelp()) { jCommander.usage(); System.exit(0); } options.process(jCommander); return options; }

Target:
private static Options parseCommandLineOrExit(List<String> args) { Options options = new Options(); CustomJCommander jCommander = new CustomJCommander(options); jCommander.parse(args.toArray(new String[0])); options.process(jCommander); return options; }
Source:
private void createAndDeployZip(ArtifactoryBuildInfoClient client) throws Exception { String tmpZipPath = path.toString() + File.separator + LOCAL_TMP_ZIP_FILENAME; File tmpZipFile = archiveProjectDir(tmpZipPath); String deploayableZipPath = path.toString() + File.separator + LOCAL_DEPLOYABLE_ZIP_FILENAME; File deployableZipFile = new File(deploayableZipPath); GoZipBallStreamer pkgArchiver = new GoZipBallStreamer(new ZipFile(tmpZipFile), moduleName, version, logger); pkgArchiver.writeDeployableZip(deployableZipFile); Artifact deployedPackage = deploy(client, deployableZipFile, PKG_ZIP_FILE_EXTENSION); artifactList.add(deployedPackage); tmpZipFile.delete(); deployableZipFile.delete(); }

Target:
private void createAndDeployZip(ArtifactoryBuildInfoClient client) throws Exception { File tmpZipFile = archiveProjectDir(); File deployableZipFile = File.createTempFile(LOCAL_PKG_FILENAME, PKG_ZIP_FILE_EXTENSION, path.toFile()); try (GoZipBallStreamer pkgArchiver = new GoZipBallStreamer(new ZipFile(tmpZipFile), moduleName, version, logger)) { pkgArchiver.writeDeployableZip(deployableZipFile); Artifact deployedPackage = deploy(client, deployableZipFile, PKG_ZIP_FILE_EXTENSION); artifactList.add(deployedPackage); } finally { Files.deleteIfExists(tmpZipFile.toPath()); Files.deleteIfExists(deployableZipFile.toPath()); } }
Source:
public boolean includeMethodFromExpression(String expression, ITestNGMethod tm) { String msg = "Beanshell related classes could not be found in CLASSPATH." + "Please add a dependency to bsh.Interpreter (beanshell jar) to your build file and try again."; throw new TestNGException(msg); }

Target:
public boolean includeMethodFromExpression(String expression, ITestNGMethod tm) { String msg = "Beanshell related classes could not be found in CLASSPATH." + "Please add a compile dependency to 'org.apache-extras.beanshell:bsh:2.0b6' in your build file and try " + "again."; throw new TestNGException(msg); }
Source:
private static String createQueueName(String clientId, String pubId, boolean shared, boolean global, boolean isVolatile) { String queue = clientId == null || clientId.isEmpty() || global ? pubId : clientId + "." + pubId; if (shared) { if (queue.contains("|")) { queue = queue.split("\\|")[0]; } if (isVolatile) { queue += ":shared-volatile"; } } return queue; }

Target:
private static String createQueueName(String clientId, String pubId, boolean shared, boolean global, boolean isVolatile) { String queue = clientId == null || clientId.isEmpty() || global ? pubId : clientId + "." + pubId; if (shared) { if (queue.contains("|")) { queue = queue.split("\\|")[0]; } if (isVolatile) { queue = "nonDurable" + "." + queue; } } return queue; }
Source:
public void assertCommandForColorChannelBlue() { String expectedReply = "{\"bri\" : 254, \"sat\" : 254, \"hue\" : 43691}"; assertSendCommandForColor(HSBType.BLUE, new HueLightState(), expectedReply); }

Target:
public void assertCommandForColorChannelBlue() { String expectedReply = "{\"bri\" : 254, \"sat\" : 254, \"hue\" : 43690}"; assertSendCommandForColor(HSBType.BLUE, new HueLightState(), expectedReply); }
Source:
public void testIndexSegmentationOnClient() throws Exception { IgniteCache<Object, Object> c1 = ignite(0).cache("org"); IgniteCache<Object, Object> c2 = ignite(0).cache("pers"); c1.put(1, new Organization("o1")); c1.put(2, new Organization("o2")); c2.put(1, new Person2(1, "o1")); c2.put(2, new Person2(2, "o2")); c2.put(3, new Person2(3, "o3")); String select0 = "select o.name n1, p.name n2 from \"pers\".Person2 p join \"org\".Organization o on p.name = o.name"; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { isClient = true; qryParallelism = 2; Ignite client = startGrid(4); assertEquals(2, client.cache("pers").query(new SqlFieldsQuery(select0)).getAll().size()); qryParallelism = 6; assertEquals(2, client.cache("pers").query(new SqlFieldsQuery(select0)).getAll().size()); return null; } }, IgniteCheckedException .class, "Query parallelism mismatch"); }

Target:
public void testIndexSegmentationOnClient() throws Exception { IgniteCache<Object, Object> c1 = ignite(0).cache("org"); IgniteCache<Object, Object> c2 = ignite(0).cache("pers"); c1.put(1, new Organization("o1")); c1.put(2, new Organization("o2")); c2.put(1, new Person2(1, "o1")); c2.put(2, new Person2(2, "o2")); c2.put(3, new Person2(3, "o3")); String select0 = "select o.name n1, p.name n2 from \"pers\".Person2 p join \"org\".Organization o on p.name = o.name"; GridTestUtils.assertThrows(log, new Callable<Object>() { @Override public Object call() throws Exception { isClient = true; qryParallelism = 2; Ignite client = startGrid(4); return null; } }, IgniteCheckedException .class, "Query parallelism mismatch"); }
Source:
public void mintDepositRecordPidTest() { PID pid = repository.mintDepositRecordPid(); assertTrue(pid.getRepositoryPath().contains(RepositoryPathConstants.DEPOSIT_RECORD_BASE)); }

Target:
public void mintDepositRecordPidTest() { PID pid = repository.mintDepositRecordPid(); assertEquals(pid.getQualifier(), RepositoryPathConstants.DEPOSIT_RECORD_BASE); assertTrue(pid.getQualifiedId().startsWith(RepositoryPathConstants.DEPOSIT_RECORD_BASE)); }
Source:
public Void call() throws Exception { if (!ourAddress.equals(origin)) { if (cacheManager.getMembers().contains(origin)) { synchronized (cacheNotifier) { boolean alreadyInstalled = false; for (Object installedListener : cacheNotifier.getListeners()) { if (installedListener instanceof LocalClusterListener && identifier.equals(((LocalClusterListener)installedListener).getId())) { alreadyInstalled = true; break; } } if (!alreadyInstalled) { LocalClusterListener listener = new LocalClusterListener(identifier, origin, distExecutor, cacheNotifier, cacheManagerNotifier); cacheNotifier.addListener(listener, filter, converter); cacheManagerNotifier.addListener(listener); if (!cacheManager.getMembers().contains(origin)) { cacheNotifier.removeListener(listener); cacheManagerNotifier.removeListener(listener); log.tracef("Removing local cluster listener for remote cluster listener that was just registered, as the origin %s went away concurrently", origin); } else { log.tracef("Registered local cluster listener for remote cluster listener from origin %s with id %s", origin, identifier); } } else { log.tracef("Local cluster listener from origin %s with id % was already installed, ignoring", origin, identifier); } } } else { log.tracef("Not registering local cluster listener for remote cluster listener from origin %s, as the origin went away", origin); } } else { log.trace("Not registering local cluster listener as we are the node who registered the cluster listener"); } return null; }

Target:
public Void call() throws Exception { if (!ourAddress.equals(origin)) { if (cacheManager.getMembers().contains(origin)) { synchronized (cacheNotifier) { boolean alreadyInstalled = false; for (Object installedListener : cacheNotifier.getListeners()) { if (installedListener instanceof RemoteClusterListener && identifier.equals(((RemoteClusterListener)installedListener).getId())) { alreadyInstalled = true; break; } } if (!alreadyInstalled) { RemoteClusterListener listener = new RemoteClusterListener(identifier, origin, distExecutor, cacheNotifier, cacheManagerNotifier); cacheNotifier.addListener(listener, filter, converter); cacheManagerNotifier.addListener(listener); if (!cacheManager.getMembers().contains(origin)) { cacheNotifier.removeListener(listener); cacheManagerNotifier.removeListener(listener); if (log.isTraceEnabled()) { log.tracef("Removing local cluster listener for remote cluster listener that was just registered, as the origin %s went away concurrently", origin); } } else if (log.isTraceEnabled()) { log.tracef("Registered local cluster listener for remote cluster listener from origin %s with id %s", origin, identifier); } } else if (log.isTraceEnabled()) { log.tracef("Local cluster listener from origin %s with id % was already installed, ignoring", origin, identifier); } } } else if (log.isTraceEnabled()) { log.tracef("Not registering local cluster listener for remote cluster listener from origin %s, as the origin went away", origin); } } else if (log.isTraceEnabled()) { log.trace("Not registering local cluster listener as we are the node who registered the cluster listener"); } return null; }
Source:
private int md5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.getBytes()); byte[] digest = md5.digest(); for (int i=0; i<4; i++) digest[i] ^= digest[i+4]+digest[i+8]+digest[i+12]; return (b2i(digest[0])<< 24)|(b2i(digest[1])<<16)|(b2i(digest[2])<< 8)|b2i(digest[3]); } catch (GeneralSecurityException e) { throw new Error("Could not generate MD5 hash", e); } }

Target:
private int md5(String s) { try { MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.update(s.getBytes()); byte[] digest = md5.digest(); for (int i=0; i<4; i++) digest[i] ^= digest[i+4]+digest[i+8]+digest[i+12]; return (b2i(digest[0])<< 24)|(b2i(digest[1])<<16)|(b2i(digest[2])<< 8)|b2i(digest[3]); } catch (GeneralSecurityException e) { throw new RuntimeException("Could not generate MD5 hash", e); } }
Source:
private boolean testForEvent(ITmfEvent event, ITmfStateSystem ss) throws AttributeNotFoundException { if (fStateValueList[1] == null) { ITmfXmlStateValue filter = fStateValueList[0]; int quark = IXmlStateSystemContainer.ROOT_QUARK; for (ITmfXmlStateAttribute attribute : filter.getAttributes()) { quark = attribute.getAttributeQuark(event, quark); if (quark == IXmlStateSystemContainer.ERROR_QUARK) { throw new AttributeNotFoundException(ss.getSSID() + " Attribute:" + attribute); } } ITmfStateValue valueXML; valueXML = filter.getValue(event); ITmfStateValue valueState = (quark != IXmlStateSystemContainer.ROOT_QUARK) ? ss.queryOngoingState(quark) : filter.getEventFieldValue(event); if (valueState == null) { throw new IllegalStateException(); } return compare(valueState, valueXML, fConditionOperator); } else if (fStateValueList[1] != null) { ITmfStateValue valuesXML[] = new ITmfStateValue[2]; valuesXML[0] = fStateValueList[0].getValue(event); valuesXML[1] = fStateValueList[1].getValue(event); return valuesXML[0].equals(valuesXML[1]); } throw new IllegalStateException(); }

Target:
private boolean testForEvent(ITmfEvent event, ITmfStateSystem ss) throws AttributeNotFoundException { if (fStateValues.size() == 1) { ITmfXmlStateValue filter = fStateValues.get(0); int quark = IXmlStateSystemContainer.ROOT_QUARK; for (ITmfXmlStateAttribute attribute : filter.getAttributes()) { quark = attribute.getAttributeQuark(event, quark); if (quark == IXmlStateSystemContainer.ERROR_QUARK) { throw new AttributeNotFoundException(ss.getSSID() + " Attribute:" + attribute); } } ITmfStateValue valueState = (quark != IXmlStateSystemContainer.ROOT_QUARK) ? ss.queryOngoingState(quark) : filter.getEventFieldValue(event); if (valueState == null) { throw new IllegalStateException("TmfXmlCondition : The state value does not exist in the state system"); } ITmfStateValue valueXML; valueXML = filter.getValue(event); return compare(valueState, valueXML, fConditionOperator); } ITmfStateValue valuesXML1 = fStateValues.get(0).getValue(event); ITmfStateValue valuesXML2 = fStateValues.get(1).getValue(event); return valuesXML1.equals(valuesXML2); }
Source:
private MetacardImpl getMetacard(String propertyTypeName, Map<String, Object> properties) throws CatalogTransformerException { if (isEmpty(propertyTypeName) || metacardTypes == null) { LOGGER.debug( "MetacardType specified in input is null or empty. Trying all transformers in order..."); Optional<MetacardImpl> first = inputTransformers == null ? Optional.of(new MetacardImpl()) : inputTransformers .stream() .map( serviceReference -> { try { InputTransformer inputTransformer = (InputTransformer) FrameworkUtil.getBundle(this.getClass()) .getBundleContext() .getService(serviceReference); return new MetacardImpl( inputTransformer.transform( new ByteArrayInputStream( ((String) properties.get("metadata")).getBytes()))); } catch (Exception e) { LOGGER.debug( "Error calling transformer: " + serviceReference.getProperty("id"), e); } return null; }) .filter(Objects::nonNull) .findFirst(); return first.orElse(new MetacardImpl()); } else { MetacardType metacardType = metacardTypes .stream() .filter(type -> type.getName().equals(propertyTypeName)) .findFirst() .orElseThrow( () -> new CatalogTransformerException( "MetacardType specified in input has not been registered with the system." + " Cannot parse input. MetacardType name: " + propertyTypeName)); LOGGER.debug("Found registered MetacardType: {}", propertyTypeName); return new MetacardImpl(metacardType); } }

Target:
private MetacardImpl getMetacard(String propertyTypeName, Map<String, Object> properties) throws CatalogTransformerException { if (isEmpty(propertyTypeName) || metacardTypes == null) { LOGGER.debug( "MetacardType specified in input is null or empty. Trying all transformers in order..."); Optional<MetacardImpl> first = inputTransformers == null ? Optional.of(new MetacardImpl()) : inputTransformers .stream() .map(service -> tryTransformers(properties, service)) .filter(Objects::nonNull) .findFirst(); return first.orElse(new MetacardImpl()); } else { MetacardType metacardType = metacardTypes .stream() .filter(type -> type.getName().equals(propertyTypeName)) .findFirst() .orElseThrow( () -> new CatalogTransformerException( "MetacardType specified in input has not been registered with the system." + " Cannot parse input. MetacardType name: " + propertyTypeName)); LOGGER.debug("Found registered MetacardType: {}", propertyTypeName); return new MetacardImpl(metacardType); } }
Source:
protected AmqpBrokerConfig createAmqpBrokerConfig(MsbConfig msbConfig) { Config amqpApplicationConfig = msbConfig.getBrokerConfig(); Config amqpLibConfig = ConfigFactory.load("amqp").getConfig("config.amqp"); Config commonConfig = ConfigFactory.defaultOverrides() .withFallback(amqpApplicationConfig) .withFallback(amqpLibConfig); AmqpBrokerConfig brokerConfig = new AmqpBrokerConfig.AmqpBrokerConfigBuilder().withConfig(commonConfig).build(); if (brokerConfig != null && (brokerConfig.getGroupId() == null || !brokerConfig.getGroupId().isPresent())) { brokerConfig.setGroupId(Optional.of(msbConfig.getServiceDetails().getName())); } return brokerConfig; }

Target:
protected AmqpBrokerConfig createAmqpBrokerConfig(MsbConfig msbConfig) { Config amqpApplicationConfig = msbConfig.getBrokerConfig(); Config amqpLibConfig = ConfigFactory.load("amqp").getConfig("config.amqp"); Config commonConfig = ConfigFactory.defaultOverrides() .withFallback(amqpApplicationConfig) .withFallback(amqpLibConfig); AmqpBrokerConfig brokerConfig = new AmqpBrokerConfig.AmqpBrokerConfigBuilder().withConfig(commonConfig).build(); if (brokerConfig != null && !brokerConfig.getGroupId().isPresent()) { brokerConfig.setGroupId(Optional.of(msbConfig.getServiceDetails().getName())); } return brokerConfig; }
Source:
public void sendChunk(ByteBuf chunk) throws IOException { if (closed.get()) { throw new IOException("ChunkResponder already closed."); } if (!channel.isActive()) { throw new IOException("Connection already closed."); } channel.write(new DefaultHttpContent(chunk)); if (size.addAndGet(chunk.readableBytes()) >= chunkMemoryLimit) { channel.flush(); } }

Target:
public void sendChunk(ByteBuf chunk) throws IOException { if (closed.get()) { throw new IOException("ChunkResponder already closed."); } if (!channel.isActive()) { throw new IOException("Connection already closed."); } int chunkSize = chunk.readableBytes(); channel.write(new DefaultHttpContent(chunk)); tryFlush(chunkSize); }
Source:
private void downloadAndCopyJars (Set<String> jarsToDownload, Path destinationPath) throws IOException { Set<String> copiedJars = new HashSet<>(); for (String jar: jarsToDownload) { if (!copiedJars.contains(jar)) { Path jarPath = Paths.get(jar); File destPath = null; if (destinationPath != null && jarPath != null) { Path jarFileName = jarPath.getFileName(); if (jarFileName != null) { destPath = Paths.get(destinationPath.toString(), jarFileName.toString()).toFile(); } } if (destPath == null) { throw new RuntimeException("null destPath"); } try (InputStream src = fileStorage.download(jar); FileOutputStream dest = new FileOutputStream(destPath) ) { IOUtils.copy(src, dest); copiedJars.add(jar); LOG.debug("Jar copied to {}", jar, destPath); } } } }

Target:
private void downloadAndCopyJars (Set<String> jarsToDownload, Path destinationPath) throws IOException { Set<String> copiedJars = new HashSet<>(); for (String jar: jarsToDownload) { if (!copiedJars.contains(jar)) { Path jarPath = Paths.get(jar); if (destinationPath == null || jarPath == null) { throw new IllegalArgumentException("null destinationPath or jarPath"); } Path jarFileName = jarPath.getFileName(); if (jarFileName == null) { throw new IllegalArgumentException("null farFileName"); } File destPath = Paths.get(destinationPath.toString(), jarFileName.toString()).toFile(); try (InputStream src = fileStorage.download(jar); FileOutputStream dest = new FileOutputStream(destPath) ) { IOUtils.copy(src, dest); copiedJars.add(jar); LOG.debug("Jar copied to {}", jar, destPath); } } } }
Source:
public ListenableFuture<Long> writeDirect(final ByteBuffer bb, final InetSocketAddress remoteAddress) { long size = 0; try { size = channel.send(bb, remoteAddress); } catch (IOException e) { return FutureUtils.immediateFailureFuture(e); } return FutureUtils.immediateResultFuture(size); }

Target:
public ListenableFuture<Long> writeDirect(final ByteBuffer bb, final InetSocketAddress remoteAddress) { long size = 0; try { size = channel.send(bb, remoteAddress); } catch (Exception e) { return FutureUtils.immediateFailureFuture(e); } return FutureUtils.immediateResultFuture(size); }
Source:
private ContrastEnhancementBuilder contrastMethod(String name, Map<String, Expression> constrastParameters) { if ("histogram".equals(name)) { this.method = ContrastMethod.HISTOGRAM; } else if ("normalize".equals(name)) { this.method = ContrastMethod.NORMALIZE; } else if ("logarithmic".equals(name)) { this.method = ContrastMethod.LOGARITHMIC; } else if ("exponential".equals(name)) { this.method = ContrastMethod.EXPONENTIAL; } else { throw new IllegalArgumentException("Unexpected ContrastEnhamcement method " + name); } if(constrastParameters!=null) { options = constrastParameters; } this.unset = false; return this; }

Target:
private ContrastEnhancementBuilder contrastMethod(String name, Map<String, Expression> constrastParameters) { this.method = ContrastMethod.valueOf(name); if(constrastParameters!=null) { options = constrastParameters; } this.unset = false; return this; }
Source:
Map<String, String> fetchAccountMetadataFromZNRecord(ZNRecord record) { if (router.get() == null) { logger.error("Router is not yet initialized"); return null; } List<String> accountBlobIDs = record.getListField(ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); if (accountBlobIDs == null || accountBlobIDs.size() == 0) { logger.debug("ZNRecord={} to read on path={} does not have a simple list with key={}", record, ACCOUNT_METADATA_BLOB_IDS_PATH, ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); return null; } else { BlobIDAndVersion blobIDAndVersion = null; for (String accountBlobIDInJson : accountBlobIDs) { BlobIDAndVersion current = BlobIDAndVersion.fromJson(accountBlobIDInJson); if (blobIDAndVersion == null || blobIDAndVersion.version < current.version) { blobIDAndVersion = current; } } logger.trace("Start reading remote account data from blob and versioned at {}.", blobIDAndVersion.blobID, blobIDAndVersion.version); return readAccountMetadataFromBlobID(blobIDAndVersion.blobID); } }

Target:
Map<String, String> fetchAccountMetadataFromZNRecord(ZNRecord record) { if (router.get() == null) { logger.error("Router is not yet initialized"); return null; } List<String> accountBlobIDs = record.getListField(ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); if (accountBlobIDs == null || accountBlobIDs.size() == 0) { logger.info("ZNRecord={} to read on path={} does not have a simple list with key={}", record, ACCOUNT_METADATA_BLOB_IDS_PATH, ACCOUNT_METADATA_BLOB_IDS_LIST_KEY); return null; } else { BlobIDAndVersion blobIDAndVersion = null; for (String accountBlobIDInJson : accountBlobIDs) { BlobIDAndVersion current = BlobIDAndVersion.fromJson(accountBlobIDInJson); if (blobIDAndVersion == null || blobIDAndVersion.version < current.version) { blobIDAndVersion = current; } } logger.trace("Start reading remote account data from blob and versioned at {}.", blobIDAndVersion.blobID, blobIDAndVersion.version); return readAccountMetadataFromBlobID(blobIDAndVersion.blobID); } }
Source:
public static String getName(String path) { String[] temp; String delimiter = "/"; temp = path.split(delimiter); int size = temp.length; String name = temp[(size - 1)]; System.out.println(name.replaceAll(" ", "_").toLowerCase()); return name.replaceAll(" ", "_").toLowerCase(); }

Target:
public static String getName(String path) { String[] temp; String delimiter = File.separator; temp = path.split(delimiter); int size = temp.length; String name = temp[(size - 1)]; System.out.println(name.replaceAll(" ", "_").toLowerCase()); return name.replaceAll(" ", "_").toLowerCase(); }
Source:
protected PollingResult compareRemoteRevisionWith(AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState _baseline) throws IOException, InterruptedException { final AbstractBuild lastBuild = project.getLastBuild(); if (lastBuild == null) { return PollingResult.BUILD_NOW; } MercurialTagAction baseline = (MercurialTagAction)_baseline; PrintStream output = listener.getLogger(); Node node = project.getLastBuiltOn(); FilePath repository = workspace2Repo(workspace); pull(launcher, repository, listener, output, node); String revisionToBuild = buildChooser.getRevisionToBuild(lastBuild, launcher, workspace, listener); return "tip".equals(revisionToBuild) ? PollingResult.NO_CHANGES : PollingResult.SIGNIFICANT; }

Target:
protected PollingResult compareRemoteRevisionWith(AbstractProject<?, ?> project, Launcher launcher, FilePath workspace, TaskListener listener, SCMRevisionState _baseline) throws IOException, InterruptedException { final AbstractBuild lastBuild = project.getLastBuild(); PrintStream output = listener.getLogger(); Node node = project.getLastBuiltOn(); FilePath repository = workspace2Repo(workspace); pull(launcher, repository, listener, output, node); MercurialTagAction revisionToBuild = buildChooser.getRevisionToBuild(lastBuild, launcher, workspace, listener); return revisionToBuild == null ? PollingResult.NO_CHANGES : PollingResult.SIGNIFICANT; }