auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public org.json.simple.JSONObject getMetadataJson(LayerDescriptor layerDescriptor) { <END> Object obj = null; String wmsUrl = null; try { wmsUrl = getWmsUrl(layerDescriptor, null); } catch (Exception e) { LOGGER.log(Level.SEVERE, String.format("Error retreiving getWmsUrl: '%s'", e.getStackTrace())); e.printStackTrace(); } String metadataUrl = String.format("%s?service=WMS&version=1.3.0&request=GetMetadata&item=layerDetails&layerName=%s", wmsUrl, layerDescriptor.getVariableName() ); JSONParser parser = new JSONParser(); try { obj = parser.parse(readUrl(metadataUrl)); } catch (Exception e) { LOGGER.log(Level.SEVERE, String.format("Error retreiving metadataUrl: '%s'", e.getMessage())); } return (JSONObject) obj; }</code><technical_language>JSONObject type need fully qualified here</technical_language>

Target:
public JSONObject getMetadataJson(LayerDescriptor layerDescriptor) { String wmsUrl; try { wmsUrl = getWmsUrl(layerDescriptor, null); } catch (Exception e) { LOGGER.log(Level.SEVERE, String.format("Error retreiving getWmsUrl: '%s'", e.getStackTrace())); e.printStackTrace(); return null; } String metadataUrl = String.format("%s?service=WMS&version=1.3.0&request=GetMetadata&item=layerDetails&layerName=%s", wmsUrl, layerDescriptor.getNetCDFVariableName() ); JSONParser parser = new JSONParser(); try { return (JSONObject) parser.parse(readUrl(metadataUrl)); } catch (Exception e) { LOGGER.log(Level.SEVERE, String.format("Error retreiving metadataUrl: '%s'", e.getMessage())); return null; } }
Source:
<code>public void onClick(View v) { AddUserBrickFragment addUserBrickFragment = AddUserBrickFragment.newInstance(); String tag = AddUserBrickFragment.ADD_USER_BRICK_FRAGMENT_TAG; <START> getFragmentManager().beginTransaction() <END> .add(R.id.fragment_container, addUserBrickFragment, tag) .addToBackStack(null) .commit(); }</code><technical_language>Please a null-ptr check</technical_language>

Target:
public void onClick(View v) { AddUserBrickFragment addUserBrickFragment = AddUserBrickFragment.newInstance(); String tag = AddUserBrickFragment.ADD_USER_BRICK_FRAGMENT_TAG; FragmentManager fragmentManager = getFragmentManager(); if (fragmentManager != null) { getFragmentManager().beginTransaction() .add(R.id.fragment_container, addUserBrickFragment, tag) .addToBackStack(null) .commit(); } }
Source:
<code>public void testLegacyUnnestArrayRows() { <START> QueryAssertions assertions = new QueryAssertions(testSessionBuilder().build(), new FeaturesConfig().setLegacyUnnestArrayRows(true)); <END> assertions.assertQuery( "SELECT * FROM UNNEST(ARRAY[ROW(1, 1.1), ROW(3, 3.3)], ARRAY[ROW('a', true), ROW('b', false)])", "VALUES ((1, 1.1), ('a', true)), ((3, 3.3), ('b', false))"); }</code><technical_language>This needs closed: java try (QueryAssertions queryAssertions = new QueryAssertions(...)) {</technical_language>

Target:
public void testLegacyUnnestArrayRows() { try (QueryAssertions assertions = new QueryAssertions(testSessionBuilder().setSystemProperty(LEGACY_UNNEST, "true").build())) { assertions.assertQuery( "SELECT * FROM UNNEST(ARRAY[ROW(1, 1.1), ROW(3, 3.3)], ARRAY[ROW('a', true), ROW('b', false)])", "VALUES ((1, 1.1), ('a', true)), ((3, 3.3), ('b', false))"); } }
Source:
<code>public void shouldThrowExceptionJsonUtils() throws Exception { Map<String, String> params = new HashMap<>(); UUID uuid = UUID.randomUUID(); params.put("uuid", uuid.toString()); String json = "not json"; InputStream inputStream = new ByteArrayInputStream(json.getBytes()); when(rapidProHttpClient.executeGet("/contacts", MediaFormat.JSON, params)).thenReturn(inputStream); <START> Contact fromWebservice = contactWebService.getContactByUUID(uuid); <END> }</code><technical_language>variable is pointless</technical_language>

Target:
public void shouldThrowExceptionJsonUtils() throws Exception { Map<String, String> params = new HashMap<>(); UUID uuid = UUID.randomUUID(); params.put("uuid", uuid.toString()); String json = "not json"; InputStream inputStream = new ByteArrayInputStream(json.getBytes()); when(rapidProHttpClient.executeGet("/contacts", MediaFormat.JSON, params)).thenReturn(inputStream); contactWebService.getContactByUUID(uuid); }
Source:
<code>public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } checkValidEncryptionParameters(); HttpPipeline pipeline = null; if (httpPipeline != null) { List<HttpPipelinePolicy> policies = new ArrayList<>(); policies.add(new BlobDecryptionPolicy(keyWrapper, keyResolver)); <START> for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { <END> HttpPipelinePolicy currPolicy = httpPipeline.getPolicy(i); policies.add(currPolicy); } pipeline = new HttpPipelineBuilder() .httpClient(httpPipeline.getHttpClient()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } this.httpPipeline = pipeline; return this; }</code><technical_language>check ensure present? I suppose matter remove encryption metadata, double decrypt, safer if check</technical_language>

Target:
public EncryptedBlobClientBuilder pipeline(HttpPipeline httpPipeline) { if (this.httpPipeline != null && httpPipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } checkValidEncryptionParameters(); HttpPipeline pipeline = null; if (httpPipeline != null) { List<HttpPipelinePolicy> policies = new ArrayList<>(); boolean decryptionPolicyPresent = false; for (int i = 0; i < httpPipeline.getPolicyCount(); i++) { HttpPipelinePolicy currPolicy = httpPipeline.getPolicy(i); decryptionPolicyPresent |= currPolicy instanceof BlobDecryptionPolicy; policies.add(currPolicy); } if (!decryptionPolicyPresent) { policies.add(0, new BlobDecryptionPolicy(keyWrapper, keyResolver)); } pipeline = new HttpPipelineBuilder() .httpClient(httpPipeline.getHttpClient()) .policies(policies.toArray(new HttpPipelinePolicy[0])) .build(); } this.httpPipeline = pipeline; return this; }
Source:
<code>public void testLabelCDataEnd() throws Exception { StyleBuilder sb = new StyleBuilder(); TextSymbolizer ts = sb.createTextSymbolizer(); ts.setLabel(ff.function("strConcat", ff.literal("abc "), ff.property("myProperty"))); StyledLayerDescriptor sld = buildSLDAroundSymbolizer(ts); String xml = transformer.transform(sld); assertTrue(xml.contains("<sld:Label>")); assertTrue(xml.contains("<![CDATA[abc ]]>")); assertTrue(xml.contains("<ogc:PropertyName>myProperty</ogc:PropertyName>")); assertTrue(xml.contains("</sld:Label>")); assertTrue(xml.indexOf("<sld:Label>") < xml.indexOf("<![CDATA[abc ]]>")); assertTrue(xml.indexOf("<![CDATA[abc ]]>") < xml.indexOf("<ogc:PropertyName>myProperty</ogc:PropertyName>")); <START> assertTrue(xml.indexOf("<ogc:PropertyName>myProperty</ogc:PropertyName>") < xml.indexOf("</sld:Label>")); <END> }</code><technical_language>is do - nice work :) I guess if returned -1 correctly fail :)</technical_language>

Target:
public void testLabelCDataEnd() throws Exception { StyleBuilder sb = new StyleBuilder(); TextSymbolizer ts = sb.createTextSymbolizer(); ts.setLabel(ff.function("strConcat", ff.literal("abc "), ff.property("myProperty"))); StyledLayerDescriptor sld = buildSLDAroundSymbolizer(ts); String xml = transformer.transform(sld); Document doc = buildTestDocument(xml); assertXpathEvaluatesTo("abc", "normalize-space( assertXpathEvaluatesTo("myProperty", " assertTrue(xml.contains("<![CDATA[abc ]]>")); }
Source:
<code>public StrongholdConfessor(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{B}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.CLERIC); this.power = new MageInt(1); this.toughness = new MageInt(1); this.addAbility(new MenaceAbility()); this.addAbility(new KickerAbility("{3}")); this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(2)), KickedCondition.instance, "If Stronghold Confessor was kicked, it enters the battlefield with two +1/+1 counters on it.", "")); <START> } <END></code><technical_language>{this} referring card names in text</technical_language>

Target:
public StrongholdConfessor(UUID ownerId, CardSetInfo setInfo) { super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{B}"); this.subtype.add(SubType.HUMAN); this.subtype.add(SubType.CLERIC); this.power = new MageInt(1); this.toughness = new MageInt(1); this.addAbility(new MenaceAbility()); this.addAbility(new KickerAbility("{3}")); this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.P1P1.createInstance(2)), KickedCondition.instance, "If {this} was kicked, it enters the battlefield with two +1/+1 counters on it.", "")); }
Source:
<code><START> private void addAndDismiss(final ReadingList readingList, final List<PageTitle> titles) { <END> if ((readingList.pages().size() + titles.size()) > SiteInfoClient.getMaxPagesPerReadingList()) { String message = getString(R.string.reading_list_article_limit_message, readingList.title(), SiteInfoClient.getMaxPagesPerReadingList()); FeedbackUtil.makeSnackbar(getActivity(), message, FeedbackUtil.LENGTH_DEFAULT).show(); dismiss(); return; } if (titles.size() == 1) { addAndDismiss(readingList, titles.get(0)); return; } execute(readingList, titles); }</code><technical_language>Do need a separate function for this? a single addAndDismiss function takes a list of Titles, give a singleton list in case of a single title</technical_language>

Target:
private void addAndDismiss(final ReadingList readingList, final List<PageTitle> titles) { if ((readingList.pages().size() + titles.size()) > SiteInfoClient.getMaxPagesPerReadingList()) { String message = getString(R.string.reading_list_article_limit_message, readingList.title(), SiteInfoClient.getMaxPagesPerReadingList()); FeedbackUtil.makeSnackbar(getActivity(), message, FeedbackUtil.LENGTH_DEFAULT).show(); dismiss(); return; } run(readingList, titles); }
Source:
<code>public void changeScene() { Pane <START> root2 = <END> new Pane(); Scene scene2 = new Scene(root2, 800, 600); root2.setPrefSize(Constants.ScreenHeight, Constants.ScreenWidht); root2.getChildren().addAll(Constants.imageView, gameMenu); scene2.setRoot(root2); Constants.stage.setScene(scene2); step=1; }</code><technical_language>bad name</technical_language>

Target:
public void changeScene() { Pane rootMenu = new Pane(); Scene sceneMenu = new Scene(rootMenu, SCREEN_HEIGHT, SCREEN_WIDTH); rootMenu.setPrefSize(SCREEN_HEIGHT, SCREEN_WIDTH); rootMenu.getChildren().addAll(GlobalVariables.imageView, gameMenu); sceneMenu.setRoot(rootMenu); GlobalVariables.stage.setScene(sceneMenu); step = 1; }
Source:
<code>public void await() throws InfrastructureException { try { result.get(resultTimeoutSeconds, TimeUnit.SECONDS); } catch (InterruptedException e) { <START> Thread.currentThread().interrupt(); <END> throw new InfrastructureException("Machine " + machineName + " start is interrupted"); } catch (TimeoutException e) { throw new InfrastructureException("Servers readiness check of machine " + machineName + " timed out"); } catch (ExecutionException e) { try { throw e.getCause(); } catch (InfrastructureException rethrow) { throw rethrow; } catch (Throwable thr) { throw new InternalInfrastructureException( "Machine " + machineName + " servers readiness check failed. Error: " + thr.getMessage(), thr); } } }</code><technical_language>considered propagating InterruptedException DockerRuntimeInfrastructure decides do it? i simplifies interruption policy logic related interruption processing "plate"</technical_language>

Target:
public void await() throws InfrastructureException, InterruptedException { try { result.get(resultTimeoutSeconds, TimeUnit.SECONDS); } catch (TimeoutException e) { throw new InfrastructureException("Servers readiness check of machine " + machineName + " timed out"); } catch (ExecutionException e) { try { throw e.getCause(); } catch (InfrastructureException rethrow) { throw rethrow; } catch (Throwable thr) { throw new InternalInfrastructureException( "Machine " + machineName + " servers readiness check failed. Error: " + thr.getMessage(), thr); } } }
Source:
<code>protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { TransactionalEditingDomain domain = (TransactionalEditingDomain) EMFHelper.resolveEditingDomain(targetEditPart); CreateElementRequest createElementRequest = new CreateElementRequest(domain, activity, typeToCreate); <START> ICommand slotCreationCommand; <END> slotCreationCommand = new CreateElementCommand(createElementRequest); slotCreationCommand.execute(new NullProgressMonitor(), null); CommandResult commandResult = slotCreationCommand.getCommandResult(); if (commandResult != null) { if (!commandResult.getStatus().isOK()) { return commandResult; } } T newCallBehaviorAction = getNewEObject(commandResult); if (newCallBehaviorAction == null) { newCallBehaviorAction = getNewEObject(createElementRequest); } if (newCallBehaviorAction != null) { updateNewlyCreatedEObjectWithEObjectDragged(newCallBehaviorAction, behavior); } else { return CommandResult.newErrorCommandResult("Could not create the calloperation for operation"); } return CommandResult.newOKCommandResult(); }</code><technical_language>change name of command</technical_language>

Target:
protected CommandResult doExecuteWithResult(IProgressMonitor progressMonitor, IAdaptable info) throws ExecutionException { TransactionalEditingDomain domain = (TransactionalEditingDomain) EMFHelper.resolveEditingDomain(targetEditPart); CreateElementRequest createElementRequest = new CreateElementRequest(domain, targetElementDiagram, typeToCreate); ICommand creationElementCommand; creationElementCommand = new CreateElementCommand(createElementRequest); creationElementCommand.execute(new NullProgressMonitor(), null); CommandResult commandResult = creationElementCommand.getCommandResult(); if (commandResult != null) { if (!commandResult.getStatus().isOK()) { return commandResult; } } T newCallBehaviorAction = getNewEObject(commandResult); if (newCallBehaviorAction == null) { newCallBehaviorAction = getNewEObject(createElementRequest); } if (newCallBehaviorAction != null) { updateNewlyCreatedEObjectWithEObjectDragged(newCallBehaviorAction, sourceElement); } else { return CommandResult.newErrorCommandResult("Could not create the calloperation for operation"); } return CommandResult.newOKCommandResult(); }
Source:
<code>public StaxParser(XmlStreamHandler streamHandler) { this.streamHandler = streamHandler; <START> WstxInputFactory xmlFactory = (WstxInputFactory) XMLInputFactory.newInstance(); <END> xmlFactory.configureForLowMemUsage(); xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); inf = new SMInputFactory(xmlFactory); }</code><technical_language>@ivandalbosco Is this a safe cast</technical_language>

Target:
public StaxParser(XmlStreamHandler streamHandler) { this.streamHandler = streamHandler; WstxInputFactory xmlFactory = (WstxInputFactory) XMLInputFactory.newInstance(); xmlFactory.configureForLowMemUsage(); xmlFactory.getConfig().setUndeclaredEntityResolver(new UndeclaredEntitiesXMLResolver()); xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, false); xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, false); inf = new SMInputFactory(xmlFactory); }
Source:
<code>public void getRadiologyReports_shouldReturnAEmptyListIfNoRadiologyReportMatchesTheCriteria() throws Exception { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd"); RadiologyReportSearchCriteria radiologyReportSearchCriteria = new RadiologyReportSearchCriteria.Builder().setFromDate(format.parse("2016-04-25")) .setToDate(format.parse("2016-05-27")) .build(); List<RadiologyReport> radiologyReports = radiologyReportService.getRadiologyReports(radiologyReportSearchCriteria); <START> assertThat(radiologyReports.size(), is(0)); <END> }</code><technical_language>@Schwasrz94 assertTrue(radiologyReports.isEmpty())</technical_language>

Target:
public void getRadiologyReports_shouldReturnAEmptyListIfNoRadiologyReportMatchesTheCriteria() throws Exception { final DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); RadiologyReportSearchCriteria radiologyReportSearchCriteria = new RadiologyReportSearchCriteria.Builder().setFromDate(format.parse("2016-04-25")) .setToDate(format.parse("2016-05-27")) .build(); List<RadiologyReport> radiologyReports = radiologyReportService.getRadiologyReports(radiologyReportSearchCriteria); assertThat(radiologyReports.size(), is(0)); }
Source:
<code>private void assertDeploymentExists(String deploymentName, boolean shouldExist) throws IOException, OperationException { <START> Assert.assertEquals("Deployment exists", shouldExist, ops.exists(Address.of("deployment", deploymentName))); <END> }</code><technical_language>assert message sense for shouldExist == true</technical_language>

Target:
private void assertDeploymentExists(String deploymentName, boolean shouldExist) throws IOException, OperationException { boolean exists = ops.exists(Address.deployment(deploymentName)); if (shouldExist) { Assert.assertTrue("Deployment should exist!", exists); } else { Assert.assertFalse("Deployment shouldn't exist!", exists); } }
Source:
<code>private ServerErrorCode handleAddStoreRequest(PartitionId partitionId) { ServerErrorCode errorCode = ServerErrorCode.No_Error; ReplicaId replicaToAdd = clusterMap.getNewReplica(partitionId.toPathString(), currentNode); if (replicaToAdd != null) { if (storeManager.addBlobStore(replicaToAdd)) { if (((ReplicationManager) replicationEngine).addReplica(replicaToAdd)) { if (statsManager.addReplica(replicaToAdd)) { logger.info("{} is successfully added into storage manager, replication manager and stats manager.", partitionId); localPartitionToReplicaMap.put(partitionId, replicaToAdd); } else { errorCode = ServerErrorCode.Unknown_Error; logger.debug("Failed to add into stats manager", partitionId); } } else { <START> errorCode = ServerErrorCode.Unknown_Error; <END> logger.debug("Failed to add into replication manager", partitionId); } } else { errorCode = ServerErrorCode.Unknown_Error; logger.debug("Failed to add into storage manager", partitionId); } } else { errorCode = ServerErrorCode.Replica_Unavailable; logger.error("No new replica found for in cluster map", partitionId); } return errorCode; }</code><technical_language>For handle* methods, more readable intersperse method returns a ton of nested layers of indentation. e.g. java if (!success1) { return errorCode1; } if (!success2) { return errorCode2; } ... return No_Error</technical_language>

Target:
private ServerErrorCode handleAddStoreRequest(PartitionId partitionId) { ServerErrorCode errorCode = ServerErrorCode.No_Error; ReplicaId replicaToAdd = clusterMap.getBootstrapReplica(partitionId.toPathString(), currentNode); if (replicaToAdd == null) { logger.error("No new replica found for in cluster map", partitionId); return ServerErrorCode.Replica_Unavailable; } if (!storeManager.addBlobStore(replicaToAdd)) { logger.debug("Failed to add into storage manager", partitionId); return ServerErrorCode.Unknown_Error; } if (!((ReplicationManager) replicationEngine).addReplica(replicaToAdd)) { logger.debug("Failed to add into replication manager", partitionId); return ServerErrorCode.Unknown_Error; } if (statsManager.addReplica(replicaToAdd)) { logger.info("{} is successfully added into storage manager, replication manager and stats manager.", partitionId); localPartitionToReplicaMap.put(partitionId, replicaToAdd); } else { errorCode = ServerErrorCode.Unknown_Error; logger.debug("Failed to add into stats manager", partitionId); } return errorCode; }
Source:
<code>public void beforeTest() throws Exception { try { waitForSystemReady(); List<String> featurePolicies = new ArrayList<>(); featurePolicies.addAll(Arrays.asList(getDefaultRequiredApps())); featurePolicies.addAll(FEATURES_TO_FILTER); featurePolicies.replaceAll( featureName -> featureName + "=\"<LINK_0>\""); List<String> servicePolicies = new ArrayList<>(SERVICES_TO_FILTER); servicePolicies.addAll(SERVICES_TO_FILTER); servicePolicies.replaceAll( serviceName -> <START> serviceName <END> + "=\"<LINK_0>\""); String adminConfigPolicyPid = "org.codice.ddf.admin.config.policy.AdminConfigPolicy"; Configuration config = getAdminConfig().getConfiguration(adminConfigPolicyPid); config.setBundleLocation( "mvn:ddf.admin.core/admin-core-configpolicy/" + System.getProperty("ddf.version")); Dictionary properties = new Hashtable<>(); properties.put("featurePolicies", featurePolicies.toArray(new String[0])); properties.put("servicePolicies", servicePolicies.toArray(new String[0])); configureService(adminConfigPolicyPid, properties, getAdminConfig()); } catch (Exception e) { LoggingUtils.failWithThrowableStacktrace(e, "Failed in @BeforeExam: "); } }</code><technical_language>move this a method configures this service for MetacardValidityFilterPlugin</technical_language>

Target:
public void beforeTest() throws Exception { try { waitForSystemReady(); List<String> featurePolicies = new ArrayList<>(); featurePolicies.addAll(Arrays.asList(getDefaultRequiredApps())); featurePolicies.addAll(FEATURES_TO_FILTER); featurePolicies.replaceAll( featureName -> featureName + "=\"<LINK_0>\""); List<String> servicePolicies = new ArrayList<>(SERVICES_TO_FILTER); servicePolicies.replaceAll( serviceName -> serviceName + "=\"<LINK_0>\""); String adminConfigPolicyPid = "org.codice.ddf.admin.config.policy.AdminConfigPolicy"; Configuration config = getAdminConfig().getConfiguration(adminConfigPolicyPid); config.setBundleLocation( "mvn:ddf.admin.core/admin-core-configpolicy/" + System.getProperty("ddf.version")); configureAdminConfigPolicy(featurePolicies, servicePolicies, getAdminConfig()); } catch (Exception e) { LoggingUtils.failWithThrowableStacktrace(e, "Failed in @BeforeExam: "); } }
Source:
<code><START> protected void authenticateWithSSO(HttpServletRequest req, HttpServletResponse resp) throws ServletException { <END> try { req.setAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY, schemes); HttpSession session = req.getSession(false); Deque<AuthenticationProfile> stack = null; if (session != null) { stack = (Deque<AuthenticationProfile>) session.getAttribute(STACK_ATTR); } if (stack == null) { stack = new ArrayDeque<>(); stack.addAll(profiles); } String username = doAuth(req, resp); if (StringUtils.isNotEmpty(username)) { Map<String, Object> response = SSOOAuthServiceUtils.loginOnBehalf(req, resp, username, scope); FiltersHelper.isStatusOk(response); createUserSession(req, FiltersHelper.getPayloadForToken(req, resp, (String) response.get("access_token"))); } } catch (Exception e) { log.error(e.getMessage()); log.debug("External Authentication with SSO failed", e); } }</code><technical_language>please refer current nego filter interact remote. auth is established interact sso</technical_language>

Target:
protected void authenticateWithSSO(HttpServletRequest req, HttpServletResponse resp) throws ServletException { try { req.setAttribute(FiltersHelper.Constants.REQUEST_SCHEMES_KEY, schemes); HttpSession session = req.getSession(false); Deque<AuthenticationProfile> stack = null; if (session != null) { stack = (Deque<AuthenticationProfile>) session.getAttribute(STACK_ATTR); } if (stack == null) { stack = new ArrayDeque<>(); stack.addAll(profiles); } String username = doAuth(req, resp); if (StringUtils.isNotEmpty(username)) { Map<String, Object> response = SSOOAuthServiceUtils.loginOnBehalf(resp, username, scope); FiltersHelper.isStatusOk(response); SSOUtils.createUserSession(req, FiltersHelper.getPayloadForToken(resp, (String) response.get("access_token")), false); } } catch (Exception e) { log.error("Cannot authenticate using External Authentication: {}", e.getMessage()); log.debug("Cannot authenticate using External Authentication", e); } }
Source:
<code>protected Map<String, Pair<String, String>> getSharedLocks() { if (getDisk() == null) { return null; } switch (getDisk().getVmEntityType()) { case VM: return createSharedLocksForVmDisk(); case TEMPLATE: return createSharedLocksForTemplateDisk(); <START> default: <END> return null; } }</code><technical_language>a bad idea log error</technical_language>

Target:
protected Map<String, Pair<String, String>> getSharedLocks() { if (getDisk() == null) { return null; } switch (getDisk().getVmEntityType()) { case VM: return createSharedLocksForVmDisk(); case TEMPLATE: return createSharedLocksForTemplateDisk(); default: log.warnFormat("No shared locks are taken while removing disk of entity: {0}", getDisk().getVmEntityType()); return null; } }
Source:
<code>protected void executeCommand() { <START> final Guid macPoolId = getParameters().getId(); <END> deletedMacPool = macPoolDao.get(getParameters().getId()); macPoolDao.remove(macPoolId); MacPoolPerDC.getInstance().removePool(macPoolId); getReturnValue().setSucceeded(true); }</code><technical_language>need save this a variable</technical_language>

Target:
protected void executeCommand() { final Guid macPoolId = getParameters().getId(); deletedMacPool = getMacPoolDAO().get(getParameters().getId()); getMacPoolDAO().remove(macPoolId); MacPoolPerDc.getInstance().removePool(macPoolId); getReturnValue().setSucceeded(true); }
Source:
<code>public void verify_notification_on_branch() throws Exception { RuleDto rule = ruleDbTester.insertRule(newRuleDto()); ComponentDto project = componentDbTester.insertMainBranch(); ComponentDto branch = componentDbTester.insertProjectBranch(project); ComponentDto file = componentDbTester.insertComponent(newFileDto(branch)); DefaultIssue issue = issueDbTester.insertIssue(IssueTesting.newIssue(rule.getDefinition(), branch, file)).setSeverity(MAJOR).toDefaultIssue(); IssueChangeContext context = IssueChangeContext.createUser(new Date(), "john"); issueFieldsSetter.setSeverity(issue, BLOCKER, context); underTest.saveIssue(dbTester.getSession(), issue, context, "increase severity"); verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture()); IssueChangeNotification issueChangeNotification = notificationArgumentCaptor.getValue(); assertThat(issueChangeNotification.getFieldValue("key")).isEqualTo(issue.key()); assertThat(issueChangeNotification.getFieldValue("projectKey")).isEqualTo(project.getDbKey()); <START> assertThat(issueChangeNotification.getFieldValue("projectName")).isEqualTo(project.longName()); <END> assertThat(issueChangeNotification.getFieldValue("branch")).isEqualTo(branch.getBranch()); }</code><technical_language>I actually, Unit Test right here. name() for a project, longName. In practice, name() longName() for a project. in theory, longName() sense for a project. change in IssueChangeNotification#setComponent</technical_language>

Target:
public void verify_notification_on_branch() throws Exception { RuleDto rule = ruleDbTester.insertRule(newRuleDto()); ComponentDto project = componentDbTester.insertMainBranch(); ComponentDto branch = componentDbTester.insertProjectBranch(project); ComponentDto file = componentDbTester.insertComponent(newFileDto(branch)); DefaultIssue issue = issueDbTester.insertIssue(IssueTesting.newIssue(rule.getDefinition(), branch, file)).setSeverity(MAJOR).toDefaultIssue(); IssueChangeContext context = IssueChangeContext.createUser(new Date(), "john"); issueFieldsSetter.setSeverity(issue, BLOCKER, context); underTest.saveIssue(dbTester.getSession(), issue, context, "increase severity"); verify(notificationManager).scheduleForSending(notificationArgumentCaptor.capture()); IssueChangeNotification issueChangeNotification = notificationArgumentCaptor.getValue(); assertThat(issueChangeNotification.getFieldValue("key")).isEqualTo(issue.key()); assertThat(issueChangeNotification.getFieldValue("projectKey")).isEqualTo(project.getDbKey()); assertThat(issueChangeNotification.getFieldValue("projectName")).isEqualTo(project.name()); assertThat(issueChangeNotification.getFieldValue("branch")).isEqualTo(branch.getBranch()); }
Source:
<code>public void onClusterAdded(String clusterName) { <START> incrementClusterAddedCount(clusterName); <END> }</code><technical_language>need extract this out private method if here. for onClusterRemoved</technical_language>

Target:
public void onClusterAdded(String clusterName) { AtomicInteger counter = clusterAddedCounter.computeIfAbsent(clusterName, (name) -> new AtomicInteger()); counter.incrementAndGet(); }
Source:
<code>public void testPutMultipartByteSource() throws Exception { long length = 33554432 + 1; BlobStore blobStore = view.getBlobStore(); MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm( getMinimumMultipartBlobSize(), blobStore.getMaximumMultipartPartSize(), blobStore.getMaximumNumberOfParts()); assertThat(algorithm.calculateChunkSize(length)).isLessThan(length); ByteSource byteSource = TestUtils.randomByteSource().slice(0, length); Payload payload = new ByteSourcePayload(byteSource); <START> payload.getContentMetadata().setContentMD5(Hashing.md5().hashBytes(byteSource.read())); <END> testPut(payload, payload, length, new PutOptions().multipart(true)); }</code><technical_language>hash buffering via: byteSource.hash(Hashing.md5())</technical_language>

Target:
public void testPutMultipartByteSource() throws Exception { long length = 32 * 1024 * 1024 + 1; BlobStore blobStore = view.getBlobStore(); MultipartUploadSlicingAlgorithm algorithm = new MultipartUploadSlicingAlgorithm( blobStore.getMinimumMultipartPartSize(), blobStore.getMaximumMultipartPartSize(), blobStore.getMaximumNumberOfParts()); assertThat(algorithm.calculateChunkSize(length)).isLessThan(length); ByteSource byteSource = TestUtils.randomByteSource().slice(0, length); Payload payload = new ByteSourcePayload(byteSource); HashCode hashCode = byteSource.hash(Hashing.md5()); testPut(payload, hashCode, payload, length, new PutOptions().multipart(true)); }
Source:
<code>public void deleteSnapshot(final INodesInPath iip, final String snapshotName, INode.ReclaimContext reclaimContext, long now) throws IOException { final INodeDirectory srcRoot = getSnapshottableRoot(iip); if (fsdir.isSnapshotDeletionOrdered()) { final DirectorySnapshottableFeature snapshottable = srcRoot.getDirectorySnapshottableFeature(); final Snapshot snapshot = snapshottable.getSnapshotByName( srcRoot, snapshotName); final int earliest = snapshottable.getDiffs().iterator().next() .getSnapshotId(); if (snapshot.getId() != earliest) { final XAttr snapshotXAttr = buildXAttr(); final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1); xattrs.add(snapshotXAttr); FSDirXAttrOp.unprotectedSetXAttrs(fsdir, INodesInPath.append(iip, snapshot.getRoot(), DFSUtil.string2Bytes(snapshotName)), xattrs, EnumSet.of(XAttrSetFlag.CREATE, XAttrSetFlag.REPLACE)); return; } final INodeDirectoryAttributes first = snapshottable.getDiffs().getFirstSnapshotINode(); if (snapshot.getRoot() != first) { <START> throw new IllegalStateException("Failed to delete snapshot " + snapshotName <END> + " from " + srcRoot.getFullPathName() + " since " + snapshotName + " is not the first snapshot (=" + first + ")"); } } srcRoot.removeSnapshot(reclaimContext, snapshotName, now); numSnapshots.getAndDecrement(); }</code><technical_language>This assertion gcDeletedSnapshot</technical_language>

Target:
public void deleteSnapshot(final INodesInPath iip, final String snapshotName, INode.ReclaimContext reclaimContext, long now) throws IOException { final INodeDirectory srcRoot = getSnapshottableRoot(iip); if (isSnapshotDeletionOrdered()) { final DirectorySnapshottableFeature snapshottable = srcRoot.getDirectorySnapshottableFeature(); final Snapshot snapshot = snapshottable.getSnapshotByName( srcRoot, snapshotName); final int earliest = snapshottable.getDiffs().getFirst().getSnapshotId(); if (snapshot.getId() != earliest) { final XAttr snapshotXAttr = buildXAttr(); final List<XAttr> xattrs = Lists.newArrayListWithCapacity(1); xattrs.add(snapshotXAttr); FSDirXAttrOp.unprotectedSetXAttrs(fsdir, INodesInPath.append(iip, snapshot.getRoot(), DFSUtil.string2Bytes(snapshotName)), xattrs, EnumSet.of(XAttrSetFlag.CREATE, XAttrSetFlag.REPLACE)); return; } assertFirstSnapshot(srcRoot, snapshottable, snapshot); } srcRoot.removeSnapshot(reclaimContext, snapshotName, now, this); numSnapshots.getAndDecrement(); }
Source:
<code>public String toString() { <START> return toStringHelper("").omitNullValues().add("id", id).add("name", name).toString(); <END> }</code><technical_language>empty string in toStringHelper("")</technical_language>

Target:
public String toString() { return toStringHelper(this).omitNullValues().add("id", id).add("name", name).toString(); }
Source:
<code>public boolean isApplicableForDwx(CloudSubnet cloudSubnet) { return cloudSubnet.getType() == null || PUBLIC.equals(cloudSubnet.getType()) <START> || SubnetType.PRIVATE.equals(cloudSubnet.getType()) <END> || SubnetType.DWX.equals(cloudSubnet.getType()); }</code><technical_language>Nit: SubnetType. qualifier is needed anymore</technical_language>

Target:
public boolean isApplicableForDwx(CloudSubnet cloudSubnet) { return cloudSubnet.getType() == null || PUBLIC.equals(cloudSubnet.getType()) || PRIVATE.equals(cloudSubnet.getType()) || DWX.equals(cloudSubnet.getType()); }
Source:
<code>public Page getNextPage() { if (isFinished()) { return null; } long start = System.nanoTime(); Page page = pageReader.next(); Block[] blocks = new Block[hiveColumnIndexes.length]; for (int fieldId = 0; fieldId < blocks.length; fieldId++) { if (hiveColumnIndexes[fieldId] >= page.getChannelCount()) { throw new PrestoException( NOT_SUPPORTED, <START> "schema mismatched table is not supported for PageFile format"); <END> } blocks[fieldId] = page.getBlock(hiveColumnIndexes[fieldId]); } readTimeNanos += System.nanoTime() - start; completedPositions += page.getPositionCount(); long pageSizeInBytes = page.getSizeInBytes(); completedBytes += pageSizeInBytes; memoryUsageBytes = Math.max(memoryUsageBytes, pageSizeInBytes); return new Page(page.getPositionCount(), blocks); }</code><technical_language>call schema evolution. change schema evolution is supported for page file format</technical_language>

Target:
public Page getNextPage() { if (isFinished()) { return null; } long start = System.nanoTime(); Page page = pageReader.next(); Block[] blocks = new Block[hiveColumnIndexes.length]; for (int fieldId = 0; fieldId < blocks.length; fieldId++) { if (hiveColumnIndexes[fieldId] >= page.getChannelCount()) { throw new PrestoException( NOT_SUPPORTED, "schema evolution is not supported for PageFile format"); } blocks[fieldId] = page.getBlock(hiveColumnIndexes[fieldId]); } readTimeNanos += System.nanoTime() - start; completedPositions += page.getPositionCount(); long pageSizeInBytes = page.getSizeInBytes(); completedBytes += pageSizeInBytes; memoryUsageBytes = Math.max(memoryUsageBytes, pageSizeInBytes); return new Page(page.getPositionCount(), blocks); }
Source:
<code>public void onMomPolicyChange(@Observes @MomPolicyUpdate final VDSGroup cluster) { if (cluster == null || cluster.getCompatibilityVersion().compareTo(Version.v3_4) < 0) return; List<VDS> activeHostsInCluster = DbFacade.getInstance() <START> .getVdsDao() <END> .getAllForVdsGroupWithStatus(cluster.getId(), VDSStatus.Up); List<Callable<VDSReturnValue>> callables = new LinkedList<>(); for (final VDS vds : activeHostsInCluster) { callables.add(new Callable<VDSReturnValue>() { @Override public VDSReturnValue call() { VDSReturnValue retVal = new VDSReturnValue(); try { retVal = resourceManagerProvider.get().runVdsCommand(VDSCommandType.SetMOMPolicyParameters, new MomPolicyVDSParameters(vds, cluster.isEnableBallooning(), cluster.isEnableKsm(), cluster.isKsmMergeAcrossNumaNodes()) ); } catch (VdcBLLException e) { log.error("Could not update MoM policy on host '{}'", vds.getName()); retVal.setSucceeded(false); } return retVal; } }); } if (callables.size() > 0) ThreadPoolUtil.invokeAll(callables); }</code><technical_language>please inject VdsDao. private members top of class</technical_language>

Target:
public void onMomPolicyChange(@Observes @MomPolicyUpdate final VDSGroup cluster) { if (cluster == null || cluster.getCompatibilityVersion().compareTo(Version.v3_4) < 0) return; List<VDS> activeHostsInCluster = vdsDAO.getAllForVdsGroupWithStatus(cluster.getId(), VDSStatus.Up); List<Callable<Object>> callables = new LinkedList<>(); for (final VDS vds : activeHostsInCluster) { callables.add(new Callable<Object>() { @Override public Object call() { try { resourceManagerProvider.get().runVdsCommand(VDSCommandType.SetMOMPolicyParameters, new MomPolicyVDSParameters(vds, cluster.isEnableBallooning(), cluster.isEnableKsm(), cluster.isKsmMergeAcrossNumaNodes()) ); } catch (VdcBLLException e) { log.error("Could not update MoM policy on host '{}'", vds.getName()); } return null; } }); } if (callables.size() > 0) ThreadPoolUtil.invokeAll(callables); }
Source:
<code>public AddDiskCommand(T parameters) { super(parameters); parameters.getDiskInfo().setId(Guid.NewGuid()); parameters.setEntityId(parameters.getDiskInfo().getId()); <START> isAddToVm = !Guid.Empty.equals(parameters.getVmId()); <END> }</code><technical_language>this a member. A function (as is computed of another member) inline</technical_language>

Target:
public AddDiskCommand(T parameters) { super(parameters); parameters.getDiskInfo().setId(Guid.NewGuid()); parameters.setEntityId(parameters.getDiskInfo().getId()); }
Source:
<code>private void registerContainerDeletionSyncTask(StateMachineEngine engine) { if (cloudConfig.cloudContainerCompactionEnabled) { Map<String, TaskFactory> taskFactoryMap = new HashMap<>(); taskFactoryMap.put(DeprecatedContainerCloudSyncTask.class.getSimpleName(), new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new DeprecatedContainerCloudSyncTask(accountService, storeConfig.storeContainerDeletionRetentionDays, cloudDestination, vcrMetrics); } }); if (!taskFactoryMap.isEmpty()) { if (engine.registerStateModelFactory(TaskConstants.STATE_MODEL_NAME, new TaskStateModelFactory(manager, taskFactoryMap))) { logger.info("Container deletion sync task registered with helix."); } else { <START> logger.error("Container deletion sync task registration with helix failed."); <END> } } } }</code><technical_language>effect of failure? Is safe log continue? I guess container deprecation fail fast situation, is wrong if log message</technical_language>

Target:
private void registerContainerDeletionSyncTask(StateMachineEngine engine) { if (cloudConfig.cloudContainerCompactionEnabled) { Map<String, TaskFactory> taskFactoryMap = new HashMap<>(); taskFactoryMap.put(DeprecatedContainerCloudSyncTask.class.getSimpleName(), new TaskFactory() { @Override public Task createNewTask(TaskCallbackContext context) { return new DeprecatedContainerCloudSyncTask(accountService, storeConfig.storeContainerDeletionRetentionDays, cloudDestination, vcrMetrics); } }); if (!taskFactoryMap.isEmpty()) { if (engine.registerStateModelFactory(TaskConstants.STATE_MODEL_NAME, new TaskStateModelFactory(manager, taskFactoryMap))) { logger.info("Container deletion sync task registered with helix."); } else { vcrMetrics.deprecationSyncTaskRegistrationFailureCount.inc(); logger.error("Container deletion sync task registration with helix failed."); } } } }
Source:
<code>public MCWeatherType getPlayerWeather() { <START> return MCWeatherType.valueOf(p.getPlayerWeather().name()); <END> }</code><technical_language>in a other places, BukkitMCWeatherType.getConcreteEnum(p.getPlayerWeather()) instead of this line. (You'll create file). assume enums map based name, prevents maintaining compatibility, functions throw error messages, instead of non-descript IllegalArgumentExceptions (and allow for intercept translate conversion in single place later, if needed.)</technical_language>

Target:
public MCWeather getPlayerWeather() { return BukkitMCWeather.getConvertor().getAbstractedEnum(p.getPlayerWeather()); }
Source:
<code>public CloudBackupManager(CloudConfig cloudConfig, ReplicationConfig replicationConfig, ClusterMapConfig clusterMapConfig, StoreConfig storeConfig, StoreKeyFactory storeKeyFactory, ClusterMap clusterMap, VirtualReplicatorCluster virtualReplicatorCluster, ScheduledExecutorService scheduler, ConnectionPool connectionPool, MetricRegistry metricRegistry, NotificationSystem requestNotification, StoreKeyConverterFactory storeKeyConverterFactory, String transformerClassName) throws ReplicationException { super(replicationConfig, clusterMapConfig, storeKeyFactory, clusterMap, scheduler, virtualReplicatorCluster.getDataNodeId(), connectionPool, metricRegistry, requestNotification, storeKeyConverterFactory, transformerClassName); <START> } <END></code><technical_language>Feel free add rest of constructor gist this PR, ready</technical_language>

Target:
public CloudBackupManager(CloudConfig cloudConfig, ReplicationConfig replicationConfig, ClusterMapConfig clusterMapConfig, StoreConfig storeConfig, StoreKeyFactory storeKeyFactory, ClusterMap clusterMap, VirtualReplicatorCluster virtualReplicatorCluster, ScheduledExecutorService scheduler, ConnectionPool connectionPool, MetricRegistry metricRegistry, NotificationSystem requestNotification, StoreKeyConverterFactory storeKeyConverterFactory, String transformerClassName) throws ReplicationException { super(replicationConfig, clusterMapConfig, storeKeyFactory, clusterMap, scheduler, virtualReplicatorCluster.getCurrentDataNodeId(), connectionPool, metricRegistry, requestNotification, storeKeyConverterFactory, transformerClassName); }
Source:
<code>private String getCanonicalHeadersString(List<HttpHeaderField> headers) { if (headers != null && !headers.isEmpty()) { <START> headers.removeIf( <END> h -> h == null || h.getName() == null || h.getName().trim().isEmpty() || h.getValue() == null); return headers.stream() .sorted((h1, h2) -> h1.getName().compareTo(h2.getName())) .map(h -> h.getName().trim() + "=" + h.getValue().trim()) .collect(Collectors.joining("|")); } return ""; }</code><technical_language>do validations resource is created, used</technical_language>

Target:
private String getCanonicalHeadersString(List<HttpHeaderField> headers) { return headers.stream() .sorted((h1, h2) -> h1.getName().compareTo(h2.getName())) .map(h -> h.getName().trim() + "=" + h.getValue().trim()) .collect(Collectors.joining("|")); }
Source:
<code>private void validateNetworkExclusiveOnIface(VdsNetworkInterface iface, NetworkType networkType) { String ifaceName = NetworkUtils.StripVlan(iface.getName()); <START> if (ifacesWithExclusiveNetwork.containsKey(ifaceName)) { <END> if ((networkType == NetworkType.VLAN && ifacesWithExclusiveNetwork.get(ifaceName) == NetworkType.VM) || networkType != NetworkType.VLAN) { addViolation(VdcBllMessages.NETWORK_INTERFACES_NOT_EXCLUSIVELY_USED_BY_NETWORK, ifaceName); } } if (networkType != NetworkType.VLAN) { ifacesWithExclusiveNetwork.put(ifaceName, networkType); } }</code><technical_language>nesting removed condition simplified</technical_language>

Target:
private void validateNetworkExclusiveOnIface(VdsNetworkInterface iface, NetworkType networkType) { String ifaceName = NetworkUtils.StripVlan(iface.getName()); List<NetworkType> networksOnIface = ifacesWithExclusiveNetwork.get(ifaceName); if (networksOnIface == null) { networksOnIface = new ArrayList<SetupNetworksHelper.NetworkType>(); ifacesWithExclusiveNetwork.put(ifaceName, networksOnIface); } if ((networkType == NetworkType.VLAN && networksOnIface.contains(NetworkType.VM)) || (networkType == NetworkType.VM && !networksOnIface.isEmpty())) { addViolation(VdcBllMessages.NETWORK_INTERFACES_NOT_EXCLUSIVELY_USED_BY_NETWORK, ifaceName); } networksOnIface.add(networkType); }
Source:
<code>public CouchDbConsentDecision(final ConsentDecision c) { setAttributes(c.getAttributes()); setPrincipal(c.getPrincipal()); setCreatedDate(c.getCreatedDate()); setId(c.getId()); setOptions(c.getOptions()); setReminder(c.getReminder()); setReminderTimeUnit(c.getReminderTimeUnit()); setService(c.getService()); if (getId() < 0) { <START> setId(SecureRandom.getInstanceStrong().nextLong()); <END> } }</code><technical_language>nextLong return a negative, right</technical_language>

Target:
public CouchDbConsentDecision(final ConsentDecision c) { setAttributes(c.getAttributes()); setPrincipal(c.getPrincipal()); setCreatedDate(c.getCreatedDate()); setId(c.getId()); setOptions(c.getOptions()); setReminder(c.getReminder()); setReminderTimeUnit(c.getReminderTimeUnit()); setService(c.getService()); if (getId() < 0) { setId(Math.abs(RandomUtils.getNativeInstance().nextLong())); } }
Source:
<code>public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password); if(u != null) { Authentication auth; try { UserDetails userDetails = u.getUserDetailsForImpersonation(); if (UserDetailsHelper.isFullyActive(userDetails)) { auth = u.impersonate(userDetails); SecurityListener.fireAuthenticated(userDetails); } else { <START> LOGGER.log(INFO, "API token matched for user {0} but the account is [enable={1}, accountNonExpired={2}, accountNonLocked={3}, credentialsNonExpired={4}]", new Object[]{ <END> username, userDetails.isEnabled(), userDetails.isAccountNonExpired(), userDetails.isAccountNonLocked(), userDetails.isCredentialsNonExpired() }); return null; } } catch (UsernameNotFoundException x) { LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true); return auth; } return null; }</code><technical_language>suggestion LOGGER.log(INFO, "API token matched for user {0} account is [enabled={1}, accountNonExpired={2}, accountNonLocked={3}, credentialsNonExpired={4}]", new Object[]{</technical_language>

Target:
public Authentication authenticate(HttpServletRequest req, HttpServletResponse rsp, String username, String password) throws ServletException { User u = BasicApiTokenHelper.isConnectingUsingApiToken(username, password); if(u != null) { Authentication auth; try { UserDetails userDetails = u.getUserDetailsForImpersonation(); if (UserDetailsHelper.isFullyActive(userDetails)) { auth = u.impersonate(userDetails); SecurityListener.fireAuthenticated(userDetails); } else { LOGGER.log(INFO, "API token matched for user {0} but the account is [enabled={1}, accountNonExpired={2}, accountNonLocked={3}, credentialsNonExpired={4}]", new Object[]{ username, userDetails.isEnabled(), userDetails.isAccountNonExpired(), userDetails.isAccountNonLocked(), userDetails.isCredentialsNonExpired() }); return null; } } catch (UsernameNotFoundException x) { LOGGER.log(WARNING, "API token matched for user " + username + " but the impersonation failed", x); throw new ServletException(x); } catch (DataAccessException x) { throw new ServletException(x); } req.setAttribute(BasicHeaderApiTokenAuthenticator.class.getName(), true); return auth; } return null; }
Source:
<code>public List<Repository> clearCache(Collection<String> repositories) throws HistoryException { List<Repository> repos = getReposFromString(repositories); HistoryCache cache = historyCache; <START> <END> for (Repository r : repos) { try { cache.clear(r); LOGGER.log(Level.INFO, "History cache for {0} cleared.", r.getDirectoryName()); } catch (HistoryException e) { LOGGER.log(Level.WARNING, "Clearing history cache for repository {0} failed: {1}", new Object[]{r.getDirectoryName(), e.getLocalizedMessage()}); } } return repos; }</code><technical_language>this is needed anymore</technical_language>

Target:
public List<Repository> clearCache(Collection<String> repositories) throws HistoryException { List<Repository> repos = new ArrayList<>(); HistoryCache cache = historyCache; if (!useCache()) { return repos; } for (Repository r : getReposFromString(repositories)) { try { cache.clear(r); repos.add(r); LOGGER.log(Level.INFO, "History cache for {0} cleared.", r.getDirectoryName()); } catch (HistoryException e) { LOGGER.log(Level.WARNING, "Clearing history cache for repository {0} failed: {1}", new Object[]{r.getDirectoryName(), e.getLocalizedMessage()}); } } return repos; }