auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void verifyResendPublishedEmailButtonExists(String courseId, String evalName) { int rowId = getEvaluationRowId(courseId, evalName); waitForElementPresence(By.id("session" + rowId)); WebElement sessionRow = browser.driver.findElement(By.id("session" + rowId)); String resendLinksClassNamePrefix = "session-resend-published-email-for-test"; <START> verifyElementContainsElement(sessionRow, By.className(resendLinksClassNamePrefix)); <END> }</code><technical_language>summarise lines: java WebElement sessionRow = waitForElementPresence(By.id("session" + getEvaluationRowId(courseId, evalName))); verifyElementContainsElement(sessionRow, By.className("session-resend-published-email-for-test"));</technical_language>

Target:
public void verifyResendPublishedEmailButtonExists(String courseId, String evalName) { WebElement sessionRow = waitForElementPresence(By.id("session" + getEvaluationRowId(courseId, evalName))); verifyElementContainsElement(sessionRow, By.className("session-resend-published-email-for-test")); }
Source:
<code>public void click() { WebElement we = resolve(); waitFor(we). <START> withTimeout(time.seconds(1), TimeUnit.MILLISECONDS). <END> pollingEvery(time.milliseconds(100), TimeUnit.MILLISECONDS). ignoring(ElementClickInterceptedException.class). until(() -> {we.click(); return true;}); }</code><technical_language>This a lot of code 1 second. Duration.ofSeconds(1) if ? I duration reading</technical_language>

Target:
public void click() { WebElement we = resolve(); waitFor(we). withTimeout(1, TimeUnit.SECONDS). pollingEvery(100, TimeUnit.MILLISECONDS). ignoring(ElementClickInterceptedException.class). until(() -> {we.click(); return true;}); }
Source:
<code>private void checkComments(RevisionResource revision, Map<String, List<Comment>> in) throws BadRequestException, OrmException { Iterator<Map.Entry<String, List<Comment>>> mapItr = in.entrySet().iterator(); <START> List<String> filePaths = <END> changeDataFactory.create(db.get(), revision.getChange()).filePaths( revision.getPatchSet()); while (mapItr.hasNext()) { Map.Entry<String, List<Comment>> ent = mapItr.next(); String path = ent.getKey(); if (!filePaths.contains(path) && !Patch.COMMIT_MSG.equals(path)) { throw new BadRequestException(String.format( "file %s not found in patch set %s", path, change.currentPatchSetId())); } List<Comment> list = ent.getValue(); if (list == null) { mapItr.remove(); continue; } Iterator<Comment> listItr = list.iterator(); while (listItr.hasNext()) { Comment c = listItr.next(); if (c.line < 0) { throw new BadRequestException(String.format( "negative line number %d not allowed on %s", c.line, path)); } c.message = Strings.emptyToNull(c.message).trim(); if (c.message.isEmpty()) { listItr.remove(); } } if (list.isEmpty()) { mapItr.remove(); } } }</code><technical_language>Switch a Set<String> do contains a loop below. wrap RHS of assignment in Sets.newHashSet(...)</technical_language>

Target:
private void checkComments(RevisionResource revision, Map<String, List<Comment>> in) throws BadRequestException, OrmException { Iterator<Map.Entry<String, List<Comment>>> mapItr = in.entrySet().iterator(); Set<String> filePaths = Sets.newHashSet(changeDataFactory.create( db.get(), revision.getChange()).filePaths( revision.getPatchSet())); while (mapItr.hasNext()) { Map.Entry<String, List<Comment>> ent = mapItr.next(); String path = ent.getKey(); if (!filePaths.contains(path) && !Patch.COMMIT_MSG.equals(path)) { throw new BadRequestException(String.format( "file %s not found in revision %s", path, change.currentPatchSetId())); } List<Comment> list = ent.getValue(); if (list == null) { mapItr.remove(); continue; } Iterator<Comment> listItr = list.iterator(); while (listItr.hasNext()) { Comment c = listItr.next(); if (c.line < 0) { throw new BadRequestException(String.format( "negative line number %d not allowed on %s", c.line, path)); } c.message = Strings.emptyToNull(c.message).trim(); if (c.message.isEmpty()) { listItr.remove(); } } if (list.isEmpty()) { mapItr.remove(); } } }
Source:
<code>protected boolean validate() { VnicProfileValidator validator = createVnicProfileValidator(); return validate(validator.vnicProfileIsSet()) && validate(validator.vnicProfileExists()) && validate(validator.vnicProfileNameNotUsed()) && validate(validator.networkNotChanged()) && validate(validator.networkQosExistsOrNull()) && validate(validator.portMirroringNotChangedIfUsedByVms()) && validate(validator.portMirroringNotSetIfExternalNetwork()) && validator.validateCustomProperties(getReturnValue().getValidationMessages()) && validate(validator.passthroughNotChangedIfUsedByVms()) && validate(validator.passthroughProfileContainsSupportedProperties()) && validate(validator.validNetworkFilterId()) && <START> validate(validator.validNetworkFilterForPassthroughProfile(false)); <END> }</code><technical_language>useDefaultNetworkFilterId is false here</technical_language>

Target:
protected boolean validate() { VnicProfileValidator validator = createVnicProfileValidator(); return validate(validator.vnicProfileIsSet()) && validate(validator.vnicProfileExists()) && validate(validator.vnicProfileNameNotUsed()) && validate(validator.networkNotChanged()) && validate(validator.networkQosExistsOrNull()) && validate(validator.portMirroringNotChangedIfUsedByVms()) && validate(validator.portMirroringNotSetIfExternalNetwork()) && validator.validateCustomProperties(getReturnValue().getValidationMessages()) && validate(validator.passthroughNotChangedIfUsedByVms()) && validate(validator.passthroughProfileContainsSupportedProperties(false)) && validate(validator.validNetworkFilterId()); }
Source:
<code>public void run() { Cluster cluster = wantsRuntimeConfig ? getRuntimeCluster(node) : getUpcomingCluster(node); TreeMap<String, String> properties = new TreeMap<>(); cluster.toProperties(false, true).forEach((k, v) -> properties.put(k.toString(), v.toString())); cluster.toProperties(true, true).forEach((k, v) -> properties.put(k.toString(), v.toString())); TreeMap<String, String> output = new TreeMap<>(); configurations.forEach(configuration -> { properties.forEach((k, v) -> { if (configuration.matchConfigPropertyKey(k)) { output.put(k, v); } }); }); String lines = output.entrySet() .stream() .map(e -> e.getKey() + "=" + e.getValue()) <START> .collect(Collectors.joining(lineSeparator())); <END> if (lines.isEmpty()) { throw new ParameterException("No configuration found for: " + configurations.stream().map(Configuration::toString).collect(Collectors.joining(", "))); } logger.info(lines); }</code><technical_language>TreeMap instead of sorted() api . logic change correct</technical_language>

Target:
public void run() { Cluster cluster = wantsRuntimeConfig ? getRuntimeCluster(node) : getUpcomingCluster(node); Properties properties = new Properties(); properties.putAll(cluster.toProperties(false, true)); properties.putAll(cluster.toProperties(true, true)); String output = properties.entrySet() .stream() .filter(e -> acceptKey(e.getKey().toString())) .map(e -> e.getKey() + "=" + e.getValue()) .sorted() .reduce((result, line) -> result + System.lineSeparator() + line) .orElseThrow(() -> new ParameterException("No configuration found")); logger.info(output); }
Source:
<code>public void testNetworkTypes() { assertTrue(mCm.isNetworkSupported(TYPE_WIFI)); <START> assertTrue(mCm.isNetworkSupported(TYPE_MOBILE)); <END> assertTrue(mCm.isNetworkSupported(TYPE_ETHERNET)); }</code><technical_language>For proper testability, listed in hasService()? ...or passing this test run right kinds of devices</technical_language>

Target:
public void testNetworkTypes() { assertTrue(mCm.isNetworkSupported(TYPE_WIFI)); assertTrue(mCm.isNetworkSupported(TYPE_MOBILE)); assertTrue(mCm.isNetworkSupported(TYPE_MOBILE_MMS)); assertFalse(mCm.isNetworkSupported(TYPE_MOBILE_FOTA)); assertTrue(mCm.isNetworkSupported(TYPE_ETHERNET)); }
Source:
<code>public ArrayList<InstanceInfo> inflateForKey (JSONObject data, String key) { ArrayList<InstanceInfo> instanceInfos = new ArrayList<InstanceInfo>(); JSONArray instances = data.optJSONArray(key); if (instances != null) { for (int i = 0; i < instances.length(); i++) { InstanceInfo instanceInfo = new InstanceInfo(); try { instanceInfo.setData(instances.getJSONObject(i)); instanceInfos.add(instanceInfo); } catch (JSONException e) { <START> e.printStackTrace(); <END> } } } return instanceInfos; }</code><technical_language>I kill e.printStackTrace();</technical_language>

Target:
public ArrayList<InstanceInfo> inflateForKey(JSONObject data, String key) { ArrayList<InstanceInfo> instanceInfos = new ArrayList<InstanceInfo>(); JSONArray instances = data.optJSONArray(key); if (instances != null) { for (int i = 0; i < instances.length(); i++) { InstanceInfo instanceInfo = new InstanceInfo(); try { instanceInfo.setData(instances.getJSONObject(i)); instanceInfos.add(instanceInfo); } catch (JSONException e) { } } } return instanceInfos; }
Source:
<code>public synchronized PublisherSession reconnectSession(String sessionId) throws ServiceNotAuthorizedException, ServiceNotEnabledException { PublisherSession state = sessions.get(sessionId); <START> if (state == null || !state.stopDeleteTimer()) <END> return null; return state; }</code><technical_language>remove session delete timer returns false</technical_language>

Target:
public synchronized PublisherSession reconnectSession(String sessionId) throws ServiceNotAuthorizedException, ServiceNotEnabledException { PublisherSession state = sessions.get(sessionId); if (state == null || !state.cancelDeleteTimer()) return null; return state; }
Source:
<code>public boolean isUeberPool() { <START> return product.getName().equals(Product.ueberProductNameForOwner(owner)); <END> }</code><technical_language>unlikely, product null here</technical_language>

Target:
public boolean isUeberPool() { return product != null && Product.ueberProductNameForOwner(owner).equals(product.getName()); }
Source:
<code>public void click(final int line, final int column, final int modifierKey) { <START> if (!KeyLookupFactory.getDefault().isModifierKey(modifierKey)) { <END> log.error(MessageFormat.format("{0} is not a modifier key.", modifierKey)); return; } log.debug(MessageFormat.format("Clicking on {0} with modifier key {1}", this, modifierKey)); notify(SWT.MouseEnter); notify(SWT.FocusIn); notify(SWT.Activate); int lineAtNextColumn = syncExec(new IntResult() { @Override public Integer run() { return widget.getLineAtOffset(offset(line, column + 1, true)); } }); int navigateToColumn = (line == lineAtNextColumn) ? column + 1 : column; navigateTo(line, navigateToColumn, true); final Point p = getXY(line, column); syncExec(new VoidResult() { @Override public void run() { Point originalCursorLocation = display.getCursorLocation(); Point absolutePoint = widget.toDisplay(p); moveMouse(absolutePoint.x, absolutePoint.y); notifyStyledText(SWT.MouseDown, createMouseEvent(p.x, p.y, 1, SWT.NONE | modifierKey, 1)); notifyStyledText(SWT.MouseUp, createMouseEvent(p.x, p.y, 1, SWT.BUTTON1 | modifierKey, 1)); moveMouse(originalCursorLocation.x, originalCursorLocation.y); } }); log.debug(MessageFormat.format("Clicked on {0} with modifier key {1}", this, modifierKey)); }</code><technical_language>Do allow modifierKey == 0? check if a modifier key if 0? Is chance special handling of this method required in some cases a normal click? fine click(int, int) call this, though</technical_language>

Target:
public void click(final int line, final int column, final int modifierKey) { if (!KeyLookupFactory.getDefault().isModifierKey(modifierKey) && modifierKey != 0) { log.error(MessageFormat.format("{0} is not a modifier key.", modifierKey)); return; } log.debug(MessageFormat.format("Clicking on {0} with modifier key {1}", this, modifierKey)); notify(SWT.MouseEnter); notify(SWT.FocusIn); notify(SWT.Activate); syncExec(new VoidResult() { @Override public void run() { Point originalCursorLocation = display.getCursorLocation(); widget.setTopIndex(line); widget.setHorizontalIndex(column); Point p = getXY(line, column); Point absolutePoint = widget.toDisplay(p); moveMouse(absolutePoint.x, absolutePoint.y); notifyStyledText(SWT.MouseDown, createMouseEvent(p.x, p.y, 1, SWT.NONE | modifierKey, 1)); notifyStyledText(SWT.MouseUp, createMouseEvent(p.x, p.y, 1, SWT.BUTTON1 | modifierKey, 1)); moveMouse(originalCursorLocation.x, originalCursorLocation.y); } }); log.debug(MessageFormat.format("Clicked on {0} with modifier key {1}", this, modifierKey)); }
Source:
<code>public void initialize() { logger.debug("Initializing DigitalSTROM Device handler."); String configdSID = getConfig().get(DigitalSTROMBindingConstants.DEVICE_DSID).toString(); if (!configdSID.isEmpty()) { dSID = configdSID; <START> if (getDssBridgeHandler() == null) { <END> updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.HANDLER_MISSING_ERROR, "Bridge is missig"); } else { bridgeHandlerInitialized(dssBridgeHandler, this.getBridge()); } } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "dSID is missig"); } }</code><technical_language>remove this "if", "else" - set HANDLER_MISSING_ERRORs, this is done framework</technical_language>

Target:
public void initialize() { logger.debug("Initializing DeviceHandler."); if (StringUtils.isNotBlank((String) getConfig().get(DigitalSTROMBindingConstants.DEVICE_DSID))) { dSID = getConfig().get(DigitalSTROMBindingConstants.DEVICE_DSID).toString(); bridgeHandlerInitialized(dssBridgeHandler, this.getBridge()); } else { updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "dSID is missig"); } }
Source:
<code>public void ThrottleOnOverTest() throws Exception { <START> githubApi.stubFor( <END> get(urlEqualTo("/rate_limit")) .inScenario("API Rate Limit Throttle on Over") .whenScenarioStateIs(Scenario.STARTED) .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withHeader("Accept-Encoding", "gzip,deflate") .withBody("{ \"rate\": { \"limit\": 100, \"remaining\": 8, \"reset\": 1 } }")) .willSetStateTo("API Rate Limit Depleted")); githubApi.stubFor( get(urlEqualTo("/rate_limit")) .inScenario("API Rate Limit Throttle on Over") .whenScenarioStateIs("API Rate Limit Depleted") .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withHeader("Accept-Encoding", "gzip,deflate") .withBody("{ \"rate\": { \"limit\": 100, \"remaining\": 100, \"reset\": 1000 } }")) .willSetStateTo("API Rate Limit Refreshed")); githubApi.stubFor( get(urlEqualTo("/rate_limit")) .inScenario("API Rate Limit Throttle on Over") .whenScenarioStateIs("API Rate Limit Refreshed") .willReturn( aResponse() .withHeader("Content-Type", "application/json; charset=utf-8") .withHeader("Accept-Encoding", "gzip,deflate") .withBody("{ \"rate\": { \"limit\": 100, \"remaining\": 99, \"reset\": 1000 } }"))); final Logger logger = Logger.getLogger(getClass().getName()); final LogTaskListener listener = new LogTaskListener(logger, Level.INFO); final ApiRateLimitChecker apiRateLimitChecker = ApiRateLimitChecker.ThrottleOnOver; apiRateLimitChecker.setExpirationWaitMillis(1); apiRateLimitChecker.checkApiRateLimit(listener, github); apiRateLimitChecker.checkApiRateLimit(listener, github); }</code><technical_language>move stubbings independent setup methods reused checkers. method pair of test methods. (This calling checkApiRateLimit a extra times in ThrottleOnOver case check a number of times.)</technical_language>

Target:
public void ThrottleOnOverTest() throws Exception { List<RateLimit> scenarios = new ArrayList<>(); int limit = 5000; int buffer = ApiRateLimitChecker.calculateBuffer(limit); int expectedNumThrottles = 10; for (int i = -10; i <= expectedNumThrottles; i++) { scenarios.add(new RateLimit(limit, buffer - i, soon)); } scenarios.add(new RateLimit(limit, limit, soon)); setupStubs(scenarios); for (int i = 0; i < 11; i++) { ApiRateLimitChecker.ThrottleOnOver.checkApiRateLimit(listener, github); } assertEquals(0, countOfOutputLines(m -> m.matches("[sS]leeping"))); ApiRateLimitChecker.ThrottleOnOver.checkApiRateLimit(listener, github); assertEquals(1, countOfOutputLinesContaining("Sleeping for")); assertEquals(expectedNumThrottles-1, countOfOutputLinesContaining("Still sleeping")); assertEquals(1, countOfOutputLinesContaining("refreshed")); ApiRateLimitChecker.ThrottleOnOver.checkApiRateLimit(listener, github); assertEquals(1, countOfOutputLinesContaining("Sleeping for")); assertEquals(expectedNumThrottles-1, countOfOutputLinesContaining("Still sleeping")); assertEquals(1, countOfOutputLinesContaining("refreshed")); }
Source:
<code>public void testPruningOfDuplicateReporter() { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); createXmlClass(xmlTest, UniqueReporterInjectionSample1.class); createXmlClass(xmlTest, UniqueReporterInjectionSample2.class); TestNG tng = create(xmlSuite); tng.setUseDefaultListeners(false); tng.addListener((ITestNGListener) new ReporterListenerForIssue1227()); tng.run(); <START> Assert.assertTrue(tng.getReporters().size() == 1); <END> }</code><technical_language>Assert.assertEquals(tng.getReporters().size(), 1)</technical_language>

Target:
public void testPruningOfDuplicateReporter() { XmlSuite xmlSuite = createXmlSuite("Suite"); XmlTest xmlTest = createXmlTest(xmlSuite, "Test"); createXmlClass(xmlTest, UniqueReporterInjectionSample1.class); createXmlClass(xmlTest, UniqueReporterInjectionSample2.class); TestNG tng = create(xmlSuite); tng.setUseDefaultListeners(false); tng.addListener((ITestNGListener) new ReporterListenerForIssue1227()); tng.run(); Assert.assertEquals(tng.getReporters().size(),1); Assert.assertEquals(ReporterListenerForIssue1227.counter, 1); }
Source:
<code>public void testChallengeSentWithUnhandledAuthorization() throws Exception { HttpChannel channel = new HttpChannel(new MockConnector(), new HttpConfiguration(), null, null) { @Override public Server getServer() { return null; } @Override protected HttpOutput newHttpOutput() { return new HttpOutput(this) { @Override public void close() @Override public void flush() throws IOException }; } }; Request req = channel.getRequest(); Response res = channel.getResponse(); <START> MetaData.Request metadata = new MetaData.Request(null, HttpURI.build("http://localhost").asImmutable(), null, <END> HttpFields.build().add(HttpHeader.AUTHORIZATION, "Basic asdf")); req.setMetaData(metadata); assertThat(channel.getState().handling(), is(HttpChannelState.Action.DISPATCH)); assertEquals(Authentication.SEND_CONTINUE, _authenticator.validateRequest(req, res, true)); assertEquals(HttpHeader.NEGOTIATE.asString(), res.getHeader(HttpHeader.WWW_AUTHENTICATE.asString())); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, res.getStatus()); }</code><technical_language>Remove asImmutable() this test class</technical_language>

Target:
public void testChallengeSentWithUnhandledAuthorization() throws Exception { HttpChannel channel = new HttpChannel(new MockConnector(), new HttpConfiguration(), null, null) { @Override public Server getServer() { return null; } @Override protected HttpOutput newHttpOutput() { return new HttpOutput(this) { @Override public void close() @Override public void flush() throws IOException }; } }; Request req = channel.getRequest(); Response res = channel.getResponse(); MetaData.Request metadata = new MetaData.Request(null, HttpURI.build("http://localhost"), null, HttpFields.build().add(HttpHeader.AUTHORIZATION, "Basic asdf")); req.setMetaData(metadata); assertThat(channel.getState().handling(), is(HttpChannelState.Action.DISPATCH)); assertEquals(Authentication.SEND_CONTINUE, _authenticator.validateRequest(req, res, true)); assertEquals(HttpHeader.NEGOTIATE.asString(), res.getHeader(HttpHeader.WWW_AUTHENTICATE.asString())); assertEquals(HttpServletResponse.SC_UNAUTHORIZED, res.getStatus()); }
Source:
<code>private IMarkerResolutionGenerator createGenerator(IConfigurationElement element) { IMarkerResolutionGenerator generator = getGenerator(element); if (generator != null && generator != GENERATOR_NOT_STARTED) { return generator; } Bundle bundle = Platform.getBundle(element.getContributor().getName()); if (bundle.getState() == Bundle.ACTIVE) { generator = createGeneratorFromActiveBundle(element); } else { BundleContext bundleContext = bundle.getBundleContext(); if (bundleContext != null) { generator = GENERATOR_NOT_ACTIVE; <START> bundleContext.addBundleListener(new BundleListener() { <END> @Override public void bundleChanged(BundleEvent b) { if (b.getType() == BundleEvent.STARTED && bundle.getState() == Bundle.ACTIVE) { bundleContext.removeBundleListener(this); if (getGenerator(element) == GENERATOR_NOT_ACTIVE) { putGenerator(element, null); } } } }); if (bundle.getState() == Bundle.ACTIVE) { generator = createGeneratorFromActiveBundle(element); } } else { generator = GENERATOR_NOT_STARTED; } } putGenerator(element, generator); return generator; }</code><technical_language>this branch is reachable in corner bundle state == STARTING. informed if state is currently RESOLVED. Is a method add a global bundle listener in a central place</technical_language>

Target:
private IMarkerResolutionGenerator createGenerator(IConfigurationElement element) { IMarkerResolutionGenerator generator = getGenerator(element); if (generator != null && generator != GENERATOR_NOT_STARTED) { return generator; } Bundle bundle = Platform.getBundle(element.getContributor().getName()); if (canLoadExtensionWithoutActivation(bundle)) { generator = createGeneratorFromActiveBundle(element); } else { BundleContext bundleContext = bundle.getBundleContext(); if (bundleContext != null) { generator = GENERATOR_NOT_ACTIVE; bundleContext.addBundleListener(new BundleListener() { @Override public void bundleChanged(BundleEvent b) { if (b.getType() == BundleEvent.STARTED && canLoadExtensionWithoutActivation(bundle)) { bundleContext.removeBundleListener(this); if (getGenerator(element) == GENERATOR_NOT_ACTIVE) { putGenerator(element, null); } } } }); if (canLoadExtensionWithoutActivation(bundle)) { generator = createGeneratorFromActiveBundle(element); } } else { generator = GENERATOR_NOT_STARTED; } } putGenerator(element, generator); return generator; }
Source:
<code>public Map<String, String> getRecipientsForQuestion( FeedbackQuestionAttributes question, String giver, InstructorAttributes instructorGiver, StudentAttributes studentGiver) throws EntityDoesNotExistException { Map<String, String> recipients = new HashMap<String, String>(); FeedbackParticipantType recipientType = question.recipientType; String giverTeam = getTeamNameForUser(giver, instructorGiver, studentGiver); <START> addRecipientsBasedOnRecipientType(question, giver, studentGiver, recipients, recipientType, giverTeam); <END> return recipients; }</code><technical_language>need recipients parameter all, empty map passed in</technical_language>

Target:
public Map<String, String> getRecipientsForQuestion( FeedbackQuestionAttributes question, String giver, InstructorAttributes instructorGiver, StudentAttributes studentGiver) throws EntityDoesNotExistException { FeedbackParticipantType recipientType = question.recipientType; String giverTeam = getTeamNameForUser(giver, instructorGiver, studentGiver); return getRecipientsBasedOnRecipientType(question, giver, studentGiver, recipientType, giverTeam); }
Source:
<code>public void shouldPerformStringSuffixSearch() throws Exception { int label = token.nodeLabel( "Node" ); int prop = token.propertyKey( "prop" ); CapableIndexReference index = schemaRead.index( label, prop ); <START> IndexValueCapability stringCapability = index.value( ValueGroup.TEXT ); <END> try ( NodeValueIndexCursor node = cursors.allocateNodeValueIndexCursor(); PrimitiveLongSet uniqueIds = Primitive.longSet() ) { read.nodeIndexSeek( index, node, null, IndexQuery.stringSuffix( prop, "e" ) ); assertFoundNodesAndValue( node, uniqueIds, stringCapability, strOne, strThree1, strThree2, strThree3 ); } }</code><technical_language>I stringCapability better</technical_language>

Target:
public void shouldPerformStringSuffixSearch() throws Exception { int label = token.nodeLabel( "Node" ); int prop = token.propertyKey( "prop" ); CapableIndexReference index = schemaRead.index( label, prop ); IndexValueCapability stringCapability = index.valueCapability( ValueGroup.TEXT ); try ( NodeValueIndexCursor node = cursors.allocateNodeValueIndexCursor(); PrimitiveLongSet uniqueIds = Primitive.longSet() ) { read.nodeIndexSeek( index, node, IndexOrder.NONE, IndexQuery.stringSuffix( prop, "e" ) ); assertFoundNodesAndValue( node, uniqueIds, stringCapability, strOne, strThree1, strThree2, strThree3 ); } }
Source:
<code>private void loadUnitDataBase(UnitDataBaseType newValue) { UnitDatabase unitDatabase = clientProperties.getUnitDatabase(); String rackoverSettingsEncoded = ""; if (newValue == UnitDataBaseType.RACKOVER) { String rackoverSettings = new Gson().toJson(new RackoversDBSettings(i18n.getUserSpecificLocale())); rackoverSettingsEncoded = Base64.getEncoder().encodeToString(rackoverSettings.getBytes()); } <START> unitsRoot.getEngine().load(newValue == UnitDataBaseType.SPOOKY ? unitDatabase.getSpookiesUrl() : unitDatabase.getRackOversUrl() + rackoverSettingsEncoded); <END> }</code><technical_language>Do concatenate String format String</technical_language>

Target:
private void loadUnitDataBase(UnitDataBaseType newValue) { UnitDatabase unitDatabase = clientProperties.getUnitDatabase(); switch (newValue) { case RACKOVER: String rackoverSettings = new Gson().toJson(new RackoversDBSettings(i18n.getUserSpecificLocale())); String rackoverSettingsEncoded = Base64.getEncoder().encodeToString(rackoverSettings.getBytes()); unitsRoot.getEngine().load(String.format(unitDatabase.getRackOversUrl(), rackoverSettingsEncoded)); break; case SPOOKY: unitsRoot.getEngine().load(unitDatabase.getSpookiesUrl()); break; default: new ProgrammingError("Trying to load unimplemented database type: " + newValue.toString()); } }
Source:
<code>public void can_merge_an_incoming_list_of_forms() { ExportForms forms = new ExportForms(new ArrayList<>(), new HashMap<>(), new HashMap<>()); <START> assertThat(forms.size(), is(0)); <END> int expectedSize = 10; forms.merge(buildFormStatusList(expectedSize)); assertThat(forms.size(), is(expectedSize)); }</code><technical_language>assertEmpty</technical_language>

Target:
public void can_merge_an_incoming_list_of_forms() { ExportForms forms = new ExportForms(new ArrayList<>(), ExportConfiguration.empty(), new HashMap<>(), new HashMap<>()); assertThat(forms.size(), is(0)); int expectedSize = 10; forms.merge(buildFormStatusList(expectedSize)); assertThat(forms.size(), is(expectedSize)); }
Source:
<code>protected boolean canDoAction() { <START> return (!QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), <END> getReturnValue().getCanDoActionMessages())); }</code><technical_language>return of check? IIRC return true if quota is valid, return true for CDA</technical_language>

Target:
protected boolean canDoAction() { return (QuotaHelper.getInstance().checkQuotaValidationForAddEdit(getParameters().getQuota(), getReturnValue().getCanDoActionMessages())); }
Source:
<code>public List<ConnectorTableLayoutResult> getTableLayouts(ConnectorSession session, ConnectorTableHandle table, Constraint<ColumnHandle> constraint, Optional<Set<ColumnHandle>> desiredColumns) { JdbcTableHandle tableHandle = (JdbcTableHandle) table; ConnectorTableLayout layout = new ConnectorTableLayout(new JdbcTableLayoutHandle(tableHandle, constraint.getSummary())); <START> return ImmutableList.of(new ConnectorTableLayoutResult(layout, TupleDomain.all())); <END> }</code><technical_language>is proper? If predicate is pushed down, I expect TupleDomain.none() here</technical_language>

Target:
public List<ConnectorTableLayoutResult> getTableLayouts(ConnectorSession session, ConnectorTableHandle table, Constraint<ColumnHandle> constraint, Optional<Set<ColumnHandle>> desiredColumns) { JdbcTableHandle tableHandle = (JdbcTableHandle) table; ConnectorTableLayout layout = new ConnectorTableLayout(new JdbcTableLayoutHandle(tableHandle, constraint.getSummary())); TupleDomain<ColumnHandle> unenforcedTupleDomain = constraint.getSummary().transform(columnHandle -> { JdbcColumnHandle jdbcColumnHandle = (JdbcColumnHandle) columnHandle; if (isAcceptedType(jdbcColumnHandle.getColumnType())) { return null; } return jdbcColumnHandle; }); return ImmutableList.of(new ConnectorTableLayoutResult(layout, unenforcedTupleDomain)); }
Source:
<code>private void handleEndedTask() { if (getState() != AsyncTaskState.Ended) { setState(AsyncTaskState.Ended); setLastStatusAccessTime(); } <START> if (isZombieTask()) { <END> getParameters().getDbAsyncTask().getTaskParameters().setTaskGroupSuccess(false); ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FAILED); onTaskEndFailure(); } if (isPartiallyCompletedCommandTask()) { getParameters().getDbAsyncTask().getTaskParameters().setTaskGroupSuccess(false); ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FAILED); onTaskEndFailure(); } if (hasTaskEndedSuccessfully()) { ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FINISHED); onTaskEndSuccess(); } else if (hasTaskEndedInFailure()) { ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FAILED); onTaskEndFailure(); } else if (!doesTaskExist()) { ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.UNKNOWN); onTaskDoesNotExist(); } }</code><technical_language>please add condition isZombieTask() if clause in line 233 (as: || isZombieTask()), code is same..lets avoid copy</technical_language>

Target:
private void handleEndedTask() { if (getState() != AsyncTaskState.Ended) { setState(AsyncTaskState.Ended); setLastStatusAccessTime(); } if (isZombieTask() || isPartiallyCompletedCommandTask()) { getParameters().getDbAsyncTask().getTaskParameters().setTaskGroupSuccess(false); ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FAILED); onTaskEndFailure(); } if (hasTaskEndedSuccessfully()) { ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FINISHED); onTaskEndSuccess(); } else if (hasTaskEndedInFailure()) { ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.FAILED); onTaskEndFailure(); } else if (!doesTaskExist()) { ExecutionHandler.endTaskStep(privateParameters.getDbAsyncTask().getStepId(), JobExecutionStatus.UNKNOWN); onTaskDoesNotExist(); } }
Source:
<code>protected void executeVdsIdCommand() { if (_vdsManager == null) { getVDSReturnValue().setSucceeded(false); return; } MigrateBrokerVDSCommand<?> command = new MigrateBrokerVDSCommand<>(getParameters()); command.execute(); VDSReturnValue vdsReturnValue = command.getVDSReturnValue(); final VmDynamic vmDynamic = getVmDynamicDAO().get(getParameters().getVmId()); if (vdsReturnValue.getSucceeded()) { vmDynamic.setStatus(VMStatus.MigratingFrom); vmDynamic.setMigratingToVds(getParameters().getDstVdsId()); vmDynamic.setExitStatus(VmExitStatus.Normal); <START> vmDynamic.setExitMessage(StringUtils.EMPTY); <END> ResourceManager.getInstance().AddAsyncRunningVm(getParameters().getVmId()); getVDSReturnValue().setReturnValue(VMStatus.MigratingFrom); } else { log.error("Failed Vm migration"); getVDSReturnValue().setSucceeded(false); getVDSReturnValue().setReturnValue(vmDynamic.getStatus()); getVDSReturnValue().setVdsError(vdsReturnValue.getVdsError()); getVDSReturnValue().setExceptionString(vdsReturnValue.getExceptionString()); getVDSReturnValue().setExceptionObject(vdsReturnValue.getExceptionObject()); } TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getVmDynamicDAO().update(vmDynamic); return null; } }); }</code><technical_language>i prefer calling InternalSetVmStatus copy logic</technical_language>

Target:
protected void executeVdsIdCommand() { if (_vdsManager == null) { getVDSReturnValue().setSucceeded(false); return; } MigrateBrokerVDSCommand<?> command = new MigrateBrokerVDSCommand<>(getParameters()); command.execute(); VDSReturnValue vdsReturnValue = command.getVDSReturnValue(); final VM vm = getVmDao().get(getParameters().getVmId()); if (vdsReturnValue.getSucceeded()) { ResourceManager.getInstance().InternalSetVmStatus(vm, VMStatus.MigratingFrom); vm.setMigratingToVds(getParameters().getDstVdsId()); ResourceManager.getInstance().AddAsyncRunningVm(getParameters().getVmId()); getVDSReturnValue().setReturnValue(VMStatus.MigratingFrom); } else { log.error("Failed Vm migration"); getVDSReturnValue().setSucceeded(false); getVDSReturnValue().setReturnValue(vm.getStatus()); getVDSReturnValue().setVdsError(vdsReturnValue.getVdsError()); getVDSReturnValue().setExceptionString(vdsReturnValue.getExceptionString()); getVDSReturnValue().setExceptionObject(vdsReturnValue.getExceptionObject()); } TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() { @Override public Void runInTransaction() { getVmDynamicDAO().update(vm.getDynamicData()); return null; } }); }
Source:
<code><START> public Mono<OAuth2AuthorizedClient> clientCredentials( <END> ClientRegistration clientRegistration, Authentication authentication, ServerWebExchange exchange) { OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration); return this.clientCredentialsTokenResponseClient.getTokenResponse(grantRequest) .flatMap(tokenResponse -> clientCredentialsResponse(clientRegistration, authentication, exchange, tokenResponse)); }</code><technical_language>I expose a public API here. do instead of: when(this.oAuth2AuthorizedClientResolver.clientCredentials(any(), any(), any())).thenReturn(Mono.just(newAuthorizedClient)); try this Mock ReactiveOAuth2AccessTokenResponseClient<OAuth2ClientCredentialsGrantRequest> set OAuth2AuthorizedClientResolver.setClientCredentialsTokenResponseClient() spy(oAuth2AuthorizedClientResolver) sense</technical_language>

Target:
Mono<OAuth2AuthorizedClient> clientCredentials( ClientRegistration clientRegistration, Authentication authentication, ServerWebExchange exchange) { OAuth2ClientCredentialsGrantRequest grantRequest = new OAuth2ClientCredentialsGrantRequest(clientRegistration); return this.clientCredentialsTokenResponseClient.getTokenResponse(grantRequest) .flatMap(tokenResponse -> clientCredentialsResponse(clientRegistration, authentication, exchange, tokenResponse)); }
Source:
<code>public void onComplete() { if (inMaybe) { actual.onComplete(); } else { inMaybe = true; s = SubscriptionHelper.CANCELLED; <START> MaybeSource<? extends T> c = other; <END> other = null; c.subscribe(this); } }</code><technical_language>named m</technical_language>

Target:
public void onComplete() { if (inMaybe) { actual.onComplete(); } else { inMaybe = true; s = SubscriptionHelper.CANCELLED; MaybeSource<? extends T> ms = other; other = null; ms.subscribe(this); } }
Source:
<code>public void removeDataBundle(DataBundle dataBundle) { deleteCourses(dataBundle.courses.values()); for (AccountAttributes account : dataBundle.accounts.values()) { if (account.studentProfile == null) { account.studentProfile = new StudentProfileAttributes(); account.studentProfile.googleId = account.googleId; } } accountsDb.deleteAccounts(dataBundle.accounts.values()); for (AdminEmailAttributes email : dataBundle.adminEmails.values()) { AdminEmailAttributes emailInDb = adminEmailsDb.getAdminEmailBySubject(email.subject); if (emailInDb != null) { <START> adminEmailsDb.deleteEntity(emailInDb); <END> } } }</code><technical_language>a guard clause unindent happy path</technical_language>

Target:
public void removeDataBundle(DataBundle dataBundle) { deleteCourses(dataBundle.courses.values()); for (AccountAttributes account : dataBundle.accounts.values()) { if (account.studentProfile == null) { account.studentProfile = new StudentProfileAttributes(); account.studentProfile.googleId = account.googleId; } } accountsDb.deleteAccounts(dataBundle.accounts.values()); for (AdminEmailAttributes email : dataBundle.adminEmails.values()) { AdminEmailAttributes emailInDb = adminEmailsDb.getAdminEmailBySubject(email.subject); if (emailInDb == null) { continue; } adminEmailsDb.deleteEntity(emailInDb); } }
Source:
<code>public void createDocument(String type, int id, String name, String desc, File file) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscriptions.add(mDataManagerDocument .createDocument(type, id, name, desc, getRequestFileBody(file)) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<DocumentRelatedResponse>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); <START> if (e instanceof HttpException) { <END> try { String errorMessage = ((HttpException) e).response().errorBody() .string(); getMvpView().showCreationError(MFErrorParser .parseError(errorMessage) .getErrors().get(0).getDefaultUserMessage()); } catch (Throwable throwable) { RxJavaPlugins.getInstance().getErrorHandler().handleError(e); } } else { getMvpView().showCreationError(e.getLocalizedMessage()); } } @Override public void onNext(DocumentRelatedResponse documentCreationResponse) { getMvpView().showProgressbar(false); getMvpView().showDocumentedCreatedSuccessfully(documentCreationResponse); } })); }</code><technical_language>@tarun0 <LINK_0></technical_language>

Target:
public void createDocument(String type, int id, String name, String desc, File file) { checkViewAttached(); getMvpView().showProgressbar(true); mSubscriptions.add(mDataManagerDocument .createDocument(type, id, name, desc, getRequestFileBody(file)) .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .subscribe(new Subscriber<DocumentRelatedResponse>() { @Override public void onCompleted() { getMvpView().showProgressbar(false); } @Override public void onError(Throwable e) { getMvpView().showProgressbar(false); getMvpView().showCreationError(MFErrorParser.errorMessage(e)); } @Override public void onNext(DocumentRelatedResponse documentCreationResponse) { getMvpView().showProgressbar(false); getMvpView().showDocumentedCreatedSuccessfully(documentCreationResponse); } })); }
Source:
<code>public List<ApiClusterTemplateConfig> getRoleConfigs(String roleType, TemplatePreparationObject source) { String adminGroup = virtualGroupService.getVirtualGroup(source.getVirtualGroupRequest(), UmsRight.RANGER_ADMIN.getRight()); <START> if (CloudPlatform.AZURE.equals(source.getCloudPlatform()) && source.getGeneralClusterConfigs().isEnableRangerRaz()) { <END> String servicePrincipals = getServicePrincipalsString(source); return List.of( config(ROLE_SAFETY_VALVE, ConfigUtils.getSafetyValveProperty(RANGER_USERSYNC_UNIX_BACKEND, "nss")), config(ROLE_ASSIGNMENT_RULES, "&ROLE_SYS_ADMIN:g:" + adminGroup), config(RANGER_USERSYNC_AZURE_MAPPING, servicePrincipals)); } else { return List.of( config(ROLE_SAFETY_VALVE, ConfigUtils.getSafetyValveProperty(RANGER_USERSYNC_UNIX_BACKEND, "nss")), config(ROLE_ASSIGNMENT_RULES, "&ROLE_SYS_ADMIN:g:" + adminGroup)); } }</code><technical_language>I mentioned, want do this if accountId necessary entitlement (CDP_CLOUD_IDENTITY_MAPPING). add a check for that. EntitlementService.cloudIdentityMappingEnabled do it</technical_language>

Target:
public List<ApiClusterTemplateConfig> getRoleConfigs(String roleType, TemplatePreparationObject source) { String adminGroup = virtualGroupService.getVirtualGroup(source.getVirtualGroupRequest(), UmsRight.RANGER_ADMIN.getRight()); if (CloudPlatform.AZURE.equals(source.getCloudPlatform()) && source.getGeneralClusterConfigs().isEnableRangerRaz() && source.getServicePrincipals() != null) { String servicePrincipals = getServicePrincipalsString(source); return List.of( config(ROLE_SAFETY_VALVE, ConfigUtils.getSafetyValveProperty(RANGER_USERSYNC_UNIX_BACKEND, "nss")), config(ROLE_ASSIGNMENT_RULES, "&ROLE_SYS_ADMIN:g:" + adminGroup), config(RANGER_USERSYNC_AZURE_MAPPING, servicePrincipals)); } else { return List.of( config(ROLE_SAFETY_VALVE, ConfigUtils.getSafetyValveProperty(RANGER_USERSYNC_UNIX_BACKEND, "nss")), config(ROLE_ASSIGNMENT_RULES, "&ROLE_SYS_ADMIN:g:" + adminGroup)); } }
Source:
<code>private RequestTemplate addQueryMapQueryParameters(Object[] argv, RequestTemplate mutable) { <START> for (int currQueryMapIndex : metadata.queryMapIndices()) { <END> Object value = argv[currQueryMapIndex]; if (value instanceof Map) { Map<String, Object> currQueryMap = (Map<String, Object>) value; for (Entry<String, Object> currEntry : currQueryMap.entrySet()) { Collection<String> values = new ArrayList<String>(); Object currValue = currEntry.getValue(); if (currValue instanceof Iterable<?>) { Iterator<?> iter = ((Iterable<?>) currValue).iterator(); while (iter.hasNext()) { values.add(String.valueOf(iter.next())); } } else { values.add(String.valueOf(currValue)); } mutable.query(currEntry.getKey(), values); } } } return mutable; }</code><technical_language>single index allow early exit.. ex. if (metadata.queryMapIndex == null) return</technical_language>

Target:
private RequestTemplate addQueryMapQueryParameters(Object[] argv, RequestTemplate mutable) { Map<Object, Object> queryMap = (Map<Object, Object>) argv[metadata.queryMapIndex()]; for (Entry<Object, Object> currEntry : queryMap.entrySet()) { checkState(currEntry.getKey().getClass() == String.class, "QueryMap key must be a String: %s", currEntry.getKey()); Collection<String> values = new ArrayList<String>(); Object currValue = currEntry.getValue(); if (currValue instanceof Iterable<?>) { Iterator<?> iter = ((Iterable<?>) currValue).iterator(); while (iter.hasNext()) { Object nextObject = iter.next(); values.add(nextObject == null ? null : nextObject.toString()); } } else { values.add(currValue == null ? null : currValue.toString()); } mutable.query((String) currEntry.getKey(), values); } return mutable; }
Source:
<code><START> public CloseableLiquibase(String changeLogFile, ResourceAccessor resourceAccessor, Database database, ManagedDataSource dataSource) throws LiquibaseException, SQLException { <END> super(changeLogFile, resourceAccessor, database); this.dataSource = dataSource; }</code><technical_language>a pity change public API, I guess reasonable in this case. hope folks wrote custom migrations commands</technical_language>

Target:
CloseableLiquibase( String changeLogFile, ResourceAccessor resourceAccessor, Database database, ManagedDataSource dataSource ) throws LiquibaseException, SQLException { super(changeLogFile, resourceAccessor, database); this.dataSource = dataSource; }
Source:
<code>public boolean submit(final RequestContext requestContext, final Credential credential) { try { final AcceptableUsagePolicyProperties.Jdbc jdbc = properties.getJdbc(); String aupColumnName = properties.getAupAttributeName(); if (StringUtils.isNotBlank(jdbc.getAupColumn())) { aupColumnName = jdbc.getAupColumn(); } final String sql = String.format(jdbc.getSqlUpdateAUP(), jdbc.getTableName(), aupColumnName, jdbc.getPrincipalIdColumn()); <START> String principalId = credential.getId(); <END> if (StringUtils.isNotBlank(jdbc.getPrincipalIdAttribute())) { @NonNull final Principal principal = WebUtils.getAuthentication(requestContext).getPrincipal(); final String pIdAttribName = jdbc.getPrincipalIdAttribute(); if (principal.getAttributes().containsKey(pIdAttribName)) { final Object pIdAttribValue = principal.getAttributes().get(pIdAttribName); if (pIdAttribValue instanceof String) { principalId = pIdAttribValue.toString(); } else { LOGGER.warn("Principal attribute was found, but its value is not a String", pIdAttribName, pIdAttribValue); } } else { LOGGER.warn("Principal attribute cannot be found. Falling back to principal ID", pIdAttribName); } } LOGGER.debug("Executing update query for principal [{}]", sql, principalId); return this.jdbcTemplate.update(sql, principalId) > 0; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return false; }</code><technical_language>Please refactor logic of determining principal-id a separate method, possibly a protected scope</technical_language>

Target:
public boolean submit(final RequestContext requestContext, final Credential credential) { try { final AcceptableUsagePolicyProperties.Jdbc jdbc = properties.getJdbc(); String aupColumnName = properties.getAupAttributeName(); if (StringUtils.isNotBlank(jdbc.getAupColumn())) { aupColumnName = jdbc.getAupColumn(); } final String sql = String.format(jdbc.getSqlUpdateAUP(), jdbc.getTableName(), aupColumnName, jdbc.getPrincipalIdColumn()); final String principalId = determinePrincipalId(requestContext, credential); LOGGER.debug("Executing update query for principal [{}]", sql, principalId); return this.jdbcTemplate.update(sql, principalId) > 0; } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return false; }
Source:
<code>public Predicate<ChangeData> reviewer(String who) throws QueryParseException, OrmException { if ("self".equals(who)) { if (currentUser instanceof IdentifiedUser) { return new ReviewerPredicate( args.dbProvider, ((IdentifiedUser) currentUser).getAccountId()); } else { throw error("reviewer:self not valid for caller"); } <START> } <END> Set<Account.Id> m = args.accountResolver.findAll(who); if (m.isEmpty()) { throw error("User " + who + " not found"); } else if (m.size() == 1) { Account.Id id = m.iterator().next(); return new ReviewerPredicate(args.dbProvider, id); } else { List<ReviewerPredicate> p = new ArrayList<ReviewerPredicate>(m.size()); for (Account.Id id : m) { p.add(new ReviewerPredicate(args.dbProvider, id)); } return Predicate.or(p); } }</code><technical_language>a lot of redundant new setup code in this patch, I suggest consolidating some of it</technical_language>

Target:
public Predicate<ChangeData> reviewer(String who) throws QueryParseException, OrmException { Set<Account.Id> m = parseAccount(who); List<ReviewerPredicate> p = Lists.newArrayListWithCapacity(m.size()); for (Account.Id id : m) { p.add(new ReviewerPredicate(args.dbProvider, id)); } return Predicate.or(p); }
Source:
<code>private Optional<KieServerConnectionInfo> get(String confType, BiFunction<String, KieServerConfigurationKey, Optional<String>> propertyProvider) { Optional<String> url = propertyProvider.apply(confType, KieServerConfigurationKey.LOCATION); Optional<String> user = propertyProvider.apply(confType, KieServerConfigurationKey.USER); Optional<String> password = propertyProvider.apply(confType, KieServerConfigurationKey.PASSWORD); Optional<String> token = propertyProvider.apply(confType, KieServerConfigurationKey.TOKEN); if (!url.isPresent() && !user.isPresent() && <START> !password.isPresent() && <END> !token.isPresent()) { return Optional.empty(); } return Optional.of(new KieServerConnectionInfo(url, user, password, token)); }</code><technical_language>Consider creating a method checks if 1...N optionals present, like: private static boolean allPresent(final Optional<String> ... optionals) { return Stream.of(optionals).allMatch(Optional::isPresent); } Then, this method lines 97 143 shorter</technical_language>

Target:
private Optional<KieServerConnectionInfo> get(String confType, BiFunction<String, KieServerConfigurationKey, Optional<String>> propertyProvider) { Optional<String> url = propertyProvider.apply(confType, KieServerConfigurationKey.LOCATION); Optional<String> user = propertyProvider.apply(confType, KieServerConfigurationKey.USER); Optional<String> password = propertyProvider.apply(confType, KieServerConfigurationKey.PASSWORD); Optional<String> token = propertyProvider.apply(confType, KieServerConfigurationKey.TOKEN); Optional<String> replaceQueryOp = propertyProvider.apply(confType, KieServerConfigurationKey.REPLACE_QUERY); boolean noPropertyFound = Stream.of(url, user, password, token, replaceQueryOp) .noneMatch(Optional::isPresent); if (noPropertyFound) { return Optional.empty(); } boolean replaceQuery = replaceQueryOp.isPresent() && Boolean.TRUE.toString().equalsIgnoreCase(replaceQueryOp.get()); return Optional.of(new KieServerConnectionInfo(url, user, password, token, replaceQuery)); }