*/
package org.sonar.ce.task.projectanalysis.duplication;
-import static com.google.common.collect.FluentIterable.from;
-import static com.google.common.collect.Iterables.isEmpty;
-import static java.util.Objects.requireNonNull;
-import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY;
-import static org.sonar.api.measures.CoreMetrics.DUPLICATED_BLOCKS_KEY;
-import static org.sonar.api.measures.CoreMetrics.DUPLICATED_FILES_KEY;
-import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY;
-import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_KEY;
-import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
-import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableList;
import java.util.HashSet;
import java.util.Set;
-
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-
-import org.sonar.ce.task.projectanalysis.component.Component;
-import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableList;
+import static com.google.common.collect.FluentIterable.from;
+import static com.google.common.collect.Iterables.isEmpty;
+import static java.util.Objects.requireNonNull;
+import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY;
+import static org.sonar.api.measures.CoreMetrics.DUPLICATED_BLOCKS_KEY;
+import static org.sonar.api.measures.CoreMetrics.DUPLICATED_FILES_KEY;
+import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY;
+import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_KEY;
+import static org.sonar.api.measures.CoreMetrics.LINES_KEY;
+import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY;
public class DuplicationMeasures {
protected final ImmutableList<Formula> formulas;
// use a set to count lines only once
Set<Integer> duplicatedLineNumbers = new HashSet<>();
- long blocks = 0;
+ int blocks = 0;
for (Duplication duplication : duplications) {
blocks++;
addLines(duplication.getOriginal(), duplicatedLineNumbers);
if (!periodHolder.hasPeriod()) {
return;
}
- Double unresolvedVariations = (double) currentCounters.counterForPeriod().unresolved;
+ double unresolvedVariations = (double) currentCounters.counterForPeriod().unresolved;
measureRepository.add(component, metricRepository.getByKey(NEW_VIOLATIONS_KEY), Measure.newMeasureBuilder()
.setVariation(unresolvedVariations)
.createNoValue());
boolean srcHashUpdated = !srcHash.equals(previousDto.getSrcHash());
String revision = computeRevision(latestChangeWithRevision);
boolean revisionUpdated = !ObjectUtils.equals(revision, previousDto.getRevision());
- boolean lineHashesVersionUpdated = !previousDto.getLineHashesVersion().equals(lineHashesVersion);
+ boolean lineHashesVersionUpdated = previousDto.getLineHashesVersion() != lineHashesVersion;
if (binaryDataUpdated || srcHashUpdated || revisionUpdated || lineHashesVersionUpdated) {
previousDto
.setBinaryData(binaryData)
}
private void persistNewIssue(IssueMapper mapper, DefaultIssue issue) {
- Integer ruleId = ruleRepository.getByKey(issue.ruleKey()).getId();
+ int ruleId = ruleRepository.getByKey(issue.ruleKey()).getId();
IssueDto dto = IssueDto.toDtoForComputationInsert(issue, ruleId, system2.now());
mapper.insert(dto);
}
}
}
- /**
- * Partition by 1000 elements a list of input and execute a consumer on each part.
- *
- * The goal is to prevent issue with ORACLE when there's more than 1000 elements in a 'in ('X', 'Y', ...)'
- * and with MsSQL when there's more than 2000 parameters in a query
- *
- * @param inputs the whole list of elements to be partitioned
- * @param sqlCaller a {@link Function} which calls the SQL update/delete and returns the number of updated/deleted rows.
- * @param partitionSizeManipulations the function that computes the number of usages of a partition, for example
- * {@code partitionSize -> partitionSize / 2} when the partition of elements
- * in used twice in the SQL request.
- * @return the total number of updated/deleted rows (computed as the sum of the values returned by {@code sqlCaller}).
- */
- public static <INPUT extends Comparable<INPUT>> int executeLargeUpdates(Collection<INPUT> inputs, Function<List<INPUT>, Integer> sqlCaller,
- IntFunction<Integer> partitionSizeManipulations) {
- Iterable<List<INPUT>> partitions = toUniqueAndSortedPartitions(inputs, partitionSizeManipulations);
- Integer res = 0;
- for (List<INPUT> partition : partitions) {
- res += sqlCaller.apply(partition);
- }
- return res;
- }
-
/**
* Ensure values {@code inputs} are unique (which avoids useless arguments) and sorted before creating the partition.
*/
session.getMapper(DuplicationMapper.class).batchInsert(dto);
}
- /**
- * @param componentUUid uuid of the component
- */
public List<DuplicationUnitDto> selectComponent(DbSession session, String componentUuid, String analysisUuid) {
return session.getMapper(DuplicationMapper.class).selectComponent(componentUuid, analysisUuid);
}
private String dataType;
private String dataHash;
private String revision;
+ @Nullable
private Integer lineHashesVersion;
- public Integer getLineHashesVersion() {
+ public int getLineHashesVersion() {
return lineHashesVersion != null ? lineHashesVersion : LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue();
}
public class ProgrammaticLogbackValve extends LogbackValve {
@Override
- public void startInternal() throws LifecycleException {
+ public synchronized void startInternal() throws LifecycleException {
try {
// direct coupling with LogbackValve implementation
FieldUtils.writeField(this, "scheduledExecutorService", ExecutorServiceUtil.newScheduledExecutorService(), true);
for (Map.Entry<String, Object> entry : token.entrySet()) {
jwtBuilder.claim(entry.getKey(), entry.getValue());
}
- jwtBuilder.setExpiration(new Date(now + expirationTimeInSeconds * 1000))
+ jwtBuilder.setExpiration(new Date(now + expirationTimeInSeconds * 1_000L))
.signWith(SIGNATURE_ALGORITHM, secretKey);
return jwtBuilder.compact();
}
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
+import java.util.OptionalLong;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
boolean startInclusive;
PeriodStart createdAfter = query.createdAfter();
if (createdAfter == null) {
- Optional<Long> minDate = getMinCreatedAt(filters, esQuery);
+ OptionalLong minDate = getMinCreatedAt(filters, esQuery);
if (!minDate.isPresent()) {
return Optional.empty();
}
- startTime = minDate.get();
+ startTime = minDate.getAsLong();
startInclusive = true;
} else {
startTime = createdAfter.date().getTime();
return Optional.of(dateHistogram);
}
- private Optional<Long> getMinCreatedAt(Map<String, QueryBuilder> filters, QueryBuilder esQuery) {
+ private OptionalLong getMinCreatedAt(Map<String, QueryBuilder> filters, QueryBuilder esQuery) {
String facetNameAndField = CREATED_AT.getFieldName();
SearchRequestBuilder esRequest = client
.prepareSearch(INDEX_TYPE_ISSUE)
esRequest.addAggregation(AggregationBuilders.min(facetNameAndField).field(facetNameAndField));
Min minValue = esRequest.get().getAggregations().get(facetNameAndField);
- Double actualValue = minValue.getValue();
- if (actualValue.isInfinite()) {
- return Optional.empty();
+ double actualValue = minValue.getValue();
+ if (Double.isInfinite(actualValue)) {
+ return OptionalLong.empty();
}
- return Optional.of(actualValue.longValue());
+ return OptionalLong.of((long)actualValue);
}
private void addAssignedToMeFacetIfNeeded(SearchRequestBuilder builder, SearchOptions options, IssueQuery query, Map<String, QueryBuilder> filters, QueryBuilder queryBuilder) {
}
private static String formatPercent(long amount) {
- return format(Locale.ENGLISH, "%.1f%%", 100 * amount * 1.0D / 100L);
+ return format(Locale.ENGLISH, "%.1f%%", 100.0 * amount * 1.0 / 100.0);
}
}
OrganizationDto organization = support.getOrganization(dbSession, request.getOrganization());
userSession.checkPermission(PROVISION_PROJECTS, organization);
String visibility = request.getVisibility();
- Boolean changeToPrivate = visibility == null ? dbClient.organizationDao().getNewProjectPrivate(dbSession, organization) : "private".equals(visibility);
+ boolean changeToPrivate = visibility == null ? dbClient.organizationDao().getNewProjectPrivate(dbSession, organization) : "private".equals(visibility);
support.checkCanUpdateProjectsVisibility(organization, changeToPrivate);
ComponentDto componentDto = componentUpdater.create(dbSession, newComponentBuilder()
private Optional<ComponentDto> getProjectByKeyOrId(DbSession dbSession, String component) {
try {
- Long componentId = Long.parseLong(component);
+ long componentId = Long.parseLong(component);
return ofNullable(dbClient.componentDao().selectById(dbSession, componentId).orElse(null));
} catch (NumberFormatException e) {
return ofNullable(dbClient.componentDao().selectByKey(dbSession, component).orElse(null));
private Optional<ComponentDto> loadComponent(DbSession dbSession, String component) {
try {
- Long componentId = Long.parseLong(component);
+ long componentId = Long.parseLong(component);
return Optional.ofNullable(dbClient.componentDao().selectById(dbSession, componentId).orElse(null));
} catch (NumberFormatException e) {
return Optional.ofNullable(dbClient.componentDao().selectByKey(dbSession, component).orElse(null));
.setExampleValue(UUID_EXAMPLE_01);
action.createParam(PARAM_QUALITY_PROFILE)
- .setDescription("Quality profile name to export. If left empty, the default profile for the language is exported.",
- PARAM_QUALITY_PROFILE)
+ .setDescription("Quality profile name to export. If left empty, the default profile for the language is exported.")
.setDeprecatedKey("name", "6.6")
.setExampleValue("My Sonar way");
RulesDefinition.NewRule rule = repo.createRule(CommonRuleKeys.INSUFFICIENT_BRANCH_COVERAGE);
rule.setName("Branches should have sufficient coverage by tests")
.addTags("bad-practice")
- .setHtmlDescription("An issue is created on a file as soon as the branch coverage on this file is less than the required threshold."
+ .setHtmlDescription("An issue is created on a file as soon as the branch coverage on this file is less than the required threshold. "
+ "It gives the number of branches to be covered in order to reach the required threshold.")
.setDebtRemediationFunction(rule.debtRemediationFunctions().linear("5min"))
.setGapDescription("number of uncovered conditions")
query.setOrganization(wsSupport.getOrganizationByKey(dbSession, organizationKey));
return;
}
- OrganizationDto organization = checkFoundWithOptional(dbClient.organizationDao().selectByUuid(dbSession, profile.getOrganizationUuid()), "No organization with UUID ",
+ OrganizationDto organization = checkFoundWithOptional(dbClient.organizationDao().selectByUuid(dbSession, profile.getOrganizationUuid()), "No organization with UUID %s",
profile.getOrganizationUuid());
if (organizationKey != null) {
OrganizationDto inputOrganization = checkFoundWithOptional(dbClient.organizationDao().selectByKey(dbSession, organizationKey), "No organization with key '%s'",
.setExampleValue("java8,security");
action.createParam(PARAM_MARKDOWN_NOTE)
- .setDescription("Optional note in markdown format. Use empty value to remove current note. Note is not changed" +
+ .setDescription("Optional note in markdown format. Use empty value to remove current note. Note is not changed " +
"if the parameter is not set.")
.setExampleValue("my *note*");
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("list_definitions")
.setDescription("List settings definitions.<br>" +
- "Requires 'Browse' permission when a component is specified<br/>",
+ "Requires 'Browse' permission when a component is specified<br/>" +
"To access licensed settings, authentication is required<br/>" +
"To access secured settings, one of the following permissions is required: " +
"<ul>" +
.setDescription("List settings values.<br>" +
"If no value has been set for a setting, then the default value is returned.<br>" +
"The settings from conf/sonar.properties are excluded from results.<br>" +
- "Requires 'Browse' or 'Execute Analysis' permission when a component is specified<br/>",
+ "Requires 'Browse' or 'Execute Analysis' permission when a component is specified.<br/>" +
"To access licensed settings, authentication is required<br/>" +
"To access secured settings, one of the following permissions is required: " +
"<ul>" +
action.createParam(KEY_PARAM)
.setRequired(true)
.setMaximumLength(KEY_PARAM_MAXIMUN_LENGTH)
- .setDescription("The key of the webhook to be deleted,"+
+ .setDescription("The key of the webhook to be deleted, "+
"auto-generated value can be obtained through api/webhooks/create or api/webhooks/list")
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(KEY_PARAM)
.setRequired(true)
.setMaximumLength(KEY_PARAM_MAXIMUN_LENGTH)
- .setDescription("The key of the webhook to be updated,"+
+ .setDescription("The key of the webhook to be updated, "+
"auto-generated value can be obtained through api/webhooks/create or api/webhooks/list")
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_WEBHOOK)
.setSince("7.1")
- .setDescription("Key of the webhook that triggered those deliveries," +
+ .setDescription("Key of the webhook that triggered those deliveries, " +
"auto-generated value that can be obtained through api/webhooks/create or api/webhooks/list")
.setExampleValue(UUID_EXAMPLE_02);
.defaultValue(Boolean.toString(CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE))
.name("Force user authentication")
.description(
- "Forcing user authentication prevents anonymous users from accessing the SonarQube UI, or project data via the Web API."
+ "Forcing user authentication prevents anonymous users from accessing the SonarQube UI, or project data via the Web API. "
+ "Some specific read-only Web APIs, including those required to prompt authentication, are still available anonymously.")
.type(PropertyType.BOOLEAN)
.category(CoreProperties.CATEGORY_SECURITY)
List<LoadedActiveRule> ruleList = new LinkedList<>();
int page = 1;
int pageSize = 500;
- int loaded = 0;
+ long loaded = 0;
while (true) {
GetRequest getRequest = new GetRequest(getUrl(qualityProfileKey, page, pageSize));
/**
* Removes everything in the specified group.
- *
- * @param group The group name.
*/
public Storage<V> clear(Object key) {
resetKey(key);
* Returns the set of cache keys associated with this group.
* TODO implement a lazy-loading equivalent with Iterator/Iterable
*
- * @param group The group.
* @return The set of cache keys for this group.
*/
@SuppressWarnings("rawtypes")
* <li>TextLineNumber.CENTER
* <li>TextLineNumber.RIGHT (default)
* </ul>
- * @param currentLineForeground the Color used to render the current line
*/
public void setDigitAlignment(float digitAlignment) {
this.digitAlignment = digitAlignment > 1.0f ? 1.0f : digitAlignment < 0.0f ? -1.0f : digitAlignment;