auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
START private String enforceNotNullNorEmpty(String str, String propertyName) { END checkNotNull(str, "%s can't be null", propertyName); checkArgument(!str.isEmpty(), "%s can't be empty", propertyName); return str; } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Make "enforceNotNullNorEmpty" a "static" method. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2325)

Target:
private static String enforceNotNullNorEmpty(String str, String propertyName) { checkNotNull(str, "%s can't be null", propertyName); checkArgument(!str.isEmpty(), "%s can't be empty", propertyName); return str; }
Source:
START public void size_rolling_policy_has_large_max_files_if_property_is_zero() throws IOException { END File logDir = temporaryFolder.newFolder(); String logPattern = "foo"; String sizePattern = "1KB"; Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "size:" +sizePattern, PROPERTY_MAX_FILES, "0"); underTest.configureGlobalFileLog(esRootLoggerConfig, logDir, logPattern); verifySizeRollingPolicy(underTest, logDir, logPattern, sizePattern, 100_000); } missing test for when property is less than zero. Code would also put large max file

Target:
public void size_rolling_policy_has_large_max_files_if_property_is_zero() throws Exception { File logDir = temporaryFolder.newFolder(); String logPattern = "foo"; String sizePattern = "1KB"; Log4JPropertiesBuilder underTest = newLog4JPropertiesBuilder( ROLLING_POLICY_PROPERTY, "size:" + sizePattern, PROPERTY_MAX_FILES, "0"); underTest.configureGlobalFileLog(esRootLoggerConfig, logDir, logPattern); verifySizeRollingPolicy(underTest, logDir, logPattern, sizePattern, 100_000); }
Source:
public Tracking<RAW, BASE> track(Collection<RAW> rawInput, Collection<BASE> baseInput) { Tracking<RAW, BASE> tracking = new Tracking<>(rawInput, baseInput); // 1. match issues with same rule, same line and same line hash, but not necessarily with same message START match(tracking, LineAndLineHashKey::new, true); END // 2. match issues with same rule, same message and same line hash match(tracking, LineHashAndMessageKey::new, true); return tracking; } The factory is always the same. If you don't want to keep the INSTANCE, what about creating as a static member field?

Target:
public Tracking<RAW, BASE> track(Collection<RAW> rawInput, Collection<BASE> baseInput) { Tracking<RAW, BASE> tracking = new Tracking<>(rawInput, baseInput); // 1. match issues with same rule, same line and same line hash, but not necessarily with same message match(tracking, LineAndLineHashKey::new); // 2. match issues with same rule, same message and same line hash match(tracking, LineHashAndMessageKey::new); return tracking; }
Source:
private void closeIssuesForDeletedComponentUuids(Set<String> deletedComponentUuids) { DiskCache<DefaultIssue>.DiskAppender cacheAppender = issueCache.newAppender(); try { for (String deletedComponentUuid : deletedComponentUuids) { START List<DefaultIssue> issues = issuesLoader.loadForComponentUuid(deletedComponentUuid, false); END for (DefaultIssue issue : issues) { issue.setBeingClosed(true); // TODO should be renamed issue.setOnDisabledRule(false); issueLifecycle.doAutomaticTransition(issue); cacheAppender.append(issue); } } } finally { cacheAppender.close(); } } A UT should be added to check that changelog are correctly loaded

Target:
private void closeIssuesForDeletedComponentUuids(Set<String> deletedComponentUuids) { DiskCache<DefaultIssue>.DiskAppender cacheAppender = issueCache.newAppender(); try { for (String deletedComponentUuid : deletedComponentUuids) { List<DefaultIssue> issues = issuesLoader.loadForComponentUuid(deletedComponentUuid); for (DefaultIssue issue : issues) { issue.setBeingClosed(true); // TODO should be renamed issue.setOnDisabledRule(false); issueLifecycle.doAutomaticTransition(issue); cacheAppender.append(issue); } } } finally { cacheAppender.close(); } }
Source:
public void handle(Request request, Response response) { try (DbSession dbSession = dbClient.openSession(false)) { START long conditionId = request.mandatoryParamAsLong(PARAM_ID); END OrganizationDto organization = wsSupport.getOrganization(dbSession); userSession.checkPermission(ADMINISTER_QUALITY_GATES, organization); dbClient.gateConditionDao().delete(wsSupport.getCondition(dbSession, conditionId), dbSession); dbSession.commit(); response.noContent(); } } Should be done before opening a db session - for to fail fast.

Target:
public void handle(Request request, Response response) { long conditionId = request.mandatoryParamAsLong(PARAM_ID); try (DbSession dbSession = dbClient.openSession(false)) { OrganizationDto organization = wsSupport.getOrganization(dbSession); userSession.checkPermission(ADMINISTER_QUALITY_GATES, organization); dbClient.gateConditionDao().delete(wsSupport.getCondition(dbSession, conditionId), dbSession); dbSession.commit(); response.noContent(); } }
Source:
public boolean equals(Object o) { if (this == o) { return true; } START if (!(o instanceof Analysis)) { END return false; } Analysis analysis = (Analysis) o; return Objects.equal(projectUuid, analysis.projectUuid) && Objects.equal(ceTaskUuid, analysis.ceTaskUuid) && Objects.equal(analysisUuid, analysis.analysisUuid); } this makes equals support subclasses. This is not necessarily the intent

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Analysis analysis = (Analysis) o; return Objects.equals(projectUuid, analysis.projectUuid) && Objects.equals(ceTaskUuid, analysis.ceTaskUuid) && Objects.equals(analysisUuid, analysis.analysisUuid); }
Source:
public void deleteByQProfileAndUser(DbSession dbSession, QProfileDto profile, UserDto user) { START mapper(dbSession).delete(profile.getKee(), user.getLogin()); END } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Remove this use of "now"; it is deprecated. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3ACallToDeprecatedMethod)

Target:
public void deleteByQProfileAndUser(DbSession dbSession, QProfileDto profile, UserDto user) { mapper(dbSession).delete(profile.getKee(), user.getId()); }
Source:
public void start() { START INSTANCE = this; END } Won't fix.

Target:
public void start() { instance = this; }
Source:
public void stop() { START INSTANCE = null; END } Won't fix.

Target:
public void stop() { instance = null; }
Source:
private String getDbVendor() { START return dbClient.getDatabase().getDialect().getId().toLowerCase(Locale.ENGLISH); END } 🐜 I would suggest not to lower the case, since it our own database ids are lowercase anyways.

Target:
private String getDbVendor() { return dbClient.getDatabase().getDialect().getId(); }
Source:
START public Optional<String> getMetadata(String id) { END GetRequestBuilder request = esClient.prepareGet(MetadataIndexDefinition.INDEX_TYPE_METADATA, id) .setStoredFields(MetadataIndexDefinition.FIELD_VALUE); GetResponse response = request.get(); if (response.isExists()) { GetField field = response.getField(MetadataIndexDefinition.FIELD_VALUE); String value = String.valueOf(field.getValue()); return Optional.of(value); } return Optional.empty(); } 🐭 I have a slight preference to have all metadata keys defined here, so that we can more easily manage what the metadata index is used for.

Target:
private Optional<String> getMetadata(String id) { GetRequestBuilder request = esClient.prepareGet(MetadataIndexDefinition.INDEX_TYPE_METADATA, id) .setStoredFields(MetadataIndexDefinition.FIELD_VALUE); GetResponse response = request.get(); if (response.isExists()) { GetField field = response.getField(MetadataIndexDefinition.FIELD_VALUE); String value = String.valueOf(field.getValue()); return Optional.of(value); } return Optional.empty(); }
Source:
START public void setMetadata(String id, String value) { END esClient.prepareIndex(MetadataIndexDefinition.INDEX_TYPE_METADATA) .setId(id) .setSource(MetadataIndexDefinition.FIELD_VALUE, value) .setRefreshPolicy(REFRESH_IMMEDIATE) .get(); } 🐭 Same here: I'd slightly prefer `private`.

Target:
private void setMetadata(String id, String value) { esClient.prepareIndex(MetadataIndexDefinition.INDEX_TYPE_METADATA) .setId(id) .setSource(MetadataIndexDefinition.FIELD_VALUE, value) .setRefreshPolicy(REFRESH_IMMEDIATE) .get(); }
Source:
public void close() { try { START hazelcastCluster.close(); END } catch (HazelcastInstanceNotActiveException e) { // hazelcastCluster may be already closed by the shutdown hook LOGGER.debug("Unable to close Hazelcast cluster", e); } } I believe it would be more appropriate to catch this error in class `HazelcastCluster` for two reasons: 1. would be able to put try/catch around `hzInstance.shutdown()` (which I believe it the method actually raising the exception in SQ's code) 2. design and import-wize AppStateClusterImpl does not deal with the hazelcast framework. It should stay that way

Target:
public void close() { hazelcastCluster.close(); }
Source:
private void loadMergeBranchComponents() { START String mergeBranchUuid = analysisMetadataHolder.getBranch().get().getMergeBranchUuid().get(); END uuidsByKey = new HashMap<>(); try (DbSession dbSession = dbClient.openSession(false)) { List<ComponentDto> components = dbClient.componentDao().selectByProjectUuid(mergeBranchUuid, dbSession); for (ComponentDto dto : components) { uuidsByKey.put(removeBranchFromKey(dto.getDbKey()), dto.uuid()); } } } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Call "Optional#isPresent()" before accessing the value. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS3655)

Target:
private void loadMergeBranchComponents() { String mergeBranchUuid = analysisMetadataHolder.getBranch().get().getMergeBranchUuid().get(); uuidsByKey = new HashMap<>(); try (DbSession dbSession = dbClient.openSession(false)) { List<ComponentDto> components = dbClient.componentDao().selectByProjectUuid(mergeBranchUuid, dbSession); for (ComponentDto dto : components) { uuidsByKey.put(dto.getKey(), dto.uuid()); } } }
Source:
public void setPrivateForRootComponentUuid(DbSession session, String projectUuid, boolean isPrivate) { mapper(session).setPrivateForRootComponentUuid(projectUuid, isPrivate); START session.getMapper(BranchMapper.class).selectByProjectUuid(projectUuid) END .stream() .filter(branch -> !projectUuid.equals(branch.getUuid())) .forEach(branch -> mapper(session).setPrivateForRootComponentUuid(branch.getUuid(), isPrivate)); } I thought we said that you'll move it to the WS ?

Target:
public void setPrivateForRootComponentUuid(DbSession session, String projectUuid, boolean isPrivate) { mapper(session).setPrivateForRootComponentUuid(projectUuid, isPrivate); }
Source:
START private static Optional<String> getBranchName(Optional<Branch> branchOpt) { END if (!branchOpt.isPresent()) { return Optional.empty(); } Branch branch = branchOpt.get(); if (!branch.isLegacyFeature() && !branch.isMain()) { return branch.getName(); } return Optional.empty(); } ![MINOR](https://sonarsource.github.io/sonar-github/severity-minor.png 'Severity: MINOR') Specify a "Branch" parameter instead. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS3553)

Target:
private static Optional<String> getBranchName(Optional<Branch> branchOpt) { if (!branchOpt.isPresent()) { return Optional.empty(); } Branch branch = branchOpt.get(); if (!branch.isLegacyFeature() && !branch.isMain()) { return Optional.of(branch.getName()); } return Optional.empty(); }
Source:
public ComponentWsRequest setComponentKey(@Nullable String componentKey) { return setComponent(componentKey); START } END ![INFO](https://sonarsource.github.io/sonar-github/severity-info.png 'Severity: INFO') Do not forget to remove this deprecated code someday. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS1133)

Target:
public ComponentWsRequest setComponentKey(@Nullable String componentKey) { this.componentKey = componentKey; return this; }
Source:
public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) { START return mapper(session).selectUuidsForQualifiers(Qualifiers.VIEW, Qualifiers.SUBVIEW, Qualifiers.APP); END } This method is only used to index view

Target:
public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) { return mapper(session).selectUuidsForQualifiers(Qualifiers.VIEW, Qualifiers.SUBVIEW); }
Source:
public MetricDto insert(DbSession session, MetricDto dto) { START mapper(session).insert(validate(dto)); END return dto; } AFAIK, It's not the responsability of DAO to validate dto. This should be in a higher layer, a XXXUpdater or the WS

Target:
public MetricDto insert(DbSession session, MetricDto dto) { mapper(session).insert(dto); return dto; }
Source:
START private String getPluginKeyAndResourcePath(HttpServletRequest request) { END return StringUtils.substringAfter(request.getRequestURI(), request.getContextPath() + request.getServletPath() + "/"); } ![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Make "getPluginKeyAndResourcePath" a "static" method. [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2325)

Target:
private static String getPluginKeyAndResourcePath(HttpServletRequest request) { return StringUtils.substringAfter(request.getRequestURI(), request.getContextPath() + request.getServletPath() + "/"); }
Source:
public void setUp() { START ws = new WsActionTester(new ShowAction(db.getDbClient(), parser, duplicationsJsonWriter, userSessionRule, TestComponentFinder.from(db))); END db.getDbClient().metricDao().insert(db.getSession(), dataMetric); db.commit(); } This can be inline with line 58

Target:
public void setUp() { db.getDbClient().metricDao().insert(db.getSession(), dataMetric); db.commit(); }
Source:
private ComponentDto getByKey(DbSession dbSession, String key, String label) { START return checkComponent(() -> dbClient.componentDao().selectByKey(dbSession, key), () -> format("%s key '%s' not found", label, key)); END } I like the pattern to use a supplier to compute the error message but why not use the same as the one used for `org.sonar.server.ws.WsUtils#checkRequest(condition, errorMessage, arguments...)`?

Target:
private ComponentDto getByKey(DbSession dbSession, String key, String label) { return checkComponent(dbClient.componentDao().selectByKey(dbSession, key), "%s key '%s' not found", label, key); }
Source:
private List<UserDto> findUsers(DbSession dbSession, PermissionQuery query) { START List<Integer> orderedIds = new ArrayList<>(dbClient.userPermissionDao().selectUserIdsByQuery(dbSession, query)); END return Ordering.explicit(orderedIds).onResultOf(UserDto::getId).immutableSortedCopy(dbClient.userDao().selectByIds(dbSession, orderedIds)); } why create a new list and not immutable?

Target:
private List<UserDto> findUsers(DbSession dbSession, PermissionQuery query) { List<Integer> orderedIds = dbClient.userPermissionDao().selectUserIdsByQuery(dbSession, query); return Ordering.explicit(orderedIds).onResultOf(UserDto::getId).immutableSortedCopy(dbClient.userDao().selectByIds(dbSession, orderedIds)); }
Source:
public LoggerContext configure(Props props) { LoggerContext ctx = helper.getRootContext(); ctx.reset(); configureRootLogger(props); helper.apply(logLevelConfig, props); START helper.enableJulChangePropagation(ctx); END configureDirectToConsoleLoggers(ctx, STARTUP_LOGGER_NAME); extendConfigure(); return ctx; } what is the reason behind moving call to enableJulChangePropagation after configuring the loggers in SLF4J?

Target:
public LoggerContext configure(Props props) { LoggerContext ctx = helper.getRootContext(); ctx.reset(); helper.enableJulChangePropagation(ctx); configureRootLogger(props); helper.apply(logLevelConfig, props); configureDirectToConsoleLoggers(ctx, STARTUP_LOGGER_NAME); extendConfigure(); return ctx; }
Source:
public TrackedIssue setComponentKey(String componentKey) { START Preconditions.checkArgument(StringUtils.countMatches(componentKey, ":") <= 1, "componentKey should not have branch"); END this.componentKey = componentKey; return this; } ":" is allowed in projet keys

Target:
public TrackedIssue setComponentKey(String componentKey) { this.componentKey = componentKey; return this; }
Source:
public void returns_project_visibility_public() { OrganizationDto organization = dbTester.organizations().insert(); START dbClient.organizationDao().setNewProjectPrivate(dbTester.getSession(), organization, false); END dbTester.commit(); userSession.logIn().addPermission(PROVISION_PROJECTS, organization); assertJson(executeRequest(organization).getInput()).isSimilarTo("{\"organization\": {\"projectVisibility\": \"public\"}}"); } what about replacing lines 221 and 222 by a method in `OrganizationDbTester`?

Target:
public void returns_project_visibility_public() { OrganizationDto organization = dbTester.organizations().insert(); dbTester.organizations().setNewProjectPrivate(organization, false); userSession.logIn().addPermission(PROVISION_PROJECTS, organization); assertJson(executeRequest(organization).getInput()).isSimilarTo("{\"organization\": {\"projectVisibility\": \"public\"}}"); }
Source:
public void handle(Request request, Response response) throws Exception { verifySystemAdministrator(); START List<RuleKey> disabledTemplateAndCustomRuleKeys = null; END try (DbSession dbSession = dbClient.openSession(false)) { if (isSupportDisabled(dbSession)) { flagCurrentUserAsRoot(dbSession); createDefaultMembersGroup(dbSession); disabledTemplateAndCustomRuleKeys = disableTemplateRulesAndCustomRules(dbSession); enableFeature(dbSession); dbSession.commit(); } } if (disabledTemplateAndCustomRuleKeys != null) { ruleIndexer.indexRuleDefinitions(disabledTemplateAndCustomRuleKeys); } response.noContent(); } no need to define this variable that early, move `ruleIndexer.indexRuleDefinitions(disabledTemplateAndCustomRuleKeys);` after `dbSession.commit();` and get rid of the ugly variable initialized to `null` closing the connection is not that important. The correct code would pass it to `ruleIndexer.indexRuleDefinitions` anyway (or it wouldn't really be closed so that a single SQL session is used by HTTP request)

Target:
public void handle(Request request, Response response) throws Exception { verifySystemAdministrator(); try (DbSession dbSession = dbClient.openSession(false)) { if (isSupportDisabled(dbSession)) { flagCurrentUserAsRoot(dbSession); createDefaultMembersGroup(dbSession); List<RuleKey> disabledTemplateAndCustomRuleKeys = disableTemplateRulesAndCustomRules(dbSession); enableFeature(dbSession); dbSession.commit(); ruleIndexer.indexRuleDefinitions(disabledTemplateAndCustomRuleKeys); } } response.noContent(); }
Source:
private static String convertPatternsToString(List<String> input) { START StringBuilder toStringBuilder = new StringBuilder(); END if (input.isEmpty()) { return ""; } if (input.size() == 1) { return toStringBuilder.append(input.get(0)).toString(); } return toStringBuilder.append(input.get(0)).append(", ...").toString(); } suggestion: rename to `output`

Target:
private static String convertPatternsToString(List<String> input) { StringBuilder output = new StringBuilder(); if (input.isEmpty()) { return ""; } if (input.size() == 1) { return output.append(input.get(0)).toString(); } return output.append(input.get(0)).append(", ...").toString(); }
Source:
private void writeResponse(Request request, Response response, OrganizationDto organization, GroupDto group) { START WsUserGroups.CreateWsResponse.Builder respBuilder = WsUserGroups.CreateWsResponse.newBuilder(); END respBuilder.setGroup(toProtobuf(organization, group, 0)); writeProtobuf(respBuilder.build(), request, response); } remark: I had the feedback that we should call this classes `CreateResponse` without Ws. I don't have a strong opinion on this…

Target:
private void writeResponse(Request request, Response response, OrganizationDto organization, GroupDto group) { WsUserGroups.CreateWsResponse.Builder respBuilder = WsUserGroups.CreateWsResponse.newBuilder(); // 'default' is always false as it's not possible to create a default group respBuilder.setGroup(toProtobuf(organization, group, 0, false)); writeProtobuf(respBuilder.build(), request, response); }
Source:
private void populateSchemaMigration(Connection connection, long maxMigrationNumber) { try (PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO SCHEMA_MIGRATIONS(VERSION) VALUES (?)")) { batchExecute( 0, maxMigrationNumber + 1, preparedStatement, connection, (statement, counter) -> statement.setString(1, String.valueOf(counter))); } catch (SQLException e) { START throw new RuntimeException("Failed to insert rows into table SCHEMA_MIGRATIONS", e); END } } ![MAJOR](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-major.png 'Severity: MAJOR') Define and throw a dedicated exception instead of using a generic one. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS00112)

Target:
private static void populateSchemaMigration(Connection connection, long maxMigrationNumber) { try (PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO SCHEMA_MIGRATIONS(VERSION) VALUES (?)")) { batchExecute( 0, maxMigrationNumber + 1, preparedStatement, connection, (statement, counter) -> statement.setString(1, String.valueOf(counter))); } catch (SQLException e) { throw new RuntimeException("Failed to insert rows into table SCHEMA_MIGRATIONS", e); } }
Source:
protected void configureModule() { add( CeTaskProcessorRepositoryImpl.class, START CeWorkerImpl.class, END CeWorkerFactoryImpl.class, CeProcessingSchedulerExecutorServiceImpl.class, CeProcessingSchedulerImpl.class); } there is no more need for any instance of `CeWorkerImpl` to be in the container `CeWorkerImpl` instances are now produced by the `CeWorkerFactory`

Target:
protected void configureModule() { add( CeTaskProcessorRepositoryImpl.class, CeWorkerFactoryImpl.class, CeProcessingSchedulerExecutorServiceImpl.class, CeProcessingSchedulerImpl.class); }
Source:
public void stop() { START hzInstance.getReplicatedMap(CLIENT_UUIDS).remove(hzInstance.getLocalEndpoint().getUuid()); END // Shutdown Hazelcast properly hzInstance.shutdown(); } This constant should be WORKER_UUIDS. 1. this either indicates that a UT is missing (if such UT existed, it would fail as the entry in the WORKER_UUIDS map for the current local endpoint isn't cleared) 2. or the entry is cleared by another piece of code and this one is useless

Target:
public void stop() { // Shutdown Hazelcast properly hzInstance.shutdown(); }
Source:
private void initCe() { processingScheduler.startScheduling(); cleaningScheduler.startScheduling(); START ceDistributedInformation.broadcastWorkerUUIDs(); END } I'd put this right after starting the CE worker processes there is no need to wait for the cleaning process to be up but broadcasting the worker uuids as soon as possible is actually important

Target:
private void initCe() { ceDistributedInformation.broadcastWorkerUUIDs(); processingScheduler.startScheduling(); cleaningScheduler.startScheduling(); }
Source:
public boolean hasNext() { for (;;) { START if (currentChunk != null && currentChunk.hasNext()) { END return true; } else if (iteratorOverChunks.hasNext()) { currentChunk = nextChunk(); } else { return false; } } } The `else` conditions can be dropped because of `return`. That will decrease cognitive complexity!

Target:
public boolean hasNext() { for (;;) { if (currentChunk != null && currentChunk.hasNext()) { return true; } if (iteratorOverChunks.hasNext()) { currentChunk = nextChunk(); } else { return false; } } }
Source:
START public List<QualityProfile> load(String projectKey, @Nullable String profileName) { END StringBuilder url = new StringBuilder(WS_URL + "?projectKey=" + encodeForUrl(projectKey)); if (profileName != null) { url.append("&profileName=").append(encodeForUrl(profileName)); } getOrganizationKey().ifPresent(k -> url.append("&organization=").append(encodeForUrl(k))); return call(url.toString()); } These `+`s could also be changed to `append`s.

Target:
public List<QualityProfile> load(String projectKey, @Nullable String profileName) { StringBuilder url = new StringBuilder(WS_URL + "?projectKey=").append(encodeForUrl(projectKey)); if (profileName != null) { url.append("&profileName=").append(encodeForUrl(profileName)); } getOrganizationKey().ifPresent(k -> url.append("&organization=").append(encodeForUrl(k))); return call(url.toString()); }
Source:
public void handle(Request request, Response response) throws Exception { START userSession.checkLoggedIn().checkIsSystemAdministrator(); END GroupsWsResponse groupsWsResponse = doHandle(toGroupsRequest(request)); writeProtobuf(groupsWsResponse, request, response); } no limit on the page size?

Target:
public void handle(Request request, Response response) throws Exception { GroupsWsResponse groupsWsResponse = doHandle(toGroupsRequest(request)); writeProtobuf(groupsWsResponse, request, response); }
Source:
START private QualityProfileDto dto(String key) { END return new QualityProfileDto() { { setKey(key); } @Override public String toString() { return getKey(); } }; } Strange way to call simply `new QualityProfileDto().setKey(key)`. Do I miss something?

Target:
private QualityProfileDto dto(String key) { return new QualityProfileDto() { @Override public String toString() { return getKey(); } }.setKey(key); }
Source:
public void name_requires_either_component_or_defaults() throws Exception { START thrown.expect(BadRequestException.class); END thrown.expectMessage("The name parameter requires either projectKey or defaults to be set."); SearchWsRequest request = new SearchWsRequest() .setProfileName("bla"); SearchDataLoader.validateRequest(request); } if exception is thrown by `validateRequest`, `thrown` configuration should be done right before `validateRequest` is called

Target:
public void name_requires_either_component_or_defaults() throws Exception { SearchWsRequest request = new SearchWsRequest() .setProfileName("bla"); thrown.expect(BadRequestException.class); thrown.expectMessage("The name parameter requires either projectKey or defaults to be set."); SearchDataLoader.validateRequest(request); }
Source:
public static NewParam createOrganizationParameter(NewAction action) { return action.createParam(PARAM_ORGANIZATION) .setDescription("Key of organization, used when group name is set") .setExampleValue("my-org") START .setSince("6.2") END .setInternal(true); } this line should not be in the builder method IMO because it's very context sensitive

Target:
public static NewParam createOrganizationParameter(NewAction action) { return action.createParam(PARAM_ORGANIZATION) .setDescription("Key of organization, used when group name is set") .setExampleValue("my-org") .setInternal(true); }
Source:
START public SelenideElement getSortingButton(String selector) { END ElementsCollection buttons = this.elt.$$(".projects-facet-sort a"); return buttons.find(new Condition("AttributeMatch") { @Override public boolean apply(WebElement webElement) { return webElement.getAttribute("href").matches(".*sort=" + selector + ".*"); } }); } it should be `private`, welcome to the java world :)

Target:
private SelenideElement getSortingButton(String selector) { ElementsCollection buttons = this.elt.$$(".projects-facet-sort a"); return buttons.find(new Condition("AttributeMatch") { @Override public boolean apply(WebElement webElement) { return webElement.getAttribute("href").matches(".*sort=" + selector + ".*"); } }); }
Source:
START public List<QualityProfileDto> selectByNameAndLanguages(String name, Collection<String> languageKeys, DbSession session) { END return executeLargeInputs(languageKeys, input -> mapper(session).selectByNameAndLanguages(name, input)); } ![INFO](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/severity-info.png 'Severity: INFO') Do not forget to remove this deprecated code someday. [![rule](https://raw.githubusercontent.com/SonarCommunity/sonar-github/master/images/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS1133)

Target:
public List<QualityProfileDto> selectByNameAndLanguages(String name, Collection<String> languageKeys, DbSession session) { return executeLargeInputs(languageKeys, input -> mapper(session).selectByNameAndLanguages(null, name, input)); }
Source:
public void onConnect(String room, String serverAddress) { debugView.showPermanently(getString(R.string.connected)); switchableView.setDisplayedChild(1); START lastServerPreferences.saveLastConnectedServer(serverAddress); END joinHangoutRoom(room); } is this a temporary hack? otherwise : I would not be saving state inside the View, I would do it inside of the model (looks like it's called a service in your case). i.e. inside of `humanTelepresenceService.connectTo(serverAddress)` compose the `humanTelepresenceService` of SharedPreferences/LongtermStorage

Target:
public void onConnect(String room, String serverAddress) { debugView.showPermanently(getString(R.string.connected)); switchableView.setDisplayedChild(1); joinHangoutRoom(room); }
Source:
START private RoundViewModel createViewModel(Sequence updatedSequence) { END int nextNotesPosition = updatedSequence.position(); List<String> notations = getNotations(nextNotesPosition); String statusMessage = getStatusMessage(); return new RoundViewModel(notations, statusMessage); } yeah there would be a Converter that converts in the model from the Domain objects to the ViewModel, hasn't been done yet. I've still been trying to understand the Domain stuff you wrote :-). // edit by atual

Target:
private RoundViewModel createViewModel(Sequence updatedSequence) { int nextNotesPosition = updatedSequence.position(); List<String> notations = getNotations(nextNotesPosition); String statusMessage = getStatusMessage(updatedSequence); return new RoundViewModel(notations, statusMessage); }
Source:
public boolean isHangoutJoinerAutomationServiceEnabled() { List<AccessibilityServiceInfo> visualFeedbackServices = getVisualFeedbackServices(); for (AccessibilityServiceInfo service : visualFeedbackServices) { START if (service.getId().equalsIgnoreCase(SERVICE_ID)) { END return true; } } return false; } flip the equals? `SERVICE_ID.equals(service.getId())`? why ignoreCase?

Target:
public boolean isHangoutJoinerAutomationServiceEnabled() { List<AccessibilityServiceInfo> visualFeedbackServices = getVisualFeedbackServices(); for (AccessibilityServiceInfo service : visualFeedbackServices) { if (SERVICE_ID.equals(service.getId())) { return true; } } return false; }
Source:
public int onStartCommand(Intent intent, int flags, int startId) { START googleApiClient = new GoogleApiClient.Builder(this) END .addApi(Nearby.MESSAGES_API) .addConnectionCallbacks(connectionCallbacks) .addOnConnectionFailedListener(onConnectionFailedListener) .build(); googleApiClient.connect(); return Service.START_NOT_STICKY; } this should be in `onCreate`

Target:
public int onStartCommand(Intent intent, int flags, int startId) { googleApiClient.connect(); return Service.START_NOT_STICKY; }
Source:
public synchronized Observable<T> attach(Observer<T> observer) { if (observer == null) { throw new DeveloperError("You cannot attach a null observer"); } START if (observers.contains(observer)) { END return this; } observers.add(observer); return this; } Better: if it doesn't contain the observer add it, then `return this` anyway.

Target:
public synchronized Observable<T> attach(Observer<T> observer) { if (observer == null) { throw new DeveloperError("You cannot attach a null observer"); } if (!observers.contains(observer)) { observers.add(observer); } return this; }
Source:
protected void notifyOf(T newValue) { Observer<T>[] observersCopy; synchronized (this) { if (hasNotChanged()) { return; } START observersCopy = observers.toArray(new Observer[observers.size()]); END clearChanged(); } for (int i = observersCopy.length - 1; i >= 0; i--) { observersCopy[i].update(newValue); } } DAT.

Target:
protected synchronized void notifyOf(T newValue) { for (int i = observers.size() - 1; i >= 0; i--) { observers.get(i).update(newValue); } }
Source:
public void showPermanently(String arrowCharacter) { START super.setText(arrowCharacter); END getHandler().removeCallbacks(clearTextRunnable); } There is no need for the `super`

Target:
public void showPermanently(String arrowCharacter) { setText(arrowCharacter); getHandler().removeCallbacks(clearTextRunnable); }
Source:
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int horizontalMargin = getResources().getDimensionPixelOffset(R.dimen.list_item_horizontal_margin); START int verticalMargin = getResources().getDimensionPixelOffset(R.dimen.list_item_vertical_margin); END outRect.left = horizontalMargin; outRect.right = horizontalMargin; outRect.top = verticalMargin; outRect.bottom = verticalMargin; } It would be cleaner to export these two as fields to the decoration class

Target:
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left = horizontalMargin; outRect.right = horizontalMargin; outRect.top = verticalMargin; outRect.bottom = verticalMargin; }
Source:
public void detach(ChannelCreationListener channelCreationListener) { START this.channelCreationListener = ChannelCreationListener.NO_OP; END newChannelName.removeTextChangedListener(channelNameTextWatcher); privateChannelSwitch.setOnCheckedChangeListener(null); createButton.setOnClickListener(null); } What is the purpose of the no_op ? can this listener be called once detached ?

Target:
public void detach(ChannelCreationListener channelCreationListener) { newChannelName.removeTextChangedListener(channelNameTextWatcher); privateChannelSwitch.setOnCheckedChangeListener(null); createButton.setOnClickListener(null); this.channelCreationListener = null; }
Source:
private boolean needsInitialisation() { START return loginService == null && chatService == null && channelService == null && firebaseAnalytics == null; END } wouldn't it be enough that one of these is `null`?

Target:
private boolean needsInitialisation() { return loginService == null || chatService == null || channelService == null || firebaseAnalytics == null; }
Source:
public void testLocation() { JavaPackageInfoSource packageInfo = Roaster.create(JavaPackageInfoSource.class); packageInfo.setPackage("abc"); Assert.assertThat(packageInfo.getStartPosition(), is(0)); START System.out.println(packageInfo); END Assert.assertThat(packageInfo.getEndPosition(), is(20)); //TODO check this Assert.assertThat(packageInfo.getColumnNumber(), is(0)); Assert.assertThat(packageInfo.getLineNumber(), is(1)); } Mind removing this System.out?

Target:
public void testLocation() { JavaPackageInfoSource packageInfo = Roaster.create(JavaPackageInfoSource.class); packageInfo.setPackage("abc"); Assert.assertThat(packageInfo.getStartPosition(), is(0)); Assert.assertThat(packageInfo.getEndPosition(), is(20)); // TODO check this Assert.assertThat(packageInfo.getColumnNumber(), is(0)); Assert.assertThat(packageInfo.getLineNumber(), is(1)); }
Source:
public MethodSource<JavaInterfaceSource> setAbstract(boolean abstrct) { if (abstrct) { START modifiers.addModifier(method, ModifierKeyword.ABSTRACT_KEYWORD); END return this; } else { throw new IllegalStateException("Method interface should be 'abstract'"); } } Call super.setAbstract here? This could avoid having the modifiers attribute declared as protected

Target:
public MethodSource<JavaInterfaceSource> setAbstract(boolean abstrct) { if (abstrct) { return super.setAbstract(abstrct); } else { throw new IllegalStateException("Method interface should be 'abstract'"); } }
Source:
START public static <O extends JavaSource<O>> int getArrayDimension(String name) END { int count = 0; if (name != null) { if (isGeneric(name)) { name = stripGenerics(name); } for (char c : name.toCharArray()) { if (c == '[') { count++; } } } return count; } Why is this method parameterized?

Target:
public static int getArrayDimension(String name) { int count = 0; if (name != null) { if (isGeneric(name)) { name = stripGenerics(name); } for (char c : name.toCharArray()) { if (c == '[') { count++; } } } return count; }
Source:
START public static <O extends JavaSource<O>> int getBasicArrayDimension(String name) END { int count = 0; if (name != null) { for (char c : name.toCharArray()) { if (c == '[') { count++; } } } return count; } Why is this method parameterized?

Target:
public static int getBasicArrayDimension(String name) { int count = 0; if (name != null) { for (char c : name.toCharArray()) { if (c == '[') { count++; } } } return count; }
Source:
private static boolean isSyntheticClass(ClassNode node) { START if ((node.access & Opcodes.ACC_SYNTHETIC) == Opcodes.ACC_SYNTHETIC) { return true; } return false; END } ```suggestion return (node.access & Opcodes.ACC_SYNTHETIC) == Opcodes.ACC_SYNTHETIC); ```

Target:
private static boolean isSyntheticClass(ClassNode node) { return ((node.access & Opcodes.ACC_SYNTHETIC) == Opcodes.ACC_SYNTHETIC); }
Source:
static String getVarName(Path path) { return "Var_" + Hashing.sha256() START .hashString(MorePaths.pathWithUnixSeparators(path.getFileName()), Charsets.UTF_8) END .toString() .substring(0, 10); } why `MorePaths.pathWithUnixSeparators`? `getFileName` should include only the name of the file without separators

Target:
static String getVarName(Path path) { return "Var_" + Hashing.sha256().hashString(path.getFileName().toString(), Charsets.UTF_8); }
Source:
public Optional<Path> getCompilerOutputPath(TargetNode<? extends JvmLibraryArg, ?> targetNode) { BuildTarget buildTarget = targetNode.getBuildTarget(); Path compilerOutputPath = DefaultJavaLibrary.getClassesDir(buildTarget, projectFilesystem); START return Optional.ofNullable(compilerOutputPath); END } This should be `Optional.of()`

Target:
public Optional<Path> getCompilerOutputPath(TargetNode<? extends JvmLibraryArg, ?> targetNode) { BuildTarget buildTarget = targetNode.getBuildTarget(); Path compilerOutputPath = DefaultJavaLibrary.getClassesDir(buildTarget, projectFilesystem); return Optional.of(compilerOutputPath); }
Source:
protected CompileToJarStepFactory buildCompileStepFactory() { return new KotlincToJarStepFactory( Preconditions.checkNotNull(kotlinBuckConfig).getKotlinc(), extraKotlincArguments, EMPTY_EXTRA_CLASSPATH, START getJavac(), javacOptions, javacOptionsAmender); END } style nit. one line per argument

Target:
protected CompileToJarStepFactory buildCompileStepFactory() { return new KotlincToJarStepFactory( Preconditions.checkNotNull(kotlinBuckConfig).getKotlinc(), extraKotlincArguments, EMPTY_EXTRA_CLASSPATH, getJavac(), Preconditions.checkNotNull(javacOptions), javacOptionsAmender); }
Source:
public void shouldCompileMixedJavaAndKotlinSources() throws Exception { START KotlinTestAssumptions.assumeCompilerSupportsMixedSources(); END ProjectWorkspace.ProcessResult buildResult = workspace.runBuckCommand("build", "//com/example/mixed:example"); buildResult.assertSuccess("Build should have succeeded."); } Can we just use junit's `@Ignore` annotation and link it with a github issue for bumping the compiler? Something like `@Ingore("https....github/issues/1234")`

Target:
public void shouldCompileMixedJavaAndKotlinSources() throws Exception { ProjectWorkspace.ProcessResult buildResult = workspace.runBuckCommand("build", "//com/example/mixed:example"); buildResult.assertSuccess("Build should have succeeded."); }
Source:
public void testAndroidKotlinLibraryMixedSourcesCompilation() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); KotlinTestAssumptions.assumeCompilerAvailable(workspace.asCell().getBuckConfig()); START KotlinTestAssumptions.assumeCompilerSupportsMixedSources(); END ProcessResult result = workspace.runBuckBuild("//kotlin/com/sample/lib:lib_mixed_sources"); result.assertSuccess(); } Can we just use junit's `@Ignore` annotation and link it with a github issue for bumping the compiler? Something like `@Ingore("https....github/issues/1234")`

Target:
public void testAndroidKotlinLibraryMixedSourcesCompilation() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); KotlinTestAssumptions.assumeCompilerAvailable(workspace.asCell().getBuckConfig()); ProcessResult result = workspace.runBuckBuild("//kotlin/com/sample/lib:lib_mixed_sources"); result.assertSuccess(); }
Source:
private Model constructModel() { File file = path.toFile(); Model model = new Model(); model.setModelVersion(POM_MODEL_VERSION); if (publishable.getPomTemplate().isPresent()) { model = constructModel(publishable.getPomTemplate().get().toFile(), model); } if (file.isFile()) { Model fromFile = constructModel(file, model); START model = merge(model, fromFile); END } return model; } `constructModel` already called `merge` up there.

Target:
private Model constructModel() { File file = path.toFile(); Model model = new Model(); model.setModelVersion(POM_MODEL_VERSION); if (publishable.getPomTemplate().isPresent()) { model = constructModel(publishable.getPomTemplate().get().toFile(), model); } if (file.isFile()) { model = constructModel(file, model); } return model; }
Source:
public static Locator createLocatorFromPathComponents(String tenantId, String... parts) throws IllegalArgumentException { if(StringUtils.isEmpty(tenantId) || parts == null) START throw new IllegalArgumentException("'tenantId' is null or empty OR 'parts' is null."); END return new Locator(tenantId + METRIC_TOKEN_SEPARATOR + StringUtils.join(parts, METRIC_TOKEN_SEPARATOR)); } why are we throwing an exception here instead of logging an error? what will happen to the thread if an exception is thrown? will the server go down? i'm fine with checking inputs when received from the outside parties, but adding exceptions to this code seems dangerous without knowing the consequences. am i missing something?

Target:
public static Locator createLocatorFromPathComponents(String tenantId, String... parts) throws IllegalArgumentException { if(StringUtils.isEmpty(tenantId) || parts == null) log.error("'tenantId' is null or empty OR 'parts' is null."); return new Locator(tenantId + METRIC_TOKEN_SEPARATOR + StringUtils.join(parts, METRIC_TOKEN_SEPARATOR)); }
Source:
public void insertLocator(Locator locator) throws IOException { Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { MutationBatch mutationBatch = AstyanaxIO.getKeyspace().prepareMutationBatch(); AstyanaxWriter.getInstance().insertLocator(locator, mutationBatch); mutationBatch.execute(); } catch (Exception e) { throw new IOException(e); } finally { START if ( timer != null ) { END timer.stop(); } } } why do you need this null check?

Target:
public void insertLocator(Locator locator) throws IOException { Timer.Context timer = Instrumentation.getWriteTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); try { MutationBatch mutationBatch = AstyanaxIO.getKeyspace().prepareMutationBatch(); AstyanaxWriter.getInstance().insertLocator(locator, mutationBatch); mutationBatch.execute(); } catch (Exception e) { throw new IOException(e); } finally { timer.stop(); } }
Source:
public Set<Locator> getLocators(RollupExecutionContext executionContext) { Set<Locator> locators = new HashSet<Locator>(); try { // get a list of all locators to rollup for a shard locators.addAll(IOContainer.fromConfig().getLocatorIO().getLocators(getShard())); START locatorsPerShard.update(locators.size()); END } catch (Throwable e) { executionContext.markUnsuccessful(e); log.error("Failed reading locators for slot: " + getParentSlot(), e); } return locators; } Can you add `log.error` to this `catch` statement too?

Target:
public Set<Locator> getLocators(RollupExecutionContext executionContext) { Set<Locator> locators = new HashSet<Locator>(); try { // get a list of all locators to rollup for a shard locators.addAll(IOContainer.fromConfig().getLocatorIO().getLocators(getShard())); locatorsPerShard.update(locators.size()); } catch (Throwable e) { log.error("Failed reading locators for slot: " + getParentSlot(), e); executionContext.markUnsuccessful(e); } return locators; }
Source:
public static void sendErrorResponse(ChannelHandlerContext ctx, FullHttpRequest request, List<ErrorResponse.ErrorData> validationErrors, HttpResponseStatus status) { try { String responseBody = new ObjectMapper().writeValueAsString(new ErrorResponse(validationErrors)); sendResponse(ctx, request, responseBody, status); } catch (IOException e) { START log.warn("Error preparing response", e); END sendErrorResponse(ctx, request, "Error preparing response", HttpResponseStatus.INTERNAL_SERVER_ERROR); } } should this be error rather than warn? We are sending back a 500 to the user.

Target:
public static void sendErrorResponse(ChannelHandlerContext ctx, FullHttpRequest request, List<ErrorResponse.ErrorData> validationErrors, HttpResponseStatus status) { try { String responseBody = new ObjectMapper().writeValueAsString(new ErrorResponse(validationErrors)); sendResponse(ctx, request, responseBody, status); } catch (IOException e) { log.error("Error preparing response", e); sendErrorResponse(ctx, request, "Error preparing response", HttpResponseStatus.INTERNAL_SERVER_ERROR); } }
Source:
public boolean hasDelayedMetrics(long ingestTime) { START if ( getDelayTime(ingestTime) > TRACKER_DELAYED_METRICS_MILLIS ) { END return true; } else { return false; } } Its probably a matter of preference, but you can just do `return getDelayTime(ingestTime) > TRACKER_DELAYED_METRICS_MILLIS`

Target:
public boolean hasDelayedMetrics(long ingestTime) { return getDelayTime(ingestTime) > TRACKER_DELAYED_METRICS_MILLIS; }
Source:
final public void run() { int sleepMillis = config.getIntegerProperty(CoreConfig.EXCESS_ENUM_READER_SLEEP); // Loop and periodically read the table from Cassandra while (true) { try { Set<Locator> excess = IOContainer.fromConfig().getExcessEnumIO().getExcessEnumMetrics(); synchronized (this) { excessEnumMetrics = excess; START } END readMeter.mark(); Thread.sleep(sleepMillis); } catch (Exception e) { log.error("ExcessEnumReader failed with exception " + e); readErrMeter.mark(); } } } is this necessary? I thought assignments are atomic operations.

Target:
final public void run() { int sleepMillis = config.getIntegerProperty(CoreConfig.EXCESS_ENUM_READER_SLEEP); // Loop and periodically read the table from Cassandra while (true) { try { Set<Locator> excess = IOContainer.fromConfig().getExcessEnumIO().getExcessEnumMetrics(); excessEnumMetrics = excess; readMeter.mark(); Thread.sleep(sleepMillis); } catch (Exception e) { log.error("ExcessEnumReader failed with exception " + e); readErrMeter.mark(); } } }
Source:
START public AbstractMetricsRW(Clock clock) { END this.clock = clock; } Why public and not protected?

Target:
protected AbstractMetricsRW(Clock clock) { this.clock = clock; }