auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testRegister() { //test one url abstractRegistry.register(mockUrl); assert abstractRegistry.getRegistered().contains(mockUrl); //test multiple urls abstractRegistry.getRegistered().clear(); List<URL> urlList = getList(); for (URL url : urlList) { abstractRegistry.register(url); } Assert.assertThat(abstractRegistry.getRegistered().size(), Matchers.equalTo(urlList.size())); }

Target:
pls. consider to enhance `registerTest`, `unregisterTest`, `subscribeTest`, `unsubsribeTest`, etc, instead of introducing new test methods. But your method naming is more recommended, pls. stick to it.
Source:
private String pullRequestBaseToDisplayName(@Nullable String pullRequestBase) { return pullRequestBase != null ? pullRequestBase : "default branch"; }

Target:
![Code Smell](https://sonarsource.github.io/sonar-github/code_smell.png 'Code Smell') Code Smell: Make "pullRequestBaseToDisplayName" a "static" method. ([squid:S2325](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2325)) [See it in SonarQube](https://next.sonarqube.com/sonarqube/project/issues?id=org.sonarsource.sonarqube%3Asonarqube&branch=feature%2Fjanos%2FSONAR-10365%2Fmigrate-data&issues=AWF65MK3GUleEzPZFu4E&open=AWF65MK3GUleEzPZFu4E) [ISSUE_KEY]: AWF65MK3GUleEzPZFu4E
Source:
public Long getCreatedAt() { return createdAt; }

Target:
should be primitive `long`
Source:
private static Map<String, String> fromJson(String json) { Gson gson = new GsonBuilder().disableHtmlEscaping().setPrettyPrinting().create(); try { return gson.fromJson(decode(json, UTF_8.name()), JSON_MAP_TYPE); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } }

Target:
is pretty printing really needed ?
Source:
private void doDefinition(WebService.NewAction action) { action.setDescription("Search for a collection of relevant rules matching a specified query.<br/>" + "Since 5.5, following fields in the response have been deprecated :" + "<ul>" + "<li>\"effortToFixDescription\" becomes \"gapDescription\"</li>" + "<li>\"debtRemFnCoeff\" becomes \"remFnGapMultiplier\"</li>" + "<li>\"defaultDebtRemFnCoeff\" becomes \"defaultRemFnGapMultiplier\"</li>" + "<li>\"debtRemFnOffset\" becomes \"remFnBaseEffort\"</li>" + "<li>\"defaultDebtRemFnOffset\" becomes \"defaultRemFnBaseEffort\"</li>" + "<li>\"debtOverloaded\" becomes \"remFnOverloaded\"</li>" + "</ul>" + "In 7.1, a new field 'scope' has been added to the response.") .setResponseExample(getClass().getResource("search-example.json")) .setSince("4.4") .setHandler(this); // Rule-specific search parameters defineRuleSearchParameters(action); }

Target:
Please move this line to the changelog of the action : ``` action.setDescription("Search for a collection...") .setChangelog(new Change("7.1", "new field 'scope' has been added to the response") .setChangelog(new Change("7.1", "field 'scope' has been added to 'f' parameter") ```
Source:
private Optional<ScmInfo> getScmInfoForComponent(Component component) { ScannerReport.Changesets changesets = scannerReportReader.readChangesets(component.getReportAttributes().getRef()); if (changesets != null) { if (changesets.getChangesetCount() == 0) { return generateAndMergeDb(component, changesets.getCopyFromPrevious()); } return getScmInfoFromReport(component, changesets); } LOGGER.trace("No SCM info for file '{}'", component.getKey()); return generateAndMergeDb(component, false); }

Target:
Why `false` ? If the scanner does not send any SCM information, why the DB data could not be reused ?
Source:
private Organization loadOrganization(ScannerReport.Metadata reportMetadata) { try (DbSession dbSession = dbClient.openSession(false)) { analysisMetadata.setOrganizationsEnabled(organizationFlags.isEnabled(dbSession)); Organization organization = toOrganization(dbSession, ceTask.getOrganizationUuid()); checkOrganizationKeyConsistency(reportMetadata, organization); analysisMetadata.setOrganization(organization); return organization; } }

Target:
minor: I would not call `organizationFlags.isEnabled` before `checkOrganizationKeyConsistency`, if the check fails, we uselessly made a call to DB
Source:
private Organization toOrganization(DbSession dbSession, String organizationUuid) { analysisMetadata.setOrganizationsEnabled(organizationFlags.isEnabled(dbSession)); Optional<OrganizationDto> organizationDto = dbClient.organizationDao().selectByUuid(dbSession, organizationUuid); checkState(organizationDto.isPresent(), "Organization with uuid '%s' can't be found", organizationUuid); return Organization.from(organizationDto.get()); }

Target:
`analysisMetadata.setOrganizationsEnabled` is already called on line 117 and it really does not belong to a method called `toOrganization` which really should be static
Source:
public void setQualityGate(QualityGate g) { // fail fast requireNonNull(g); checkState(qualityGate == null, "QualityGateHolder can be initialized only once"); this.qualityGate = Optional.of(g); }

Target:
![MAJOR](https://sonarsource.github.io/sonar-github/severity-major.png 'Severity: MAJOR') Remove this null-check of an "Optional". [![rule](https://sonarsource.github.io/sonar-github/rule.png)](https://next.sonarqube.com/sonarqube/coding_rules#rule_key=squid%3AS2789)
Source:
private void validateQualityGate(DbSession dbSession, OrganizationDto organizationDto, String name) { List<String> errors = new ArrayList<>(); checkQualityGateDoesNotAlreadyExist(dbSession, organizationDto, name, errors); checkRequest(errors.isEmpty(), errors); }

Target:
Please remove checkRequest => it's no more needed as there's now only one error that can be generated in `checkQualityGateDoesNotAlreadyExist`. Moreoever, `checkQualityGateDoesNotAlreadyExist` should then directly throw an IllegalArgumentException instead of adding an error to the list of error.
Source:
public QualityGateDto selectBuiltIn(DbSession dbSession) { QualityGateDto qualityGateDto = mapper(dbSession).selectBuiltIn(); checkState(qualityGateDto != null, "Builtin quality gate is missing."); return qualityGateDto; }

Target:
AFAIK, such check should not be in DAO (it probably should be in QualityGateFinder).
Source:
public void after() { underTest.stop(); db.executeUpdateSql("delete from metrics"); db.commit(); }

Target:
Why are you removing metrics at the end ? It's not already done by DbTester ?
Source:
public void define(Context context) { System.err.println("Fake GOV WS being setup: " + actions.length); NewController controller = context.createController("api/fake_gov"); Arrays.stream(actions).forEach(action -> action.define(controller)); controller.done(); }

Target:
Shouldn't this be in a Logger (so we may see it in web.log during a test ?)
Source:
private void uninstallPlugins(Set<String> pluginsToRemove) { for (String pluginKey : pluginsToRemove) { editionPluginUninstaller.uninstall(pluginKey); } }

Target:
can't `foreach` be used here?
Source:
public boolean hasDownloads() { return !getDownloadedPluginFilenames().isEmpty(); }

Target:
why public?
Source:
public List<String> getDownloadedPluginFilenames() { List<String> names = new ArrayList<>(); for (File file : listPlugins(this.downloadDir)) { names.add(file.getName()); } return names; }

Target:
why public?
Source:
protected void ensurePluginIsInstalled(String key) { if (!serverPluginRepository.hasPlugin(key)) { throw new IllegalArgumentException(format("Plugin [%s] is not installed", key)); } }

Target:
should be private
Source:
private 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; }

Target:
![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)
Source:
public void size_rolling_policy_has_large_max_files_if_property_is_zero() throws IOException { 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); }

Target:
missing test for when property is less than zero. Code would also put large max file
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 match(tracking, LineAndLineHashKey::new, true); // 2. match issues with same rule, same message and same line hash match(tracking, LineHashAndMessageKey::new, true); return tracking; }

Target:
The factory is always the same. If you don't want to keep the INSTANCE, what about creating as a static member field?
Source:
private void closeIssuesForDeletedComponentUuids(Set<String> deletedComponentUuids) { DiskCache<DefaultIssue>.DiskAppender cacheAppender = issueCache.newAppender(); try { for (String deletedComponentUuid : deletedComponentUuids) { List<DefaultIssue> issues = issuesLoader.loadForComponentUuid(deletedComponentUuid, false); for (DefaultIssue issue : issues) { issue.setBeingClosed(true); // TODO should be renamed issue.setOnDisabledRule(false); issueLifecycle.doAutomaticTransition(issue); cacheAppender.append(issue); } } } finally { cacheAppender.close(); } }

Target:
A UT should be added to check that changelog are correctly loaded
Source:
public void handle(Request request, Response response) { try (DbSession dbSession = dbClient.openSession(false)) { long conditionId = request.mandatoryParamAsLong(PARAM_ID); OrganizationDto organization = wsSupport.getOrganization(dbSession); userSession.checkPermission(ADMINISTER_QUALITY_GATES, organization); dbClient.gateConditionDao().delete(wsSupport.getCondition(dbSession, conditionId), dbSession); dbSession.commit(); response.noContent(); } }

Target:
Should be done before opening a db session - for to fail fast.
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Analysis)) { return false; } Analysis analysis = (Analysis) o; return Objects.equal(projectUuid, analysis.projectUuid) && Objects.equal(ceTaskUuid, analysis.ceTaskUuid) && Objects.equal(analysisUuid, analysis.analysisUuid); }

Target:
this makes equals support subclasses. This is not necessarily the intent
Source:
public void deleteByQProfileAndUser(DbSession dbSession, QProfileDto profile, UserDto user) { mapper(dbSession).delete(profile.getKee(), user.getLogin()); }

Target:
![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)
Source:
public void start() { INSTANCE = this; }

Target:
Won't fix.
Source:
public void stop() { INSTANCE = null; }

Target:
Won't fix.
Source:
private String getDbVendor() { return dbClient.getDatabase().getDialect().getId().toLowerCase(Locale.ENGLISH); }

Target:
🐜 I would suggest not to lower the case, since it our own database ids are lowercase anyways.
Source:
public 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(); }

Target:
🐭 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.
Source:
public void setMetadata(String id, String value) { esClient.prepareIndex(MetadataIndexDefinition.INDEX_TYPE_METADATA) .setId(id) .setSource(MetadataIndexDefinition.FIELD_VALUE, value) .setRefreshPolicy(REFRESH_IMMEDIATE) .get(); }

Target:
🐭 Same here: I'd slightly prefer `private`.
Source:
public void close() { try { hazelcastCluster.close(); } catch (HazelcastInstanceNotActiveException e) { // hazelcastCluster may be already closed by the shutdown hook LOGGER.debug("Unable to close Hazelcast cluster", e); } }

Target:
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
Source:
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(removeBranchFromKey(dto.getDbKey()), dto.uuid()); } } }

Target:
![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)
Source:
public void setPrivateForRootComponentUuid(DbSession session, String projectUuid, boolean isPrivate) { mapper(session).setPrivateForRootComponentUuid(projectUuid, isPrivate); session.getMapper(BranchMapper.class).selectByProjectUuid(projectUuid) .stream() .filter(branch -> !projectUuid.equals(branch.getUuid())) .forEach(branch -> mapper(session).setPrivateForRootComponentUuid(branch.getUuid(), isPrivate)); }

Target:
I thought we said that you'll move it to the WS ?
Source:
private static Optional<String> getBranchName(Optional<Branch> branchOpt) { if (!branchOpt.isPresent()) { return Optional.empty(); } Branch branch = branchOpt.get(); if (!branch.isLegacyFeature() && !branch.isMain()) { return branch.getName(); } return Optional.empty(); }

Target:
![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)
Source:
public ComponentWsRequest setComponentKey(@Nullable String componentKey) { return setComponent(componentKey); }

Target:
![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)
Source:
public List<UuidWithProjectUuidDto> selectAllViewsAndSubViews(DbSession session) { return mapper(session).selectUuidsForQualifiers(Qualifiers.VIEW, Qualifiers.SUBVIEW, Qualifiers.APP); }

Target:
This method is only used to index view
Source:
public MetricDto insert(DbSession session, MetricDto dto) { mapper(session).insert(validate(dto)); return dto; }

Target:
AFAIK, It's not the responsability of DAO to validate dto. This should be in a higher layer, a XXXUpdater or the WS
Source:
private String getPluginKeyAndResourcePath(HttpServletRequest request) { return StringUtils.substringAfter(request.getRequestURI(), request.getContextPath() + request.getServletPath() + "/"); }

Target:
![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)
Source:
public void setUp() { ws = new WsActionTester(new ShowAction(db.getDbClient(), parser, duplicationsJsonWriter, userSessionRule, TestComponentFinder.from(db))); db.getDbClient().metricDao().insert(db.getSession(), dataMetric); db.commit(); }

Target:
This can be inline with line 58
Source:
private ComponentDto getByKey(DbSession dbSession, String key, String label) { return checkComponent(() -> dbClient.componentDao().selectByKey(dbSession, key), () -> format("%s key '%s' not found", label, key)); }

Target:
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...)`?
Source:
private List<UserDto> findUsers(DbSession dbSession, PermissionQuery query) { List<Integer> orderedIds = new ArrayList<>(dbClient.userPermissionDao().selectUserIdsByQuery(dbSession, query)); return Ordering.explicit(orderedIds).onResultOf(UserDto::getId).immutableSortedCopy(dbClient.userDao().selectByIds(dbSession, orderedIds)); }

Target:
why create a new list and not immutable?
Source:
public LoggerContext configure(Props props) { LoggerContext ctx = helper.getRootContext(); ctx.reset(); configureRootLogger(props); helper.apply(logLevelConfig, props); helper.enableJulChangePropagation(ctx); configureDirectToConsoleLoggers(ctx, STARTUP_LOGGER_NAME); extendConfigure(); return ctx; }

Target:
what is the reason behind moving call to enableJulChangePropagation after configuring the loggers in SLF4J?
Source:
public TrackedIssue setComponentKey(String componentKey) { Preconditions.checkArgument(StringUtils.countMatches(componentKey, ":") <= 1, "componentKey should not have branch"); this.componentKey = componentKey; return this; }

Target:
":" is allowed in projet keys
Source:
public void returns_project_visibility_public() { OrganizationDto organization = dbTester.organizations().insert(); dbClient.organizationDao().setNewProjectPrivate(dbTester.getSession(), organization, false); dbTester.commit(); userSession.logIn().addPermission(PROVISION_PROJECTS, organization); assertJson(executeRequest(organization).getInput()).isSimilarTo("{\"organization\": {\"projectVisibility\": \"public\"}}"); }

Target:
what about replacing lines 221 and 222 by a method in `OrganizationDbTester`?
Source:
public void handle(Request request, Response response) throws Exception { verifySystemAdministrator(); List<RuleKey> disabledTemplateAndCustomRuleKeys = null; 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(); }

Target:
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)
Source:
private static String convertPatternsToString(List<String> input) { StringBuilder toStringBuilder = new StringBuilder(); if (input.isEmpty()) { return ""; } if (input.size() == 1) { return toStringBuilder.append(input.get(0)).toString(); } return toStringBuilder.append(input.get(0)).append(", ...").toString(); }

Target:
suggestion: rename to `output`
Source:
private void writeResponse(Request request, Response response, OrganizationDto organization, GroupDto group) { WsUserGroups.CreateWsResponse.Builder respBuilder = WsUserGroups.CreateWsResponse.newBuilder(); respBuilder.setGroup(toProtobuf(organization, group, 0)); writeProtobuf(respBuilder.build(), request, response); }

Target:
remark: I had the feedback that we should call this classes `CreateResponse` without Ws. I don't have a strong opinion on this…
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) { throw new RuntimeException("Failed to insert rows into table SCHEMA_MIGRATIONS", e); } }

Target:
![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)
Source:
protected void configureModule() { add( CeTaskProcessorRepositoryImpl.class, CeWorkerImpl.class, CeWorkerFactoryImpl.class, CeProcessingSchedulerExecutorServiceImpl.class, CeProcessingSchedulerImpl.class); }

Target:
there is no more need for any instance of `CeWorkerImpl` to be in the container `CeWorkerImpl` instances are now produced by the `CeWorkerFactory`
Source:
public void stop() { hzInstance.getReplicatedMap(CLIENT_UUIDS).remove(hzInstance.getLocalEndpoint().getUuid()); // Shutdown Hazelcast properly hzInstance.shutdown(); }

Target:
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
Source:
private void initCe() { processingScheduler.startScheduling(); cleaningScheduler.startScheduling(); ceDistributedInformation.broadcastWorkerUUIDs(); }

Target:
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
Source:
public boolean hasNext() { for (;;) { if (currentChunk != null && currentChunk.hasNext()) { return true; } else if (iteratorOverChunks.hasNext()) { currentChunk = nextChunk(); } else { return false; } } }

Target:
The `else` conditions can be dropped because of `return`. That will decrease cognitive complexity!
Source:
public List<QualityProfile> load(String projectKey, @Nullable String profileName) { 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()); }

Target:
These `+`s could also be changed to `append`s.
Source:
public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn().checkIsSystemAdministrator(); GroupsWsResponse groupsWsResponse = doHandle(toGroupsRequest(request)); writeProtobuf(groupsWsResponse, request, response); }

Target:
no limit on the page size?
Source:
private QualityProfileDto dto(String key) { return new QualityProfileDto() { { setKey(key); } @Override public String toString() { return getKey(); } }; }

Target:
Strange way to call simply `new QualityProfileDto().setKey(key)`. Do I miss something?
Source:
public void name_requires_either_component_or_defaults() throws Exception { thrown.expect(BadRequestException.class); thrown.expectMessage("The name parameter requires either projectKey or defaults to be set."); SearchWsRequest request = new SearchWsRequest() .setProfileName("bla"); SearchDataLoader.validateRequest(request); }

Target:
if exception is thrown by `validateRequest`, `thrown` configuration should be done right before `validateRequest` is called
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") .setSince("6.2") .setInternal(true); }

Target:
this line should not be in the builder method IMO because it's very context sensitive
Source:
public 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 + ".*"); } }); }

Target:
it should be `private`, welcome to the java world :)
Source:
public List<QualityProfileDto> selectByNameAndLanguages(String name, Collection<String> languageKeys, DbSession session) { return executeLargeInputs(languageKeys, input -> mapper(session).selectByNameAndLanguages(name, input)); }

Target:
![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)
Source:
public void onConnect(String room, String serverAddress) { debugView.showPermanently(getString(R.string.connected)); switchableView.setDisplayedChild(1); lastServerPreferences.saveLastConnectedServer(serverAddress); joinHangoutRoom(room); }

Target:
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
Source:
private RoundViewModel createViewModel(Sequence updatedSequence) { int nextNotesPosition = updatedSequence.position(); List<String> notations = getNotations(nextNotesPosition); String statusMessage = getStatusMessage(); return new RoundViewModel(notations, statusMessage); }

Target:
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
Source:
public boolean isHangoutJoinerAutomationServiceEnabled() { List<AccessibilityServiceInfo> visualFeedbackServices = getVisualFeedbackServices(); for (AccessibilityServiceInfo service : visualFeedbackServices) { if (service.getId().equalsIgnoreCase(SERVICE_ID)) { return true; } } return false; }

Target:
flip the equals? `SERVICE_ID.equals(service.getId())`? why ignoreCase?
Source:
public int onStartCommand(Intent intent, int flags, int startId) { googleApiClient = new GoogleApiClient.Builder(this) .addApi(Nearby.MESSAGES_API) .addConnectionCallbacks(connectionCallbacks) .addOnConnectionFailedListener(onConnectionFailedListener) .build(); googleApiClient.connect(); return Service.START_NOT_STICKY; }

Target:
this should be in `onCreate`
Source:
public synchronized Observable<T> attach(Observer<T> observer) { if (observer == null) { throw new DeveloperError("You cannot attach a null observer"); } if (observers.contains(observer)) { return this; } observers.add(observer); return this; }

Target:
Better: if it doesn't contain the observer add it, then `return this` anyway.
Source:
protected void notifyOf(T newValue) { Observer<T>[] observersCopy; synchronized (this) { if (hasNotChanged()) { return; } observersCopy = observers.toArray(new Observer[observers.size()]); clearChanged(); } for (int i = observersCopy.length - 1; i >= 0; i--) { observersCopy[i].update(newValue); } }

Target:
DAT.
Source:
public void showPermanently(String arrowCharacter) { super.setText(arrowCharacter); getHandler().removeCallbacks(clearTextRunnable); }

Target:
There is no need for the `super`
Source:
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int horizontalMargin = getResources().getDimensionPixelOffset(R.dimen.list_item_horizontal_margin); int verticalMargin = getResources().getDimensionPixelOffset(R.dimen.list_item_vertical_margin); outRect.left = horizontalMargin; outRect.right = horizontalMargin; outRect.top = verticalMargin; outRect.bottom = verticalMargin; }

Target:
It would be cleaner to export these two as fields to the decoration class
Source:
public void detach(ChannelCreationListener channelCreationListener) { this.channelCreationListener = ChannelCreationListener.NO_OP; newChannelName.removeTextChangedListener(channelNameTextWatcher); privateChannelSwitch.setOnCheckedChangeListener(null); createButton.setOnClickListener(null); }

Target:
What is the purpose of the no_op ? can this listener be called once detached ?
Source:
private boolean needsInitialisation() { return loginService == null && chatService == null && channelService == null && firebaseAnalytics == null; }

Target:
wouldn't it be enough that one of these is `null`?
Source:
public void testLocation() { JavaPackageInfoSource packageInfo = Roaster.create(JavaPackageInfoSource.class); packageInfo.setPackage("abc"); Assert.assertThat(packageInfo.getStartPosition(), is(0)); System.out.println(packageInfo); Assert.assertThat(packageInfo.getEndPosition(), is(20)); //TODO check this Assert.assertThat(packageInfo.getColumnNumber(), is(0)); Assert.assertThat(packageInfo.getLineNumber(), is(1)); }

Target:
Mind removing this System.out?
Source:
public MethodSource<JavaInterfaceSource> setAbstract(boolean abstrct) { if (abstrct) { modifiers.addModifier(method, ModifierKeyword.ABSTRACT_KEYWORD); return this; } else { throw new IllegalStateException("Method interface should be 'abstract'"); } }

Target:
Call super.setAbstract here? This could avoid having the modifiers attribute declared as protected
Source:
public static <O extends JavaSource<O>> 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; }

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

Target:
Why is this method parameterized?
Source:
private static boolean isSyntheticClass(ClassNode node) { if ((node.access & Opcodes.ACC_SYNTHETIC) == Opcodes.ACC_SYNTHETIC) { return true; } return false; }

Target:
```suggestion return (node.access & Opcodes.ACC_SYNTHETIC) == Opcodes.ACC_SYNTHETIC); ```
Source:
static String getVarName(Path path) { return "Var_" + Hashing.sha256() .hashString(MorePaths.pathWithUnixSeparators(path.getFileName()), Charsets.UTF_8) .toString() .substring(0, 10); }

Target:
why `MorePaths.pathWithUnixSeparators`? `getFileName` should include only the name of the file without separators
Source:
public Optional<Path> getCompilerOutputPath(TargetNode<? extends JvmLibraryArg, ?> targetNode) { BuildTarget buildTarget = targetNode.getBuildTarget(); Path compilerOutputPath = DefaultJavaLibrary.getClassesDir(buildTarget, projectFilesystem); return Optional.ofNullable(compilerOutputPath); }

Target:
This should be `Optional.of()`
Source:
protected CompileToJarStepFactory buildCompileStepFactory() { return new KotlincToJarStepFactory( Preconditions.checkNotNull(kotlinBuckConfig).getKotlinc(), extraKotlincArguments, EMPTY_EXTRA_CLASSPATH, getJavac(), javacOptions, javacOptionsAmender); }

Target:
style nit. one line per argument
Source:
public void shouldCompileMixedJavaAndKotlinSources() throws Exception { KotlinTestAssumptions.assumeCompilerSupportsMixedSources(); ProjectWorkspace.ProcessResult buildResult = workspace.runBuckCommand("build", "//com/example/mixed:example"); buildResult.assertSuccess("Build should have succeeded."); }

Target:
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")`
Source:
public void testAndroidKotlinLibraryMixedSourcesCompilation() throws Exception { AssumeAndroidPlatform.assumeSdkIsAvailable(); KotlinTestAssumptions.assumeCompilerAvailable(workspace.asCell().getBuckConfig()); KotlinTestAssumptions.assumeCompilerSupportsMixedSources(); ProcessResult result = workspace.runBuckBuild("//kotlin/com/sample/lib:lib_mixed_sources"); result.assertSuccess(); }

Target:
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")`
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); model = merge(model, fromFile); } return model; }

Target:
`constructModel` already called `merge` up there.
Source:
public static Locator createLocatorFromPathComponents(String tenantId, String... parts) throws IllegalArgumentException { if(StringUtils.isEmpty(tenantId) || parts == null) throw new IllegalArgumentException("'tenantId' is null or empty OR 'parts' is null."); return new Locator(tenantId + METRIC_TOKEN_SEPARATOR + StringUtils.join(parts, METRIC_TOKEN_SEPARATOR)); }

Target:
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?
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 { if ( timer != null ) { timer.stop(); } } }

Target:
why do you need this null check?
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())); locatorsPerShard.update(locators.size()); } catch (Throwable e) { executionContext.markUnsuccessful(e); log.error("Failed reading locators for slot: " + getParentSlot(), e); } return locators; }

Target:
Can you add `log.error` to this `catch` statement too?
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) { log.warn("Error preparing response", e); sendErrorResponse(ctx, request, "Error preparing response", HttpResponseStatus.INTERNAL_SERVER_ERROR); } }

Target:
should this be error rather than warn? We are sending back a 500 to the user.
Source:
public boolean hasDelayedMetrics(long ingestTime) { if ( getDelayTime(ingestTime) > TRACKER_DELAYED_METRICS_MILLIS ) { return true; } else { return false; } }

Target:
Its probably a matter of preference, but you can just do `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; } readMeter.mark(); Thread.sleep(sleepMillis); } catch (Exception e) { log.error("ExcessEnumReader failed with exception " + e); readErrMeter.mark(); } } }

Target:
is this necessary? I thought assignments are atomic operations.
Source:
public AbstractMetricsRW(Clock clock) { this.clock = clock; }

Target:
Why public and not protected?
Source:
public int processLocator(int rollCount, RollupExecutionContext executionContext, RollupBatchWriter rollupBatchWriter, Locator locator) { if (log.isTraceEnabled()) log.trace("Rolling up (check,metric,dimension) for (gran,slot,shard) {}", locator, parentSlotKey); try { executeRollupForLocator(executionContext, rollupBatchWriter, locator); rollCount += 1; } catch (Throwable any) { // continue on, but log the problem so that we can fix things later. executionContext.markUnsuccessful(any); executionContext.decrementReadCounter(); log.error(any.getMessage(), any); log.error("BasicRollup failed for at {}", parentSlotKey, serverTime); } return rollCount; }

Target:
Do we want to expose this out to caller? I.e: allowing them to skip Instrumentation? I'm thinking we may not want to. So make it protected (test classes can still call)?
Source:
public static AggregatedPayload createPayload(String json) throws JsonSyntaxException { AggregatedPayload payload = new Gson().fromJson(json, AggregatedPayload.class); return payload; }

Target:
We should use `JsonParseException` here if you want to declare the exception.
Source:
public static List<AggregatedPayload> createBundleList(String json) throws JsonSyntaxException { Gson gson = new Gson(); JsonParser parser = new JsonParser(); JsonArray jArray = parser.parse(json).getAsJsonArray(); ArrayList<AggregatedPayload> bundleList = new ArrayList<AggregatedPayload>(); for(JsonElement obj : jArray ) { AggregatedPayload bundle = gson.fromJson( obj , AggregatedPayload.class); bundleList.add(bundle); } return bundleList; }

Target:
JsonParseException
Source:
protected Points.Point createPoint( Long timestamp, Object value ) { if( value instanceof Rollup || value instanceof String) return new Points.Point( timestamp, value); else return new Points.Point( timestamp, new SimpleNumber( value ) ); }

Target:
I missed bounded type parameters already :-) I don't know if it would be better to create separate versions of `createPoint` methods? Like this? ``` protected Points.Point createPoint(Long timestamp, Rollup value); protected Points.Point createPoint(Long timestamp, String value); protected Points.Point createPoint(Long timestamp, Object value); ```
Source:
public ScheduleContext(long currentTimeMillis, Collection<Integer> managedShards) { this.scheduleTime = currentTimeMillis; this.shardStateManager = new ShardStateManager(managedShards, asMillisecondsSinceEpochTicker()); this.lockManager = new NoOpShardLockManager(); this.clock = new DefaultClockImpl(); registerMBean(); }

Target:
why repeat this? calling this() should be the correct thing to do, just don't call registerMBean() in the subsequent constructor.
Source:
public Map<Locator, MetricData> getEnumMetricDataForRangeForLocatorList(final List<Locator> locators, final Range range, final Granularity gran) { String columnFamily = CassandraModel.getColumnFamily(BluefloodEnumRollup.class, gran).getName(); if ( columnFamily == null ) { throw new IllegalArgumentException("invalid granularity: " + gran); } return getEnumMetricDataForRangeForLocatorList(locators, range, columnFamily); }

Target:
Does this ever happen?
Source:
public static Tracker getInstance() { register(); return instance; }

Target:
Do we need this method? It seems like people should just call Tracker.register() ?
Source:
public void waitForRollups() throws InterruptedException { Thread.currentThread().sleep(LOCATOR_WAIT_FOR_ALL_SECS * 1000); }

Target:
Someone could totally mess with us by calling this repeatedly. We shouldnt expose these kinda methods. If you want control, have LOCATOR_WAIT_FOR_ALL_SECS to be set in a separate constructor. For tests you can set it to zero if you dont want it to wait. You can make it non-static that would let you set it in constructor. Its just an integer field.
Source:
protected int sizeOfSize() { return 1; }

Target:
do we want to make these abstract?
Source:
protected String[] getBodyArray( HttpResponse response ) throws IOException { StringWriter sw = new StringWriter(); IOUtils.copy( response.getEntity().getContent(), sw ); IOUtils.closeQuietly( response.getEntity().getContent() ); return sw.toString().split( System.lineSeparator() ); }

Target:
Can you do closeQuietly in a finally block?
Source:
private double meanOfPointCollectionRoll( Collection<Points.Point<BasicRollup>> fullPoints ) { long sum = 0; int count = 0; for( Points.Point<BasicRollup> p : fullPoints ) { sum += p.getData().getAverage().toLong(); count++; } return sum / count; }

Target:
Why do you need count? Cant you use fullPoints.size?
Source:
private static void checkConfiguration() { if (!config.getBooleanProperty(CoreConfig.INGEST_MODE)) { log.error("Ingestion mode not enabled. Please check your configuration"); System.exit(StopReasons.INCORRECT_CONFIGURATION); } log.info("Configuration is good"); boolean useZookeeper = false; log.info("Using zookeeper? " + useZookeeper); }

Target:
can we delete the boolean and this log statement? I think that's the only use of the variable.
Source:
public void testNoCassandraHostsFailsValidation() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, ""); // when BluefloodServiceStarterException ex = null; try { BluefloodServiceStarter.validateCassandraHosts(); } catch (BluefloodServiceStarterException e) { ex = e; } // then assertNotNull(ex); assertEquals(-1, ex.getStatus()); }

Target:
You could do the same thing by doing `@Test(expected = BluefloodServiceStarterException.class)` I would say checking for exit code equals -1 is not that important to do.
Source:
public void testCassandraHostWithoutPortFailsValidation() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.CASSANDRA_HOSTS, "127.0.0.1"); // when BluefloodServiceStarterException ex = null; try { BluefloodServiceStarter.validateCassandraHosts(); } catch (BluefloodServiceStarterException e) { ex = e; } // then assertNotNull(ex); assertEquals(-1, ex.getStatus()); }

Target:
Can use `@Test(expected = ...)`, see above.
Source:
public void testRollupModeEnabled() { // given Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.ROLLUP_MODE, "true"); String[] args = new String[0]; // when BluefloodServiceStarterException ex = null; try { BluefloodServiceStarter.main(args); } catch (BluefloodServiceStarterException e) { ex = e; } // then assertNull(ex); }

Target:
We can simplify this test method this way: ``` @Test public void testRollupModeEnabledShouldNotFail() throws Exception { Configuration config = Configuration.getInstance(); config.setProperty(CoreConfig.ROLLUP_MODE, "true"); String[] args = new String[0]; BluefloodServiceStarter.main(args); } ```
Source:
public static boolean containsKey(String key) { return props.containsKey(key); }

Target:
Do these need to be static?
Source:
public static void clearProperty(Enum<? extends ConfigDefaults> name) { clearProperty(name.toString()); }

Target:
Do these need to be static?
Source:
public int getNumPoints() { int enumCount = 0; Set keySet = hashedEnumValues2Count.keySet(); Iterator itr = keySet.iterator(); while(itr.hasNext()){ enumCount+= hashedEnumValues2Count.get(itr.next()); } return enumCount; }

Target:
wouldn't it be clearer to iterate through the values with the foreach syntax, something like this: for (Long value: hashedEnumValues2Count.values()): enumCount += value;
Source:
private Map<Long, String> getEnumValueFromHashes(ColumnList<Long> enumValues) { HashMap<Long,String> hash2enumValues = new HashMap<Long, String>(); for (Column<Long> col: enumValues) { hash2enumValues.put(col.getName(), col.getStringValue()); } return hash2enumValues; }

Target:
This method is useful and should be made public. I am going to need it in my PR. And what happened to the "getColumnsFromEnumCF" method? I am going to need that also. Or should I just add that on my own?
Source:
private static <T> Points<T> asPoints(Class<T> type, long initialTime, long timeDelta, T... values) { Points<T> points = new Points<T>(); long time = initialTime; for (T v : values) { points.add(new Points.Point<T>(time, v)); time += timeDelta; } return points; }

Target:
You've added multiple copies of this method. Can it be put in a utility class somewhere?
Source:
public void insertPreaggreatedMetrics(Collection<IMetric> metrics) throws Exception { try { AstyanaxWriter.getInstance().insertMetrics(metrics, CassandraModel.CF_METRICS_PREAGGREGATED_FULL); } catch (ConnectionException e) { throw new IOException(e); } }

Target:
What code changes in this class is throwing more exceptions other than IOException that cause you to change this throws definition?
Source:
public ByteBuffer toByteBuffer(Object o) { try { byte type = typeOf(o); byte[] buf = new byte[sizeOf(o, type, VERSION_2_TIMER)]; serializeFullResMetric(o, buf); ByteBuffer out = ByteBuffer.wrap(buf); return out; } catch(IOException e) { throw new RuntimeException(e); } }

Target:
It seems a bit strange to pass in the `timer` version while serializing non-timer rollups like gauges, counters etc. What do you think about having two overloaded methods named `sizeOf` with one accepting just two arguments i.e `(Object, Type)` which will be used by all non-timer rollup types and then the other one with `timerVersion` as the third argument, which gets called by the timer serializer?
Source:
public boolean shouldPersist(Metric metric) throws Exception { boolean areStringMetricsDropped = Configuration.getInstance().getBooleanProperty(CoreConfig.STRING_METRICS_DROPPED); if(areStringMetricsDropped) { return false; } else { String currentValue = String.valueOf(metric.getMetricValue()); final String lastValue = AstyanaxReader.getInstance().getLastStringValue(metric.getLocator()); return lastValue == null || !currentValue.equals(lastValue); } }

Target:
perhaps this should be a static field on the class
Source:
private String getUnit(Metric metric) { return metric.getUnit(); }

Target:
Should make static.
Source:
public <C> Builder<A, C> withFunction(AsyncFunction<B, C> function) { Preconditions.checkNotNull(function); ArrayList<AsyncFunction<?, ?>> copy = new ArrayList<AsyncFunction<?, ?>>(this.functions); return new Builder<A, C>(copy); }

Target:
does this add the function to the list of `functions`?
Source:
public boolean areTTLsForced() { final Configuration config = Configuration.getInstance(); return config.getBooleanProperty(TtlConfig.ARE_TTLS_FORCED); }

Target:
this method could return a `public static final` that gets set during the static initialization. it would avoid map lookup and object creation for every call.
Source:
public static final boolean areTTLsForced() { final Configuration config = Configuration.getInstance(); return config.getBooleanProperty(TtlConfig.ARE_TTLS_FORCED); }

Target:
`Configuration.getStringProperty()` (the base method in that class), does at least one map looking, more on overrides.
Source:
public static void main(String[] args) throws Exception { String[] preLoadClasses = { "javax.servlet.Filter", "javax.servlet.DispatcherType", }; for (String className : preLoadClasses) { Class.forName(className); } new IngestApplication().run(args); }

Target:
Not sure why this code is over here.
Source:
public void update(long when, int shard) { Long current = updates.get(shard); if (current == null) { updates.put(shard, when); } else { if (when > current) { updates.put(shard, when); } } }

Target:
Why are the shard updates taken only when the collection time is greater than the last update time? We allow uncontrolled update in the current setting right?
Source:
public void decrementReadCounter(long count) { readCounter.addAndGet((-1) * count); owner.interrupt(); }

Target:
unary minus would make this prettier.