JavaColorizerFormat.class,
// issues
+ IssueTrackingDecorator.class,
+ IssueTracking.class,
IssueHandlers.class,
IssueFilters.class,
CountOpenIssuesDecorator.class,
VersionEventsSensor.class,
CheckAlertThresholds.class,
GenerateAlertEvents.class,
- ViolationsDecorator.class,
- IssueTrackingDecorator.class,
- WeightedViolationsDecorator.class,
- ViolationsDensityDecorator.class,
LineCoverageDecorator.class,
CoverageDecorator.class,
BranchCoverageDecorator.class,
DirectoriesDecorator.class,
FilesDecorator.class,
ReviewNotifications.class,
- ReviewWorkflowDecorator.class,
- ManualMeasureDecorator.class,
- ManualViolationInjector.class,
- ViolationSeverityUpdater.class,
IndexProjectPostJob.class,
- ReviewsMeasuresDecorator.class,
+ ManualMeasureDecorator.class,
// time machine
TendencyDecorator.class,
VariationDecorator.class,
- ViolationTrackingDecorator.class,
- IssueTracking.class,
- ViolationPersisterDecorator.class,
- NewViolationsDecorator.class,
TimeMachineConfigurationPersister.class,
NewCoverageFileAnalyzer.class,
NewItCoverageFileAnalyzer.class,
@DependedUpon
public List<Metric> generatesIssuesMetrics() {
return ImmutableList.of(
- CoreMetrics.ISSUES,
- CoreMetrics.BLOCKER_ISSUES,
- CoreMetrics.CRITICAL_ISSUES,
- CoreMetrics.MAJOR_ISSUES,
- CoreMetrics.MINOR_ISSUES,
- CoreMetrics.INFO_ISSUES,
- CoreMetrics.NEW_ISSUES,
- CoreMetrics.NEW_BLOCKER_ISSUES,
- CoreMetrics.NEW_CRITICAL_ISSUES,
- CoreMetrics.NEW_MAJOR_ISSUES,
- CoreMetrics.NEW_MINOR_ISSUES,
- CoreMetrics.NEW_INFO_ISSUES,
- CoreMetrics.UNASSIGNED_ISSUES,
+ CoreMetrics.VIOLATIONS,
+ CoreMetrics.BLOCKER_VIOLATIONS,
+ CoreMetrics.CRITICAL_VIOLATIONS,
+ CoreMetrics.MAJOR_VIOLATIONS,
+ CoreMetrics.MINOR_VIOLATIONS,
+ CoreMetrics.INFO_VIOLATIONS,
+ CoreMetrics.NEW_VIOLATIONS,
+ CoreMetrics.NEW_BLOCKER_VIOLATIONS,
+ CoreMetrics.NEW_CRITICAL_VIOLATIONS,
+ CoreMetrics.NEW_MAJOR_VIOLATIONS,
+ CoreMetrics.NEW_MINOR_VIOLATIONS,
+ CoreMetrics.NEW_INFO_VIOLATIONS,
CoreMetrics.OPEN_ISSUES,
CoreMetrics.REOPENED_ISSUES,
CoreMetrics.CONFIRMED_ISSUES
Multiset<RulePriority> severityBag = HashMultiset.create();
Map<RulePriority, Multiset<Rule>> rulesPerSeverity = Maps.newHashMap();
ListMultimap<RulePriority, Issue> issuesPerSeverity = ArrayListMultimap.create();
- int countUnassigned = 0;
int countOpen = 0;
int countReopened = 0;
int countConfirmed = 0;
rulesBag.add(rulefinder.findByKey(issue.ruleKey().repository(), issue.ruleKey().rule()));
issuesPerSeverity.put(RulePriority.valueOf(issue.severity()), issue);
- if (issue.assignee() == null) {
- countUnassigned++;
- }
if (Issue.STATUS_OPEN.equals(issue.status())){
countOpen++;
}
saveTotalIssues(context, issues);
saveNewIssues(context, issues, shouldSaveNewMetrics);
- saveMeasure(context, CoreMetrics.UNASSIGNED_ISSUES, countUnassigned);
saveMeasure(context, CoreMetrics.OPEN_ISSUES, countOpen);
saveMeasure(context, CoreMetrics.REOPENED_ISSUES, countReopened);
saveMeasure(context, CoreMetrics.CONFIRMED_ISSUES, countConfirmed);
}
private void saveTotalIssues(DecoratorContext context, Collection<Issue> issues) {
- if (context.getMeasure(CoreMetrics.ISSUES) == null) {
- Collection<Measure> childrenIssues = context.getChildrenMeasures(CoreMetrics.ISSUES);
+ if (context.getMeasure(CoreMetrics.VIOLATIONS) == null) {
+ Collection<Measure> childrenIssues = context.getChildrenMeasures(CoreMetrics.VIOLATIONS);
Double sum = MeasureUtils.sum(true, childrenIssues);
- context.saveMeasure(CoreMetrics.ISSUES, sum + issues.size());
+ context.saveMeasure(CoreMetrics.VIOLATIONS, sum + issues.size());
}
}
private void saveNewIssues(DecoratorContext context, Collection<Issue> issues, boolean shouldSaveNewMetrics) {
if (shouldSaveNewMetrics) {
- Measure measure = new Measure(CoreMetrics.NEW_ISSUES);
+ Measure measure = new Measure(CoreMetrics.NEW_VIOLATIONS);
saveNewIssues(context, measure, issues);
}
}
}
private boolean shouldSaveNewMetrics(DecoratorContext context) {
- return context.getProject().isLatestAnalysis() && context.getMeasure(CoreMetrics.NEW_ISSUES) == null;
+ return context.getProject().isLatestAnalysis() && context.getMeasure(CoreMetrics.NEW_VIOLATIONS) == null;
}
private Collection<Issue> getOpenIssues(Collection<Issue> issues) {
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
-import org.sonar.api.batch.Decorator;
-import org.sonar.api.batch.DecoratorBarriers;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DependedUpon;
+import org.sonar.api.batch.*;
import org.sonar.api.component.ResourcePerspectives;
import org.sonar.api.issue.Issuable;
import org.sonar.api.issue.Issue;
import java.util.Collection;
import java.util.Map;
-@DependedUpon(DecoratorBarriers.END_OF_ISSUES_UPDATES)
+@DependsUpon({DecoratorBarriers.END_OF_VIOLATIONS_GENERATION, DecoratorBarriers.START_VIOLATION_TRACKING})
+@DependedUpon({DecoratorBarriers.END_OF_VIOLATION_TRACKING,DecoratorBarriers.END_OF_ISSUES_UPDATES})
public class IssueTrackingDecorator implements Decorator {
private final IssueCache issueCache;
@DependsUpon
public List<Metric> dependsUponWeightedIissuesAndNcloc() {
- return Arrays.asList(CoreMetrics.WEIGHTED_ISSUES, CoreMetrics.NCLOC);
+ return Arrays.asList(CoreMetrics.WEIGHTED_VIOLATIONS, CoreMetrics.NCLOC);
}
@DependedUpon
public Metric generatesIssuesDensity() {
- return CoreMetrics.ISSUES_DENSITY;
+ return CoreMetrics.VIOLATIONS_DENSITY;
}
public void decorate(Resource resource, DecoratorContext context) {
}
protected boolean shouldDecorateResource(DecoratorContext context) {
- return context.getMeasure(CoreMetrics.ISSUES_DENSITY) == null;
+ return context.getMeasure(CoreMetrics.VIOLATIONS_DENSITY) == null;
}
private void decorateDensity(DecoratorContext context) {
}
private void saveDensity(DecoratorContext context, int ncloc) {
- Measure debt = context.getMeasure(CoreMetrics.WEIGHTED_ISSUES);
+ Measure debt = context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS);
Integer debtValue = 0;
if (MeasureUtils.hasValue(debt)) {
debtValue = debt.getValue().intValue();
}
double density = calculate(debtValue, ncloc);
- context.saveMeasure(CoreMetrics.ISSUES_DENSITY, density);
+ context.saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, density);
}
protected static double calculate(int debt, int ncloc) {
static Metric severityToIssueMetric(RulePriority severity) {
Metric metric;
if (severity.equals(RulePriority.BLOCKER)) {
- metric = CoreMetrics.BLOCKER_ISSUES;
+ metric = CoreMetrics.BLOCKER_VIOLATIONS;
} else if (severity.equals(RulePriority.CRITICAL)) {
- metric = CoreMetrics.CRITICAL_ISSUES;
+ metric = CoreMetrics.CRITICAL_VIOLATIONS;
} else if (severity.equals(RulePriority.MAJOR)) {
- metric = CoreMetrics.MAJOR_ISSUES;
+ metric = CoreMetrics.MAJOR_VIOLATIONS;
} else if (severity.equals(RulePriority.MINOR)) {
- metric = CoreMetrics.MINOR_ISSUES;
+ metric = CoreMetrics.MINOR_VIOLATIONS;
} else if (severity.equals(RulePriority.INFO)) {
- metric = CoreMetrics.INFO_ISSUES;
+ metric = CoreMetrics.INFO_VIOLATIONS;
} else {
throw new IllegalArgumentException("Unsupported severity: " + severity);
}
static Metric severityToNewMetricIssue(RulePriority severity) {
Metric metric;
if (severity.equals(RulePriority.BLOCKER)) {
- metric = CoreMetrics.NEW_BLOCKER_ISSUES;
+ metric = CoreMetrics.NEW_BLOCKER_VIOLATIONS;
} else if (severity.equals(RulePriority.CRITICAL)) {
- metric = CoreMetrics.NEW_CRITICAL_ISSUES;
+ metric = CoreMetrics.NEW_CRITICAL_VIOLATIONS;
} else if (severity.equals(RulePriority.MAJOR)) {
- metric = CoreMetrics.NEW_MAJOR_ISSUES;
+ metric = CoreMetrics.NEW_MAJOR_VIOLATIONS;
} else if (severity.equals(RulePriority.MINOR)) {
- metric = CoreMetrics.NEW_MINOR_ISSUES;
+ metric = CoreMetrics.NEW_MINOR_VIOLATIONS;
} else if (severity.equals(RulePriority.INFO)) {
- metric = CoreMetrics.NEW_INFO_ISSUES;
+ metric = CoreMetrics.NEW_INFO_VIOLATIONS;
} else {
throw new IllegalArgumentException("Unsupported severity: " + severity);
}
@DependsUpon
public List<Metric> dependsUponIssues() {
- return Arrays.asList(CoreMetrics.BLOCKER_ISSUES, CoreMetrics.CRITICAL_ISSUES,
- CoreMetrics.MAJOR_ISSUES, CoreMetrics.MINOR_ISSUES, CoreMetrics.INFO_ISSUES);
+ return Arrays.asList(CoreMetrics.BLOCKER_VIOLATIONS, CoreMetrics.CRITICAL_VIOLATIONS,
+ CoreMetrics.MAJOR_VIOLATIONS, CoreMetrics.MINOR_VIOLATIONS, CoreMetrics.INFO_VIOLATIONS);
}
@DependedUpon
public Metric generatesWeightedIssues() {
- return CoreMetrics.WEIGHTED_ISSUES;
+ return CoreMetrics.WEIGHTED_VIOLATIONS;
}
public boolean shouldExecuteOnProject(Project project) {
}
}
- Measure debtMeasure = new Measure(CoreMetrics.WEIGHTED_ISSUES, debt, KeyValueFormat.format(distribution));
+ Measure debtMeasure = new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, debt, KeyValueFormat.format(distribution));
context.saveMeasure(debtMeasure);
}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import org.slf4j.LoggerFactory;
-import org.sonar.api.batch.Decorator;
-import org.sonar.api.batch.DecoratorBarriers;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DependedUpon;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.RuleFinder;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-import org.sonar.core.review.ReviewDao;
-import org.sonar.core.review.ReviewDto;
-import org.sonar.core.review.ReviewPredicates;
-
-import java.util.Collection;
-
-@DependedUpon(DecoratorBarriers.END_OF_VIOLATIONS_GENERATION)
-public class ManualViolationInjector implements Decorator {
-
- private ReviewDao reviewDao;
- private RuleFinder ruleFinder;
-
- public ManualViolationInjector(ReviewDao reviewDao, RuleFinder ruleFinder) {
- this.reviewDao = reviewDao;
- this.ruleFinder = ruleFinder;
- }
-
- public boolean shouldExecuteOnProject(Project project) {
- return true;
- }
-
- public void decorate(Resource resource, DecoratorContext context) {
- if (resource.getId() != null) {
- Collection<ReviewDto> openReviews = reviewDao.selectOpenByResourceId(resource.getId(),
- ReviewPredicates.status(ReviewDto.STATUS_OPEN),
- ReviewPredicates.manualViolation());
- for (ReviewDto openReview : openReviews) {
- if (openReview.getRuleId() == null) {
- LoggerFactory.getLogger(getClass()).warn("No rule is defined on the review with id: " + openReview.getId());
- }
- if (openReview.getViolationPermanentId() == null) {
- LoggerFactory.getLogger(getClass()).warn("Permanent id of manual violation is missing on the review with id: " + openReview.getId());
- }
- Violation violation = Violation.create(ruleFinder.findById(openReview.getRuleId()), resource);
- violation.setManual(true);
- violation.setLineId(openReview.getLine());
- violation.setPermanentId(openReview.getViolationPermanentId());
- violation.setSwitchedOff(false);
- violation.setCreatedAt(openReview.getCreatedAt());
- violation.setMessage(openReview.getTitle());
- violation.setSeverity(RulePriority.valueOf(openReview.getSeverity()));
- context.saveViolation(violation);
- }
- }
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName();
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Function;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-import org.apache.commons.lang.ObjectUtils;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.api.batch.*;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.resources.ResourceUtils;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.violations.ViolationQuery;
-import org.sonar.batch.index.ResourcePersister;
-import org.sonar.core.DryRunIncompatible;
-import org.sonar.core.review.ReviewDao;
-import org.sonar.core.review.ReviewDto;
-
-import javax.annotation.Nullable;
-import java.util.*;
-
-@DryRunIncompatible
-@DependsUpon(DecoratorBarriers.END_OF_VIOLATION_TRACKING)
-@DependedUpon(ReviewWorkflowDecorator.END_OF_REVIEWS_UPDATES)
-public class ReviewWorkflowDecorator implements Decorator {
-
- public static final String END_OF_REVIEWS_UPDATES = "END_OF_REVIEWS_UPDATES";
-
- private ReviewNotifications notifications;
- private ReviewDao reviewDao;
- private ResourcePersister resourcePersister;
-
- public ReviewWorkflowDecorator(ReviewNotifications notifications, ReviewDao reviewDao, ResourcePersister resourcePersister) {
- this.notifications = notifications;
- this.reviewDao = reviewDao;
- this.resourcePersister = resourcePersister;
- }
-
- public boolean shouldExecuteOnProject(Project project) {
- return project.isLatestAnalysis();
- }
-
- public void decorate(Resource resource, DecoratorContext context) {
- Snapshot snapshot = resourcePersister.getSnapshot(resource);
- if (snapshot != null) {
- Collection<ReviewDto> openReviews = reviewDao.selectOpenByResourceId(snapshot.getResourceId());
- Set<ReviewDto> updated = Sets.newHashSet();
- if (!openReviews.isEmpty()) {
- List<Violation> violations = context.getViolations(ViolationQuery.create().forResource(resource).setSwitchMode(ViolationQuery.SwitchMode.BOTH));
- closeResolvedStandardViolations(openReviews, violations, context.getProject(), resource, updated);
- closeResolvedManualViolations(openReviews, context.getProject(), resource, updated);
- reopenUnresolvedViolations(openReviews, context.getProject(), resource, updated);
- updateReviewInformation(openReviews, violations, updated);
- }
- if (ResourceUtils.isRootProject(resource)) {
- closeReviewsOnDeletedResources((Project) resource, snapshot.getResourceId(), snapshot.getId(), updated);
- }
- persistUpdates(updated);
- }
- }
-
- private void persistUpdates(Set<ReviewDto> updated) {
- if (!updated.isEmpty()) {
- reviewDao.update(updated);
- }
- }
-
- /**
- * Close reviews that relate to resources that have been deleted or renamed.
- */
- private void closeReviewsOnDeletedResources(Project project, int rootProjectId, int rootSnapshotId, Set<ReviewDto> updated) {
- Collection<ReviewDto> reviews = reviewDao.selectOnDeletedResources(rootProjectId, rootSnapshotId);
- for (ReviewDto review : reviews) {
- close(review, project, null);
- updated.add(review);
- }
- }
-
- private void updateReviewInformation(Collection<ReviewDto> openReviews, Collection<Violation> violations, Set<ReviewDto> updated) {
- Map<Integer, Violation> violationsByPermanentId = Maps.newHashMap();
- for (Violation violation : violations) {
- if (violation.getPermanentId()!=null) {
- violationsByPermanentId.put(violation.getPermanentId(), violation);
- }
- }
-
- for (ReviewDto review : openReviews) {
- Violation violation = violationsByPermanentId.get(review.getViolationPermanentId());
- if (violation != null && !hasUpToDateInformation(review, violation)) {
- review.setLine(violation.getLineId());
- review.setTitle(violation.getMessage());
- updated.add(review);
- }
- }
- }
-
- @VisibleForTesting
- static boolean hasUpToDateInformation(ReviewDto review, Violation violation) {
- return StringUtils.equals(review.getTitle(), violation.getMessage()) && ObjectUtils.equals(review.getLine(), violation.getLineId());
- }
-
- private void closeResolvedManualViolations(Collection<ReviewDto> openReviews, Project project, Resource resource, Set<ReviewDto> updated) {
- for (ReviewDto openReview : openReviews) {
- if (openReview.isManualViolation() && ReviewDto.STATUS_RESOLVED.equals(openReview.getStatus())) {
- close(openReview, project, resource);
- updated.add(openReview);
- }
- }
- }
-
- private void closeResolvedStandardViolations(Collection<ReviewDto> openReviews, List<Violation> violations, Project project, Resource resource, Set<ReviewDto> updated) {
- Set<Integer> violationIds = Sets.newHashSet(Collections2.transform(violations, new ViolationToPermanentIdFunction()));
-
- for (ReviewDto openReview : openReviews) {
- if (!openReview.isManualViolation() && !violationIds.contains(openReview.getViolationPermanentId())) {
- close(openReview, project, resource);
- updated.add(openReview);
- }
- }
- }
-
- private void reopenUnresolvedViolations(Collection<ReviewDto> openReviews, Project project, Resource resource, Set<ReviewDto> updated) {
- for (ReviewDto openReview : openReviews) {
- if (ReviewDto.STATUS_RESOLVED.equals(openReview.getStatus()) && !ReviewDto.RESOLUTION_FALSE_POSITIVE.equals(openReview.getResolution())
- && !openReview.isManualViolation()) {
- reopen(openReview, project, resource);
- updated.add(openReview);
- }
- }
- }
-
- private void close(ReviewDto review, Project project, Resource resource) {
- notifications.notifyClosed(review, project, resource);
- review.setStatus(ReviewDto.STATUS_CLOSED);
- review.setUpdatedAt(new Date());
- }
-
- private void reopen(ReviewDto review, Project project, Resource resource) {
- notifications.notifyReopened(review, project, resource);
- review.setStatus(ReviewDto.STATUS_REOPENED);
- review.setResolution(null);
- review.setUpdatedAt(new Date());
- }
-
- private static final class ViolationToPermanentIdFunction implements Function<Violation, Integer> {
- public Integer apply(@Nullable Violation violation) {
- return (violation != null ? violation.getPermanentId() : null);
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.collect.Maps;
-import org.sonar.api.batch.Decorator;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DependedUpon;
-import org.sonar.api.batch.DependsUpon;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.MeasureUtils;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.resources.ResourceUtils;
-import org.sonar.api.rules.Violation;
-import org.sonar.batch.components.PastSnapshot;
-import org.sonar.batch.components.TimeMachineConfiguration;
-import org.sonar.core.review.ReviewDao;
-import org.sonar.core.review.ReviewDto;
-import org.sonar.core.review.ReviewPredicates;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Decorator that creates measures related to reviews.
- *
- * @since 2.14
- */
-@DependsUpon(ReviewWorkflowDecorator.END_OF_REVIEWS_UPDATES)
-public class ReviewsMeasuresDecorator implements Decorator {
-
- private ReviewDao reviewDao;
- private TimeMachineConfiguration timeMachineConfiguration;
-
- public ReviewsMeasuresDecorator(ReviewDao reviewDao, TimeMachineConfiguration timeMachineConfiguration) {
- this.reviewDao = reviewDao;
- this.timeMachineConfiguration = timeMachineConfiguration;
- }
-
- public boolean shouldExecuteOnProject(Project project) {
- return project.isLatestAnalysis();
- }
-
- @DependedUpon
- public Collection<Metric> generatesMetrics() {
- return Arrays.asList(CoreMetrics.ACTIVE_REVIEWS, CoreMetrics.UNASSIGNED_REVIEWS, CoreMetrics.UNPLANNED_REVIEWS, CoreMetrics.FALSE_POSITIVE_REVIEWS,
- CoreMetrics.UNREVIEWED_VIOLATIONS, CoreMetrics.NEW_UNREVIEWED_VIOLATIONS);
- }
-
- @SuppressWarnings({"rawtypes"})
- public void decorate(Resource resource, DecoratorContext context) {
- if (!ResourceUtils.isPersistable(resource) || resource.getId() == null) {
- return;
- }
-
- // Load open reviews (used for counting and also for tracking new violations without a review)
- Collection<ReviewDto> openReviews = reviewDao.selectOpenByResourceId(resource.getId(),
- ReviewPredicates.status(ReviewDto.STATUS_OPEN, ReviewDto.STATUS_REOPENED));
-
- Map<Integer, ReviewDto> openReviewsByViolationPermanentId = Maps.newHashMap();
- int countUnassigned = 0;
- int unplanned = 0;
- for (ReviewDto openReview : openReviews) {
- openReviewsByViolationPermanentId.put(openReview.getViolationPermanentId(), openReview);
- if (openReview.getAssigneeId() == null) {
- countUnassigned++;
- }
- if (openReview.getActionPlanId() == null) {
- unplanned++;
- }
- }
-
- int totalOpenReviews = openReviews.size() + sumChildren(resource, context, CoreMetrics.ACTIVE_REVIEWS);
- context.saveMeasure(CoreMetrics.ACTIVE_REVIEWS, (double) totalOpenReviews);
- context.saveMeasure(CoreMetrics.UNASSIGNED_REVIEWS, (double) (countUnassigned + sumChildren(resource, context, CoreMetrics.UNASSIGNED_REVIEWS)));
- context.saveMeasure(CoreMetrics.UNPLANNED_REVIEWS, (double) (unplanned + sumChildren(resource, context, CoreMetrics.UNPLANNED_REVIEWS)));
-
- Collection<ReviewDto> falsePositives = reviewDao.selectOpenByResourceId(resource.getId(),
- ReviewPredicates.resolution(ReviewDto.RESOLUTION_FALSE_POSITIVE));
-
- context.saveMeasure(CoreMetrics.FALSE_POSITIVE_REVIEWS, (double) (falsePositives.size() + sumChildren(resource, context, CoreMetrics.FALSE_POSITIVE_REVIEWS)));
-
- Double violationsCount = MeasureUtils.getValue(context.getMeasure(CoreMetrics.VIOLATIONS), 0.0);
- context.saveMeasure(CoreMetrics.UNREVIEWED_VIOLATIONS, violationsCount - totalOpenReviews);
-
- trackNewViolationsWithoutReview(context, openReviewsByViolationPermanentId);
- }
-
- protected void trackNewViolationsWithoutReview(DecoratorContext context, Map<Integer, ReviewDto> openReviewsByViolationPermanentIds) {
- List<Violation> violations = context.getViolations();
- Measure measure = new Measure(CoreMetrics.NEW_UNREVIEWED_VIOLATIONS);
- for (PastSnapshot pastSnapshot : timeMachineConfiguration.getProjectPastSnapshots()) {
- int newUnreviewedViolations = countNewUnreviewedViolationsForSnapshot(pastSnapshot, violations, openReviewsByViolationPermanentIds);
- int variationIndex = pastSnapshot.getIndex();
- Collection<Measure> children = context.getChildrenMeasures(CoreMetrics.NEW_UNREVIEWED_VIOLATIONS);
- double sumNewUnreviewedViolations = MeasureUtils.sumOnVariation(true, variationIndex, children) + newUnreviewedViolations;
- measure.setVariation(variationIndex, sumNewUnreviewedViolations);
- }
- context.saveMeasure(measure);
- }
-
- protected int countNewUnreviewedViolationsForSnapshot(PastSnapshot pastSnapshot, List<Violation> violations,
- Map<Integer, ReviewDto> openReviewsByViolationPermanentIds) {
- Date targetDate = pastSnapshot.getTargetDate();
- int newViolationCount = 0;
- int newReviewedViolationCount = 0;
- for (Violation violation : violations) {
- if (isAfter(violation, targetDate)) {
- newViolationCount += 1;
- if (openReviewsByViolationPermanentIds.get(violation.getPermanentId()) != null) {
- newReviewedViolationCount += 1;
- }
- }
- }
- return newViolationCount - newReviewedViolationCount;
- }
-
- private int sumChildren(Resource<?> resource, DecoratorContext context, Metric metric) {
- int sum = 0;
- if (!ResourceUtils.isFile(resource)) {
- sum = MeasureUtils.sum(true, context.getChildrenMeasures(metric)).intValue();
- }
- return sum;
- }
-
- private boolean isAfter(Violation violation, Date date) {
- if (date == null) {
- return true;
- }
- return violation.getCreatedAt() != null && violation.getCreatedAt().after(date);
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.rules.RulePriority;
-
-final class SeverityUtils {
- private SeverityUtils() {
- // only static methods
- }
-
- static Metric severityToViolationMetric(RulePriority severity) {
- Metric metric;
- if (severity.equals(RulePriority.BLOCKER)) {
- metric = CoreMetrics.BLOCKER_VIOLATIONS;
- } else if (severity.equals(RulePriority.CRITICAL)) {
- metric = CoreMetrics.CRITICAL_VIOLATIONS;
- } else if (severity.equals(RulePriority.MAJOR)) {
- metric = CoreMetrics.MAJOR_VIOLATIONS;
- } else if (severity.equals(RulePriority.MINOR)) {
- metric = CoreMetrics.MINOR_VIOLATIONS;
- } else if (severity.equals(RulePriority.INFO)) {
- metric = CoreMetrics.INFO_VIOLATIONS;
- } else {
- throw new IllegalArgumentException("Unsupported severity: " + severity);
- }
- return metric;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.collect.Maps;
-import org.sonar.api.batch.*;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-import org.sonar.core.review.ReviewDao;
-import org.sonar.core.review.ReviewDto;
-import org.sonar.core.review.ReviewPredicates;
-import org.sonar.plugins.core.timemachine.ViolationTrackingDecorator;
-
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Severity of violations can be explicitely changed by end-users. In this case the severity is fixed and must not be changed
- * by rule engines.
- *
- * @since 2.13
- */
-@DependsUpon(DecoratorBarriers.START_VIOLATION_TRACKING)
-@DependedUpon(DecoratorBarriers.END_OF_VIOLATION_TRACKING)
-public class ViolationSeverityUpdater implements Decorator {
-
- private ReviewDao reviewDao;
-
- public ViolationSeverityUpdater(ReviewDao reviewDao) {
- this.reviewDao = reviewDao;
- }
-
- public boolean shouldExecuteOnProject(Project project) {
- return true;
- }
-
- @DependsUpon
- public Class dependsUponViolationTracking() {
- // permanent ids of violations have been updated, so we can link them with reviews
- return ViolationTrackingDecorator.class;
- }
-
- public void decorate(Resource resource, DecoratorContext context) {
- if (resource.getId()==null) {
- return;
- }
- Map<Integer, Violation> violationMap = filterViolationsPerPermanent(context.getViolations());
- if (!violationMap.isEmpty()) {
- Collection<ReviewDto> reviews = selectReviewsWithManualSeverity(resource.getId());
- for (ReviewDto review : reviews) {
- Violation violation = violationMap.get(review.getViolationPermanentId());
- if (violation != null) {
- violation.setSeverity(RulePriority.valueOf(review.getSeverity()));
- }
- }
- }
- }
-
- private Collection<ReviewDto> selectReviewsWithManualSeverity(long resourceId) {
- return reviewDao.selectOpenByResourceId(resourceId, ReviewPredicates.manualSeverity());
- }
-
- private Map<Integer, Violation> filterViolationsPerPermanent(List<Violation> violations) {
- Map<Integer, Violation> result = Maps.newHashMap();
- for (Violation violation : violations) {
- if (violation.getPermanentId() != null) {
- result.put(violation.getPermanentId(), violation);
- }
- }
- return result;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName();
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.collect.HashMultiset;
-import com.google.common.collect.Maps;
-import com.google.common.collect.Multiset;
-import org.sonar.api.batch.*;
-import org.sonar.api.measures.*;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-@DependsUpon(DecoratorBarriers.END_OF_VIOLATION_TRACKING)
-public class ViolationsDecorator implements Decorator {
-
- public boolean shouldExecuteOnProject(Project project) {
- return true;
- }
-
- @DependedUpon
- public List<Metric> generatesViolationsMetrics() {
- return Arrays.asList(CoreMetrics.VIOLATIONS,
- CoreMetrics.BLOCKER_VIOLATIONS,
- CoreMetrics.CRITICAL_VIOLATIONS,
- CoreMetrics.MAJOR_VIOLATIONS,
- CoreMetrics.MINOR_VIOLATIONS,
- CoreMetrics.INFO_VIOLATIONS);
- }
-
- public void decorate(Resource resource, DecoratorContext context) {
- computeTotalViolations(context);
- computeViolationsPerSeverities(context);
- computeViolationsPerRules(context);
- }
-
- private void computeTotalViolations(DecoratorContext context) {
- if (context.getMeasure(CoreMetrics.VIOLATIONS) == null) {
- Collection<Measure> childrenViolations = context.getChildrenMeasures(CoreMetrics.VIOLATIONS);
- Double sum = MeasureUtils.sum(true, childrenViolations);
- context.saveMeasure(CoreMetrics.VIOLATIONS, sum + context.getViolations().size());
- }
- }
-
- private void computeViolationsPerSeverities(DecoratorContext context) {
- Multiset<RulePriority> severitiesBag = HashMultiset.create();
- for (Violation violation : context.getViolations()) {
- severitiesBag.add(violation.getSeverity());
- }
-
- for (RulePriority severity : RulePriority.values()) {
- Metric metric = SeverityUtils.severityToViolationMetric(severity);
- if (context.getMeasure(metric) == null) {
- Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.metric(metric));
- int sum = MeasureUtils.sum(true, children).intValue() + severitiesBag.count(severity);
- context.saveMeasure(metric, (double) sum);
- }
- }
- }
-
- private void computeViolationsPerRules(DecoratorContext context) {
- Map<RulePriority, Multiset<Rule>> rulesPerSeverity = Maps.newHashMap();
- for (Violation violation : context.getViolations()) {
- Multiset<Rule> rulesBag = initRules(rulesPerSeverity, violation.getSeverity());
- rulesBag.add(violation.getRule());
- }
-
- for (RulePriority severity : RulePriority.values()) {
- Metric metric = SeverityUtils.severityToViolationMetric(severity);
-
- Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.rules(metric));
- for (Measure child : children) {
- RuleMeasure childRuleMeasure = (RuleMeasure) child;
- Rule rule = childRuleMeasure.getRule();
- if (rule != null && MeasureUtils.hasValue(childRuleMeasure)) {
- Multiset<Rule> rulesBag = initRules(rulesPerSeverity, severity);
- rulesBag.add(rule, childRuleMeasure.getIntValue());
- }
- }
-
- Multiset<Rule> rulesBag = rulesPerSeverity.get(severity);
- if (rulesBag != null) {
- for (Multiset.Entry<Rule> entry : rulesBag.entrySet()) {
- RuleMeasure measure = RuleMeasure.createForRule(metric, entry.getElement(), (double) entry.getCount());
- measure.setSeverity(severity);
- context.saveMeasure(measure);
- }
- }
- }
- }
-
- private Multiset<Rule> initRules(Map<RulePriority, Multiset<Rule>> rulesPerSeverity, RulePriority severity) {
- Multiset<Rule> rulesBag = rulesPerSeverity.get(severity);
- if (rulesBag == null) {
- rulesBag = HashMultiset.create();
- rulesPerSeverity.put(severity, rulesBag);
- }
- return rulesBag;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName();
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import org.sonar.api.batch.Decorator;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DependedUpon;
-import org.sonar.api.batch.DependsUpon;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.MeasureUtils;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-
-import java.util.Arrays;
-import java.util.List;
-
-public class ViolationsDensityDecorator implements Decorator {
-
- public boolean shouldExecuteOnProject(Project project) {
- return true;
- }
-
- @DependsUpon
- public List<Metric> dependsUponWeightedViolationsAndNcloc() {
- return Arrays.asList(CoreMetrics.WEIGHTED_VIOLATIONS, CoreMetrics.NCLOC);
- }
-
- @DependedUpon
- public Metric generatesViolationsDensity() {
- return CoreMetrics.VIOLATIONS_DENSITY;
- }
-
- public void decorate(Resource resource, DecoratorContext context) {
- if (shouldDecorateResource(context)) {
- decorateDensity(context);
- }
- }
-
- protected boolean shouldDecorateResource(DecoratorContext context) {
- return context.getMeasure(CoreMetrics.VIOLATIONS_DENSITY) == null;
- }
-
- private void decorateDensity(DecoratorContext context) {
- Measure ncloc = context.getMeasure(CoreMetrics.NCLOC);
- if (MeasureUtils.hasValue(ncloc) && ncloc.getValue() > 0.0) {
- saveDensity(context, ncloc.getValue().intValue());
- }
- }
-
- private void saveDensity(DecoratorContext context, int ncloc) {
- Measure debt = context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS);
- Integer debtValue = 0;
- if (MeasureUtils.hasValue(debt)) {
- debtValue = debt.getValue().intValue();
- }
- double density = calculate(debtValue, ncloc);
- context.saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, density);
- }
-
- protected static double calculate(int debt, int ncloc) {
- double rci = (1.0 - ((double) debt / (double) ncloc)) * 100.0;
- rci = Math.max(rci, 0.0);
- return rci;
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName();
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.collect.Multiset;
-import com.google.common.collect.TreeMultiset;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.batch.Decorator;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DependedUpon;
-import org.sonar.api.batch.DependsUpon;
-import org.sonar.api.config.Settings;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.MeasureUtils;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.utils.KeyValueFormat;
-
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-
-public class WeightedViolationsDecorator implements Decorator {
-
- private Settings settings;
- private Map<RulePriority, Integer> weightsBySeverity;
-
- public WeightedViolationsDecorator(Settings settings) {
- this.settings = settings;
- }
-
- @DependsUpon
- public List<Metric> dependsUponViolations() {
- return Arrays.asList(CoreMetrics.BLOCKER_VIOLATIONS, CoreMetrics.CRITICAL_VIOLATIONS,
- CoreMetrics.MAJOR_VIOLATIONS, CoreMetrics.MINOR_VIOLATIONS, CoreMetrics.INFO_VIOLATIONS);
- }
-
- @DependedUpon
- public Metric generatesWeightedViolations() {
- return CoreMetrics.WEIGHTED_VIOLATIONS;
- }
-
- public boolean shouldExecuteOnProject(Project project) {
- return true;
- }
-
- public void start() {
- weightsBySeverity = getWeights(settings);
- }
-
- Map<RulePriority, Integer> getWeightsBySeverity() {
- return weightsBySeverity;
- }
-
- static Map<RulePriority, Integer> getWeights(final Settings settings) {
- String value = settings.getString(CoreProperties.CORE_RULE_WEIGHTS_PROPERTY);
-
- Map<RulePriority, Integer> weights = KeyValueFormat.parse(value, KeyValueFormat.newPriorityConverter(), KeyValueFormat.newIntegerConverter());
-
- for (RulePriority priority : RulePriority.values()) {
- if (!weights.containsKey(priority)) {
- weights.put(priority, 1);
- }
- }
- return weights;
- }
-
-
- public void decorate(Resource resource, DecoratorContext context) {
- decorate(context);
- }
-
- void decorate(DecoratorContext context) {
- double debt = 0.0;
- Multiset<RulePriority> distribution = TreeMultiset.create();
-
- for (RulePriority severity : RulePriority.values()) {
- Measure measure = context.getMeasure(SeverityUtils.severityToViolationMetric(severity));
- if (measure != null && MeasureUtils.hasValue(measure)) {
- distribution.add(severity, measure.getIntValue());
- double add = weightsBySeverity.get(severity) * measure.getIntValue();
- debt += add;
- }
- }
-
- Measure debtMeasure = new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, debt, KeyValueFormat.format(distribution));
- context.saveMeasure(debtMeasure);
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.timemachine;
-
-import com.google.common.collect.ArrayListMultimap;
-import com.google.common.collect.ListMultimap;
-import com.google.common.collect.Sets;
-import org.apache.commons.lang.StringUtils;
-import org.sonar.api.batch.Decorator;
-import org.sonar.api.batch.DecoratorBarriers;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.batch.DependedUpon;
-import org.sonar.api.batch.DependsUpon;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.MeasureUtils;
-import org.sonar.api.measures.MeasuresFilters;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.RuleMeasure;
-import org.sonar.api.notifications.Notification;
-import org.sonar.api.notifications.NotificationManager;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.resources.ResourceUtils;
-import org.sonar.api.resources.Scopes;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-import org.sonar.batch.components.PastSnapshot;
-import org.sonar.batch.components.TimeMachineConfiguration;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-
-@DependsUpon(DecoratorBarriers.END_OF_VIOLATION_TRACKING)
-public class NewViolationsDecorator implements Decorator {
-
- private TimeMachineConfiguration timeMachineConfiguration;
- private NotificationManager notificationManager;
-
- public NewViolationsDecorator(TimeMachineConfiguration timeMachineConfiguration, NotificationManager notificationManager) {
- this.timeMachineConfiguration = timeMachineConfiguration;
- this.notificationManager = notificationManager;
- }
-
- public boolean shouldExecuteOnProject(Project project) {
- return project.isLatestAnalysis();
- }
-
- @DependedUpon
- public List<Metric> generatesMetric() {
- return Arrays.asList(
- CoreMetrics.NEW_VIOLATIONS,
- CoreMetrics.NEW_BLOCKER_VIOLATIONS,
- CoreMetrics.NEW_CRITICAL_VIOLATIONS,
- CoreMetrics.NEW_MAJOR_VIOLATIONS,
- CoreMetrics.NEW_MINOR_VIOLATIONS,
- CoreMetrics.NEW_INFO_VIOLATIONS);
- }
-
- @SuppressWarnings("rawtypes")
- public void decorate(Resource resource, DecoratorContext context) {
- if (shouldDecorateResource(resource, context)) {
- computeNewViolations(context);
- computeNewViolationsPerSeverity(context);
- computeNewViolationsPerRule(context);
- }
- if (ResourceUtils.isRootProject(resource)) {
- notifyNewViolations((Project) resource, context);
- }
- }
-
- private boolean shouldDecorateResource(Resource<?> resource, DecoratorContext context) {
- return (StringUtils.equals(Scopes.PROJECT, resource.getScope()) || StringUtils.equals(Scopes.DIRECTORY, resource.getScope()) || StringUtils
- .equals(Scopes.FILE, resource.getScope()))
- && (context.getMeasure(CoreMetrics.NEW_VIOLATIONS) == null);
- }
-
- private void computeNewViolations(DecoratorContext context) {
- Measure measure = new Measure(CoreMetrics.NEW_VIOLATIONS);
- for (PastSnapshot pastSnapshot : timeMachineConfiguration.getProjectPastSnapshots()) {
- int variationIndex = pastSnapshot.getIndex();
- Collection<Measure> children = context.getChildrenMeasures(CoreMetrics.NEW_VIOLATIONS);
- int count = countViolations(context.getViolations(), pastSnapshot.getTargetDate());
- double sum = MeasureUtils.sumOnVariation(true, variationIndex, children) + count;
- measure.setVariation(variationIndex, sum);
- }
- context.saveMeasure(measure);
- }
-
- private void computeNewViolationsPerSeverity(DecoratorContext context) {
- ListMultimap<RulePriority, Violation> violationsPerSeverities = ArrayListMultimap.create();
- for (Violation violation : context.getViolations()) {
- violationsPerSeverities.put(violation.getSeverity(), violation);
- }
-
- for (RulePriority severity : RulePriority.values()) {
- Metric metric = severityToMetric(severity);
- Measure measure = new Measure(metric);
- for (PastSnapshot pastSnapshot : timeMachineConfiguration.getProjectPastSnapshots()) {
- int variationIndex = pastSnapshot.getIndex();
- int count = countViolations(violationsPerSeverities.get(severity), pastSnapshot.getTargetDate());
- Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.metric(metric));
- double sum = MeasureUtils.sumOnVariation(true, variationIndex, children) + count;
- measure.setVariation(variationIndex, sum);
- }
- context.saveMeasure(measure);
- }
- }
-
- private void computeNewViolationsPerRule(DecoratorContext context) {
- for (RulePriority severity : RulePriority.values()) {
- Metric metric = severityToMetric(severity);
- ListMultimap<Rule, Measure> childMeasuresPerRule = ArrayListMultimap.create();
- ListMultimap<Rule, Violation> violationsPerRule = ArrayListMultimap.create();
- Set<Rule> rules = Sets.newHashSet();
-
- Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.rules(metric));
- for (Measure child : children) {
- RuleMeasure childRuleMeasure = (RuleMeasure) child;
- Rule rule = childRuleMeasure.getRule();
- if (rule != null) {
- childMeasuresPerRule.put(rule, childRuleMeasure);
- rules.add(rule);
- }
- }
-
- for (Violation violation : context.getViolations()) {
- if (violation.getSeverity().equals(severity)) {
- rules.add(violation.getRule());
- violationsPerRule.put(violation.getRule(), violation);
- }
- }
-
- for (Rule rule : rules) {
- RuleMeasure measure = RuleMeasure.createForRule(metric, rule, null);
- measure.setSeverity(severity);
- for (PastSnapshot pastSnapshot : timeMachineConfiguration.getProjectPastSnapshots()) {
- int variationIndex = pastSnapshot.getIndex();
- int count = countViolations(violationsPerRule.get(rule), pastSnapshot.getTargetDate());
- double sum = MeasureUtils.sumOnVariation(true, variationIndex, childMeasuresPerRule.get(rule)) + count;
- measure.setVariation(variationIndex, sum);
- }
- context.saveMeasure(measure);
- }
- }
- }
-
- int countViolations(Collection<Violation> violations, Date targetDate) {
- if (violations == null) {
- return 0;
- }
- int count = 0;
- for (Violation violation : violations) {
- if (isAfter(violation, targetDate)) {
- count++;
- }
- }
- return count;
- }
-
- private boolean isAfter(Violation violation, Date date) {
- if (date == null) {
- return true;
- }
- return violation.getCreatedAt() != null && violation.getCreatedAt().after(date);
- }
-
- private Metric severityToMetric(RulePriority severity) {
- Metric metric;
- if (severity.equals(RulePriority.BLOCKER)) {
- metric = CoreMetrics.NEW_BLOCKER_VIOLATIONS;
- } else if (severity.equals(RulePriority.CRITICAL)) {
- metric = CoreMetrics.NEW_CRITICAL_VIOLATIONS;
- } else if (severity.equals(RulePriority.MAJOR)) {
- metric = CoreMetrics.NEW_MAJOR_VIOLATIONS;
- } else if (severity.equals(RulePriority.MINOR)) {
- metric = CoreMetrics.NEW_MINOR_VIOLATIONS;
- } else if (severity.equals(RulePriority.INFO)) {
- metric = CoreMetrics.NEW_INFO_VIOLATIONS;
- } else {
- throw new IllegalArgumentException("Unsupported severity: " + severity);
- }
- return metric;
- }
-
- protected void notifyNewViolations(Project project, DecoratorContext context) {
- List<PastSnapshot> projectPastSnapshots = timeMachineConfiguration.getProjectPastSnapshots();
- if (projectPastSnapshots.size() >= 1) {
- // we always check new violations against period1
- PastSnapshot pastSnapshot = projectPastSnapshots.get(0);
- Double newViolationsCount = context.getMeasure(CoreMetrics.NEW_VIOLATIONS).getVariation1();
- // Do not send notification if this is the first analysis or if there's no violation
- if (pastSnapshot.getTargetDate() != null && newViolationsCount != null && newViolationsCount > 0) {
- // Maybe we should check if this is the first analysis or not?
- DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
- Notification notification = new Notification("new-violations")
- .setDefaultMessage(newViolationsCount.intValue() + " new violations on " + project.getLongName() + ".")
- .setFieldValue("count", String.valueOf(newViolationsCount.intValue()))
- .setFieldValue("projectName", project.getLongName())
- .setFieldValue("projectKey", project.getKey())
- .setFieldValue("projectId", String.valueOf(project.getId()))
- .setFieldValue("fromDate", dateformat.format(pastSnapshot.getTargetDate()));
- notificationManager.scheduleForSending(notification);
- }
- }
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName();
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.timemachine;
-
-import org.sonar.api.batch.*;
-import org.sonar.api.database.DatabaseSession;
-import org.sonar.api.database.model.RuleFailureModel;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleFinder;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.violations.ViolationQuery;
-import org.sonar.batch.index.ResourcePersister;
-import org.sonar.core.DryRunIncompatible;
-
-import java.util.List;
-
-@DryRunIncompatible
-@DependsUpon({ DecoratorBarriers.END_OF_VIOLATION_TRACKING, DecoratorBarriers.START_VIOLATION_PERSISTENCE })
-@DependedUpon(DecoratorBarriers.END_OF_VIOLATION_PERSISTENCE)
-public class ViolationPersisterDecorator implements Decorator {
-
- private ViolationTrackingDecorator tracker;
- private ResourcePersister persister;
- private RuleFinder ruleFinder;
- private DatabaseSession session;
-
- public ViolationPersisterDecorator(ViolationTrackingDecorator tracker, ResourcePersister persister, RuleFinder ruleFinder, DatabaseSession session) {
- this.tracker = tracker;
- this.persister = persister;
- this.ruleFinder = ruleFinder;
- this.session = session;
- }
-
- public boolean shouldExecuteOnProject(Project project) {
- return true;
- }
-
- public void decorate(Resource resource, DecoratorContext context) {
- saveViolations(context.getProject(), context.getViolations(ViolationQuery.create().forResource(resource).setSwitchMode(ViolationQuery.SwitchMode.BOTH)));
- }
-
- void saveViolations(Project project, List<Violation> violations) {
- for (Violation violation : violations) {
- RuleFailureModel referenceViolation = tracker.getReferenceViolation(violation);
- save(project, violation, referenceViolation);
- }
- session.commit();
- }
-
- public void save(Project project, Violation violation, RuleFailureModel referenceViolation) {
- Snapshot snapshot = persister.saveResource(project, violation.getResource());
-
- RuleFailureModel model = createModel(violation);
- if (referenceViolation != null) {
- model.setPermanentId(referenceViolation.getPermanentId());
- }
- model.setSnapshotId(snapshot.getId());
- session.saveWithoutFlush(model);
-
- if (model.getPermanentId() == null) {
- model.setPermanentId(model.getId());
- session.saveWithoutFlush(model);
- }
- violation.setMessage(model.getMessage());// the message can be changed in the class RuleFailure (truncate + trim)
- }
-
-
- private RuleFailureModel createModel(Violation violation) {
- RuleFailureModel model = new RuleFailureModel();
- Rule rule = ruleFinder.findByKey(violation.getRule().getRepositoryKey(), violation.getRule().getKey());
- model.setRuleId(rule.getId());
- model.setPriority(violation.getSeverity());
- model.setLine(violation.getLineId());
- model.setMessage(violation.getMessage());
- model.setCost(violation.getCost());
- model.setChecksum(violation.getChecksum());
- model.setCreatedAt(violation.getCreatedAt());
- model.setSwitchedOff(violation.isSwitchedOff());
- model.setPersonId(violation.getPersonId());
- return model;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.timemachine;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Objects;
-import com.google.common.collect.*;
-import org.apache.commons.lang.ObjectUtils;
-import org.apache.commons.lang.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sonar.api.batch.*;
-import org.sonar.api.database.model.RuleFailureModel;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.violations.ViolationQuery;
-import org.sonar.batch.scan.LastSnapshots;
-import org.sonar.plugins.core.timemachine.tracking.*;
-
-import javax.annotation.Nullable;
-
-import java.util.*;
-
-@DependsUpon({DecoratorBarriers.END_OF_VIOLATIONS_GENERATION, DecoratorBarriers.START_VIOLATION_TRACKING})
-@DependedUpon(DecoratorBarriers.END_OF_VIOLATION_TRACKING)
-public class ViolationTrackingDecorator implements Decorator {
-
- private static final Logger LOG = LoggerFactory.getLogger(ViolationTrackingDecorator.class);
-
- private LastSnapshots lastSnapshots;
- private Map<Violation, RuleFailureModel> referenceViolationsMap = Maps.newIdentityHashMap();
- private SonarIndex index;
- private Project project;
-
- /**
- * Live collection of unmapped past violations.
- */
- private Set<RuleFailureModel> unmappedLastViolations = Sets.newHashSet();
-
- public ViolationTrackingDecorator(Project project, LastSnapshots lastSnapshots, SonarIndex index) {
- this.lastSnapshots = lastSnapshots;
- this.index = index;
- this.project = project;
- }
-
- public boolean shouldExecuteOnProject(Project project) {
- return true;
- }
-
- public void decorate(Resource resource, DecoratorContext context) {
- LOG.debug("ViolationTracking : " + resource);
-
- referenceViolationsMap.clear();
-
- ViolationQuery violationQuery = ViolationQuery.create().forResource(resource).setSwitchMode(ViolationQuery.SwitchMode.BOTH);
- if (context.getViolations(violationQuery).isEmpty()) {
- return;
- }
-
- String source = index.getSource(resource);
-
- // Load new violations
- List<Violation> newViolations = prepareNewViolations(context, source);
-
- // Load the violations of the last available analysis
- List<RuleFailureModel> referenceViolations = lastSnapshots.getViolations(resource);
-
- // Map new violations with old ones
- mapViolations(newViolations, referenceViolations, source, resource);
- }
-
- private List<Violation> prepareNewViolations(DecoratorContext context, String source) {
- List<Violation> result = Lists.newArrayList();
- List<String> checksums = SourceChecksum.lineChecksumsOfFile(source);
- for (Violation violation : context.getViolations()) {
- violation.setChecksum(SourceChecksum.getChecksumForLine(checksums, violation.getLineId()));
- result.add(violation);
- }
- return result;
- }
-
- public RuleFailureModel getReferenceViolation(Violation violation) {
- return referenceViolationsMap.get(violation);
- }
-
- @VisibleForTesting
- Map<Violation, RuleFailureModel> mapViolations(List<Violation> newViolations, @Nullable List<RuleFailureModel> lastViolations) {
- return mapViolations(newViolations, lastViolations, null, null);
- }
-
- @VisibleForTesting
- Map<Violation, RuleFailureModel> mapViolations(List<Violation> newViolations, @Nullable List<RuleFailureModel> lastViolations,
- @Nullable String source, @Nullable Resource resource) {
- boolean hasLastScan = false;
- Multimap<Integer, RuleFailureModel> lastViolationsByRule = LinkedHashMultimap.create();
-
- if (lastViolations != null) {
- hasLastScan = true;
- unmappedLastViolations.addAll(lastViolations);
-
- for (RuleFailureModel lastViolation : lastViolations) {
- lastViolationsByRule.put(lastViolation.getRuleId(), lastViolation);
- }
-
- // Match the permanent id of the violation. This id is for example set explicitly when injecting manual violations
- for (Violation newViolation : newViolations) {
- mapViolation(newViolation,
- findLastViolationWithSamePermanentId(newViolation, lastViolationsByRule.get(newViolation.getRule().getId())),
- lastViolationsByRule, referenceViolationsMap);
- }
-
- // Try first to match violations on same rule with same line and with same checksum (but not necessarily with same message)
- for (Violation newViolation : newViolations) {
- if (isNotAlreadyMapped(newViolation)) {
- mapViolation(newViolation,
- findLastViolationWithSameLineAndChecksum(newViolation, lastViolationsByRule.get(newViolation.getRule().getId())),
- lastViolationsByRule, referenceViolationsMap);
- }
- }
- }
-
- // If each new violation matches an old one we can stop the matching mechanism
- if (referenceViolationsMap.size() != newViolations.size()) {
- if (source != null && resource != null && hasLastScan) {
- String referenceSource = lastSnapshots.getSource(resource);
- if (referenceSource != null) {
- HashedSequence<StringText> hashedReference = HashedSequence.wrap(new StringText(referenceSource), StringTextComparator.IGNORE_WHITESPACE);
- HashedSequence<StringText> hashedSource = HashedSequence.wrap(new StringText(source), StringTextComparator.IGNORE_WHITESPACE);
- HashedSequenceComparator<StringText> hashedComparator = new HashedSequenceComparator<StringText>(StringTextComparator.IGNORE_WHITESPACE);
-
- ViolationTrackingBlocksRecognizer rec = new ViolationTrackingBlocksRecognizer(hashedReference, hashedSource, hashedComparator);
-
- Multimap<Integer, Violation> newViolationsByLines = newViolationsByLines(newViolations, rec);
- Multimap<Integer, RuleFailureModel> lastViolationsByLines = lastViolationsByLines(unmappedLastViolations, rec);
-
- RollingHashSequence<HashedSequence<StringText>> a = RollingHashSequence.wrap(hashedReference, hashedComparator, 5);
- RollingHashSequence<HashedSequence<StringText>> b = RollingHashSequence.wrap(hashedSource, hashedComparator, 5);
- RollingHashSequenceComparator<HashedSequence<StringText>> cmp = new RollingHashSequenceComparator<HashedSequence<StringText>>(hashedComparator);
-
- Map<Integer, HashOccurrence> map = Maps.newHashMap();
-
- for (Integer line : lastViolationsByLines.keySet()) {
- int hash = cmp.hash(a, line - 1);
- HashOccurrence hashOccurrence = map.get(hash);
- if (hashOccurrence == null) {
- // first occurrence in A
- hashOccurrence = new HashOccurrence();
- hashOccurrence.lineA = line;
- hashOccurrence.countA = 1;
- map.put(hash, hashOccurrence);
- } else {
- hashOccurrence.countA++;
- }
- }
-
- for (Integer line : newViolationsByLines.keySet()) {
- int hash = cmp.hash(b, line - 1);
- HashOccurrence hashOccurrence = map.get(hash);
- if (hashOccurrence != null) {
- hashOccurrence.lineB = line;
- hashOccurrence.countB++;
- }
- }
-
- for (HashOccurrence hashOccurrence : map.values()) {
- if (hashOccurrence.countA == 1 && hashOccurrence.countB == 1) {
- // Guaranteed that lineA has been moved to lineB, so we can map all violations on lineA to all violations on lineB
- LOG.debug("*** Guaranteed that lineA has been moved to lineB, so we can map all issues on lineA to all issues on lineB");
- map(newViolationsByLines.get(hashOccurrence.lineB), lastViolationsByLines.get(hashOccurrence.lineA), lastViolationsByRule);
- lastViolationsByLines.removeAll(hashOccurrence.lineA);
- newViolationsByLines.removeAll(hashOccurrence.lineB);
- }
- }
-
- // Check if remaining number of lines exceeds threshold
- if (lastViolationsByLines.keySet().size() * newViolationsByLines.keySet().size() < 250000) {
- List<LinePair> possibleLinePairs = Lists.newArrayList();
- for (Integer oldLine : lastViolationsByLines.keySet()) {
- for (Integer newLine : newViolationsByLines.keySet()) {
- int weight = rec.computeLengthOfMaximalBlock(oldLine - 1, newLine - 1);
- possibleLinePairs.add(new LinePair(oldLine, newLine, weight));
- }
- }
- Collections.sort(possibleLinePairs, LINE_PAIR_COMPARATOR);
- for (LinePair linePair : possibleLinePairs) {
- // High probability that lineA has been moved to lineB, so we can map all violations on lineA to all violations on lineB
- LOG.debug("*** High probability that lineA has been moved to lineB, so we can map all Issues on lineA to all Issues on lineB");
- map(newViolationsByLines.get(linePair.lineB), lastViolationsByLines.get(linePair.lineA), lastViolationsByRule);
- }
- }
- }
- }
-
- // Try then to match violations on same rule with same message and with same checksum
- for (Violation newViolation : newViolations) {
- if (isNotAlreadyMapped(newViolation)) {
- LOG.debug("*** Try then to match issues on same rule with same message and with same checksum");
- mapViolation(newViolation,
- findLastViolationWithSameChecksumAndMessage(newViolation, lastViolationsByRule.get(newViolation.getRule().getId())),
- lastViolationsByRule, referenceViolationsMap);
- }
- }
-
- // Try then to match violations on same rule with same line and with same message
- for (Violation newViolation : newViolations) {
- if (isNotAlreadyMapped(newViolation)) {
- LOG.debug("*** Try then to match issues on same rule with same line and with same message");
- mapViolation(newViolation,
- findLastViolationWithSameLineAndMessage(newViolation, lastViolationsByRule.get(newViolation.getRule().getId())),
- lastViolationsByRule, referenceViolationsMap);
- }
- }
-
- // Last check: match violation if same rule and same checksum but different line and different message
- // See SONAR-2812
- for (Violation newViolation : newViolations) {
- if (isNotAlreadyMapped(newViolation)) {
- LOG.debug("*** Last check: match issue if same rule and same checksum but different line and different message");
- mapViolation(newViolation,
- findLastViolationWithSameChecksum(newViolation, lastViolationsByRule.get(newViolation.getRule().getId())),
- lastViolationsByRule, referenceViolationsMap);
- }
- }
- }
-
- unmappedLastViolations.clear();
- return referenceViolationsMap;
- }
-
- private void map(Collection<Violation> newViolations, Collection<RuleFailureModel> lastViolations, Multimap<Integer, RuleFailureModel> lastViolationsByRule) {
- for (Violation newViolation : newViolations) {
- if (isNotAlreadyMapped(newViolation)) {
- for (RuleFailureModel pastViolation : lastViolations) {
- if (isNotAlreadyMapped(pastViolation) && Objects.equal(newViolation.getRule().getId(), pastViolation.getRuleId())) {
- LOG.debug("mapIssue newViolation : " + newViolation + " with pastViolation : " + pastViolation);
- mapViolation(newViolation, pastViolation, lastViolationsByRule, referenceViolationsMap);
- break;
- } else {
- LOG.debug("Not mapIssue newViolation : " + newViolation + " with pastViolation : " + pastViolation);
- }
- }
- }
- }
- }
-
- private Multimap<Integer, Violation> newViolationsByLines(Collection<Violation> newViolations, ViolationTrackingBlocksRecognizer rec) {
- Multimap<Integer, Violation> newViolationsByLines = LinkedHashMultimap.create();
- for (Violation newViolation : newViolations) {
- if (isNotAlreadyMapped(newViolation)) {
- if (rec.isValidLineInSource(newViolation.getLineId())) {
- newViolationsByLines.put(newViolation.getLineId(), newViolation);
- }
- }
- }
- return newViolationsByLines;
- }
-
- private Multimap<Integer, RuleFailureModel> lastViolationsByLines(Collection<RuleFailureModel> lastViolations, ViolationTrackingBlocksRecognizer rec) {
- Multimap<Integer, RuleFailureModel> lastViolationsByLines = LinkedHashMultimap.create();
- for (RuleFailureModel pastViolation : lastViolations) {
- if (rec.isValidLineInReference(pastViolation.getLine())) {
- lastViolationsByLines.put(pastViolation.getLine(), pastViolation);
- }
- }
- return lastViolationsByLines;
- }
-
- private static final Comparator<LinePair> LINE_PAIR_COMPARATOR = new Comparator<LinePair>() {
- public int compare(LinePair o1, LinePair o2) {
- return o2.weight - o1.weight;
- }
- };
-
- static class LinePair {
- int lineA;
- int lineB;
- int weight;
-
- public LinePair(int lineA, int lineB, int weight) {
- this.lineA = lineA;
- this.lineB = lineB;
- this.weight = weight;
- }
- }
-
- static class HashOccurrence {
- int lineA;
- int lineB;
- int countA;
- int countB;
- }
-
- private boolean isNotAlreadyMapped(RuleFailureModel pastViolation) {
- return unmappedLastViolations.contains(pastViolation);
- }
-
- private boolean isNotAlreadyMapped(Violation newViolation) {
- return !referenceViolationsMap.containsKey(newViolation);
- }
-
- private RuleFailureModel findLastViolationWithSameChecksum(Violation newViolation, Collection<RuleFailureModel> lastViolations) {
- for (RuleFailureModel pastViolation : lastViolations) {
- if (isSameChecksum(newViolation, pastViolation)) {
- return pastViolation;
- }
- }
- return null;
- }
-
- private RuleFailureModel findLastViolationWithSameLineAndMessage(Violation newViolation, Collection<RuleFailureModel> lastViolations) {
- for (RuleFailureModel pastViolation : lastViolations) {
- if (isSameLine(newViolation, pastViolation) && isSameMessage(newViolation, pastViolation)) {
- return pastViolation;
- }
- }
- return null;
- }
-
- private RuleFailureModel findLastViolationWithSameChecksumAndMessage(Violation newViolation, Collection<RuleFailureModel> lastViolations) {
- for (RuleFailureModel pastViolation : lastViolations) {
- if (isSameChecksum(newViolation, pastViolation) && isSameMessage(newViolation, pastViolation)) {
- return pastViolation;
- }
- }
- return null;
- }
-
- private RuleFailureModel findLastViolationWithSameLineAndChecksum(Violation newViolation, Collection<RuleFailureModel> lastViolations) {
- for (RuleFailureModel pastViolation : lastViolations) {
- if (isSameLine(newViolation, pastViolation) && isSameChecksum(newViolation, pastViolation)) {
- return pastViolation;
- }
- }
- return null;
- }
-
- private RuleFailureModel findLastViolationWithSamePermanentId(Violation newViolation, Collection<RuleFailureModel> lastViolations) {
- for (RuleFailureModel pastViolation : lastViolations) {
- if (isSamePermanentId(newViolation, pastViolation)) {
- return pastViolation;
- }
- }
- return null;
- }
-
- private boolean isSameChecksum(Violation newViolation, RuleFailureModel pastViolation) {
- return StringUtils.equals(pastViolation.getChecksum(), newViolation.getChecksum());
- }
-
- private boolean isSameLine(Violation newViolation, RuleFailureModel pastViolation) {
- return ObjectUtils.equals(pastViolation.getLine(), newViolation.getLineId());
- }
-
- private boolean isSameMessage(Violation newViolation, RuleFailureModel pastViolation) {
- return StringUtils.equals(RuleFailureModel.abbreviateMessage(newViolation.getMessage()), pastViolation.getMessage());
- }
-
- private boolean isSamePermanentId(Violation newViolation, RuleFailureModel pastViolation) {
- return newViolation.getPermanentId() != null && newViolation.getPermanentId().equals(pastViolation.getPermanentId());
- }
-
- private void mapViolation(Violation newViolation, RuleFailureModel pastViolation,
- Multimap<Integer, RuleFailureModel> lastViolationsByRule, Map<Violation, RuleFailureModel> violationMap) {
- if (pastViolation != null) {
- LOG.debug("Mapping with old violation from newViolation : " + newViolation + " and pastViolation : " + pastViolation);
-
- newViolation.setCreatedAt(pastViolation.getCreatedAt());
- newViolation.setPermanentId(pastViolation.getPermanentId());
- newViolation.setSwitchedOff(pastViolation.isSwitchedOff());
- newViolation.setPersonId(pastViolation.getPersonId());
- newViolation.setNew(false);
- lastViolationsByRule.remove(newViolation.getRule().getId(), pastViolation);
- violationMap.put(newViolation, pastViolation);
- unmappedLastViolations.remove(pastViolation);
- } else {
- LOG.debug("No old violation, creating new one with newViolation : " + newViolation + " and pastViolation : " + pastViolation);
-
- newViolation.setNew(true);
- newViolation.setCreatedAt(project.getAnalysisDate());
- }
- }
-
- @Override
- public String toString() {
- return getClass().getSimpleName();
- }
-
-}
layout.evaluation=Embedded database should be used for evaluation purpose only
layout.ie6_warn=Your web browser is outdated. This website may not display correctly.
layout.dashboards=Dashboards
-layout.reviews=Reviews
layout.configuration=Configuration
layout.projects=Projects
layout.recent_projects=Recent Projects
user_groups.page=Groups
users.page=Users
violations.page=Violations
-violations_drilldown.page=Violations Drilldown
update_center.page=Update Center
lcom4_viewer.page=LCOM4
resource_deletion.page={0} Deletion
<div class="line-block">
<div style="float:right">
- <a href="#" onclick="window.location.href='<%= url_for(:controller => 'drilldown', :action => 'violations') -%>/<%= @resource.id -%>?period=<%= dashboard_configuration.period_index -%>&severity=' + $F('select-severity_<%= widget.id -%>') ">
+ <a href="#" onclick="window.location.href='<%= url_for(:controller => 'drilldown', :action => 'issues') -%>/<%= @resource.id -%>?period=<%= dashboard_configuration.period_index -%>&severity=' + $F('select-severity_<%= widget.id -%>') ">
<%= message('widget.hotspot_metric.more') -%>
</a>
</div>
<%= image_tag('priority/' + m.severity + '.png') -%>
</td>
<td>
- <a href="<%= url_for(:controller => 'drilldown', :action => 'violations', :id => @resource.key, :rule => rule.key, :rule_sev => m.severity, :period => dashboard_configuration.period_index) -%>">
+ <a href="<%= url_for(:controller => 'drilldown', :action => 'issues', :id => @resource.key, :rule => rule.key, :rule_sev => m.severity, :period => dashboard_configuration.period_index) -%>">
<%= h rule.name -%>
</a>
</td>
context = mock(DecoratorContext.class);
when(context.getResource()).thenReturn(resource);
when(context.getProject()).thenReturn(project);
- when(context.getMeasure(CoreMetrics.NEW_ISSUES)).thenReturn(null);
+ when(context.getMeasure(CoreMetrics.NEW_VIOLATIONS)).thenReturn(null);
issuable = mock(Issuable.class);
ResourcePerspectives perspectives = mock(ResourcePerspectives.class);
@Test
public void should_be_depended_upon_metric() {
- assertThat(decorator.generatesIssuesMetrics()).hasSize(16);
+ assertThat(decorator.generatesIssuesMetrics()).hasSize(15);
}
@Test
decorator.decorate(resource, context);
- verify(context).saveMeasure(CoreMetrics.ISSUES, 4.0);
+ verify(context).saveMeasure(CoreMetrics.VIOLATIONS, 4.0);
}
@Test
when(resource.getScope()).thenReturn(Scopes.PROJECT);
when(issuable.issues()).thenReturn(createIssues());
when(context.getChildrenMeasures(any(MeasuresFilter.class))).thenReturn(Collections.<Measure>emptyList());
- when(context.getMeasure(CoreMetrics.ISSUES)).thenReturn(new Measure(CoreMetrics.ISSUES, 3000.0));
- when(context.getMeasure(CoreMetrics.MAJOR_ISSUES)).thenReturn(new Measure(CoreMetrics.MAJOR_ISSUES, 500.0));
+ when(context.getMeasure(CoreMetrics.VIOLATIONS)).thenReturn(new Measure(CoreMetrics.ISSUES, 3000.0));
+ when(context.getMeasure(CoreMetrics.MAJOR_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.MAJOR_ISSUES, 500.0));
decorator.decorate(resource, context);
- verify(context, never()).saveMeasure(eq(CoreMetrics.ISSUES), anyDouble());// not changed
- verify(context, never()).saveMeasure(eq(CoreMetrics.MAJOR_ISSUES), anyDouble());// not changed
- verify(context, times(1)).saveMeasure(eq(CoreMetrics.CRITICAL_ISSUES), anyDouble());// did not exist
+ verify(context, never()).saveMeasure(eq(CoreMetrics.VIOLATIONS), anyDouble());// not changed
+ verify(context, never()).saveMeasure(eq(CoreMetrics.MAJOR_VIOLATIONS), anyDouble());// not changed
+ verify(context, times(1)).saveMeasure(eq(CoreMetrics.CRITICAL_VIOLATIONS), anyDouble());// did not exist
}
@Test
decorator.decorate(resource, context);
- verify(context).saveMeasure(CoreMetrics.ISSUES, 0.0);
+ verify(context).saveMeasure(CoreMetrics.VIOLATIONS, 0.0);
}
@Test
decorator.decorate(resource, context);
- verify(context).saveMeasure(CoreMetrics.ISSUES, 0.0);
+ verify(context).saveMeasure(CoreMetrics.VIOLATIONS, 0.0);
}
@Test
decorator.decorate(resource, context);
- verify(context).saveMeasure(CoreMetrics.BLOCKER_ISSUES, 0.0);
- verify(context).saveMeasure(CoreMetrics.CRITICAL_ISSUES, 2.0);
- verify(context).saveMeasure(CoreMetrics.MAJOR_ISSUES, 1.0);
- verify(context).saveMeasure(CoreMetrics.MINOR_ISSUES, 1.0);
- verify(context).saveMeasure(CoreMetrics.INFO_ISSUES, 0.0);
+ verify(context).saveMeasure(CoreMetrics.BLOCKER_VIOLATIONS, 0.0);
+ verify(context).saveMeasure(CoreMetrics.CRITICAL_VIOLATIONS, 2.0);
+ verify(context).saveMeasure(CoreMetrics.MAJOR_VIOLATIONS, 1.0);
+ verify(context).saveMeasure(CoreMetrics.MINOR_VIOLATIONS, 1.0);
+ verify(context).saveMeasure(CoreMetrics.INFO_VIOLATIONS, 0.0);
}
@Test
decorator.decorate(resource, context);
- verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.CRITICAL_ISSUES, ruleA1, 2.0)));
- verify(context, never()).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MAJOR_ISSUES, ruleA1, 0.0)));
- verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MAJOR_ISSUES, ruleA2, 1.0)));
+ verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.CRITICAL_VIOLATIONS, ruleA1, 2.0)));
+ verify(context, never()).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MAJOR_VIOLATIONS, ruleA1, 0.0)));
+ verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MAJOR_VIOLATIONS, ruleA2, 1.0)));
}
@Test
verify(context).saveMeasure(CoreMetrics.UNASSIGNED_ISSUES, 2.0);
}
- @Test
- public void should_save_open_issues() {
- List<Issue> issues = newArrayList();
- issues.add(new DefaultIssue().setRuleKey(ruleA1.ruleKey()).setStatus(Issue.STATUS_OPEN).setSeverity(RulePriority.CRITICAL.name()));
- issues.add(new DefaultIssue().setRuleKey(ruleA1.ruleKey()).setStatus(Issue.STATUS_REOPENED).setSeverity(RulePriority.CRITICAL.name()));
- issues.add(new DefaultIssue().setRuleKey(ruleA2.ruleKey()).setStatus(Issue.STATUS_OPEN).setSeverity(RulePriority.CRITICAL.name()));
- when(issuable.issues()).thenReturn(issues);
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.OPEN_ISSUES, 2.0);
- }
-
- @Test
- public void should_save_reopened_issues() {
- List<Issue> issues = newArrayList();
- issues.add(new DefaultIssue().setRuleKey(ruleA1.ruleKey()).setStatus(Issue.STATUS_OPEN).setSeverity(RulePriority.CRITICAL.name()));
- issues.add(new DefaultIssue().setRuleKey(ruleA1.ruleKey()).setStatus(Issue.STATUS_REOPENED).setSeverity(RulePriority.CRITICAL.name()));
- issues.add(new DefaultIssue().setRuleKey(ruleA2.ruleKey()).setStatus(Issue.STATUS_OPEN).setSeverity(RulePriority.CRITICAL.name()));
- when(issuable.issues()).thenReturn(issues);
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.REOPENED_ISSUES, 1.0);
- }
-
-
- @Test
- public void should_save_confirmed_issues() {
- List<Issue> issues = newArrayList();
- issues.add(new DefaultIssue().setRuleKey(ruleA1.ruleKey()).setStatus(Issue.STATUS_CONFIRMED).setSeverity(RulePriority.CRITICAL.name()));
- issues.add(new DefaultIssue().setRuleKey(ruleA1.ruleKey()).setStatus(Issue.STATUS_REOPENED).setSeverity(RulePriority.CRITICAL.name()));
- issues.add(new DefaultIssue().setRuleKey(ruleA2.ruleKey()).setStatus(Issue.STATUS_CONFIRMED).setSeverity(RulePriority.CRITICAL.name()));
- when(issuable.issues()).thenReturn(issues);
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.CONFIRMED_ISSUES, 2.0);
- }
-
@Test
public void same_rule_should_have_different_severities() {
List<Issue> issues = newArrayList();
decorator.decorate(resource, context);
- verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.CRITICAL_ISSUES, ruleA1, 2.0)));
- verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MINOR_ISSUES, ruleA1, 1.0)));
+ verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.CRITICAL_VIOLATIONS, ruleA1, 2.0)));
+ verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MINOR_VIOLATIONS, ruleA1, 1.0)));
}
@Test
decorator.decorate(resource, context);
decorator.decorate(resource, context);
- verify(context, times(2)).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_ISSUES, 1.0, 1.0)));
- verify(context, never()).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_ISSUES, 2.0, 2.0)));
+ verify(context, times(2)).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS, 1.0, 1.0)));
+ verify(context, never()).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS, 2.0, 2.0)));
}
@Test
decorator.decorate(resource, context);
// remember : period1 is 5daysAgo, period2 is 10daysAgo
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_BLOCKER_ISSUES, 0.0, 0.0)));
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_ISSUES, 1.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_MAJOR_ISSUES, 0.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_MINOR_ISSUES, 0.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_INFO_ISSUES, 0.0, 0.0)));
+ verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_BLOCKER_VIOLATIONS, 0.0, 0.0)));
+ verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS, 1.0, 1.0)));
+ verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_MAJOR_VIOLATIONS, 0.0, 1.0)));
+ verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_MINOR_VIOLATIONS, 0.0, 1.0)));
+ verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_INFO_VIOLATIONS, 0.0, 0.0)));
}
@Test
decorator.decorate(resource, context);
// remember : period1 is 5daysAgo, period2 is 10daysAgo
- verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_CRITICAL_ISSUES, ruleA1, 1.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_MAJOR_ISSUES, ruleA2, 0.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_MINOR_ISSUES, ruleB1, 0.0, 1.0)));
+ verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS, ruleA1, 1.0, 1.0)));
+ verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_MAJOR_VIOLATIONS, ruleA2, 0.0, 1.0)));
+ verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_MINOR_VIOLATIONS, ruleB1, 0.0, 1.0)));
}
@Test
decorator.decorate(resource, context);
- verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_BLOCKER_ISSUES)));
- verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_CRITICAL_ISSUES)));
- verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_MAJOR_ISSUES)));
- verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_MINOR_ISSUES)));
- verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_INFO_ISSUES)));
- verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_CRITICAL_ISSUES)));
+ verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_BLOCKER_VIOLATIONS)));
+ verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS)));
+ verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_MAJOR_VIOLATIONS)));
+ verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_MINOR_VIOLATIONS)));
+ verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_INFO_VIOLATIONS)));
+ verify(context, never()).saveMeasure(argThat(new IsMetricMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS)));
}
List<Issue> createIssues() {
public void decorate_density() {
DecoratorContext context = mock(DecoratorContext.class);
when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 200.0));
- when(context.getMeasure(CoreMetrics.WEIGHTED_ISSUES)).thenReturn(new Measure(CoreMetrics.WEIGHTED_ISSUES, 50.0));
+ when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 50.0));
decorator.decorate(resource, context);
- verify(context).saveMeasure(CoreMetrics.ISSUES_DENSITY, 75.0);
+ verify(context).saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, 75.0);
}
@Test
public void no_density_if_no_ncloc() {
DecoratorContext context = mock(DecoratorContext.class);
when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 0.0));
- when(context.getMeasure(CoreMetrics.WEIGHTED_ISSUES)).thenReturn(new Measure(CoreMetrics.WEIGHTED_ISSUES, 50.0));
+ when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 50.0));
decorator.decorate(resource, context);
- verify(context, never()).saveMeasure(Matchers.eq(CoreMetrics.ISSUES_DENSITY), Matchers.anyDouble());
+ verify(context, never()).saveMeasure(Matchers.eq(CoreMetrics.VIOLATIONS_DENSITY), Matchers.anyDouble());
}
@Test
public void save_density_if_value_is_zero() {
DecoratorContext context = mock(DecoratorContext.class);
when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 200.0));
- when(context.getMeasure(CoreMetrics.WEIGHTED_ISSUES)).thenReturn(new Measure(CoreMetrics.WEIGHTED_ISSUES, 5000.0));
+ when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 5000.0));
decorator.decorate(resource, context);
- verify(context).saveMeasure(CoreMetrics.ISSUES_DENSITY, 0.0);
+ verify(context).saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, 0.0);
}
@Test
decorator.decorate(resource, context);
- verify(context).saveMeasure(CoreMetrics.ISSUES_DENSITY, 100.0);
+ verify(context).saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, 100.0);
}
@Test
public void density_is_hundred_when_debt_is_zero() {
DecoratorContext context = mock(DecoratorContext.class);
when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 200.0));
- when(context.getMeasure(CoreMetrics.WEIGHTED_ISSUES)).thenReturn(new Measure(CoreMetrics.WEIGHTED_ISSUES, 0.0));
+ when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 0.0));
decorator.decorate(resource, context);
- verify(context).saveMeasure(CoreMetrics.ISSUES_DENSITY, 100.0);
+ verify(context).saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, 100.0);
}
}
public class WeightedIssuesDecoratorTest {
@Test
- public void test_weighted_issues() {
+ public void test_weighted_VIOLATIONS() {
Settings settings = new Settings();
settings.setProperty(CoreProperties.CORE_RULE_WEIGHTS_PROPERTY, "BLOCKER=10;CRITICAL=5;MAJOR=2;MINOR=1;INFO=0");
WeightedIssuesDecorator decorator = new WeightedIssuesDecorator(settings);
DecoratorContext context = mock(DecoratorContext.class);
- when(context.getMeasure(CoreMetrics.INFO_ISSUES)).thenReturn(new Measure(CoreMetrics.INFO_ISSUES, 50.0));
- when(context.getMeasure(CoreMetrics.CRITICAL_ISSUES)).thenReturn(new Measure(CoreMetrics.CRITICAL_ISSUES, 80.0));
- when(context.getMeasure(CoreMetrics.BLOCKER_ISSUES)).thenReturn(new Measure(CoreMetrics.BLOCKER_ISSUES, 100.0));
+ when(context.getMeasure(CoreMetrics.INFO_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.INFO_VIOLATIONS, 50.0));
+ when(context.getMeasure(CoreMetrics.CRITICAL_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.CRITICAL_VIOLATIONS, 80.0));
+ when(context.getMeasure(CoreMetrics.BLOCKER_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.BLOCKER_VIOLATIONS, 100.0));
decorator.start();
decorator.decorate(context);
- verify(context).saveMeasure(argThat(new IsMeasure(CoreMetrics.WEIGHTED_ISSUES, (double) (100 * 10 + 80 * 5 + 50 * 0))));
- verify(context).saveMeasure(argThat(new IsMeasure(CoreMetrics.WEIGHTED_ISSUES, "INFO=50;CRITICAL=80;BLOCKER=100")));
+ verify(context).saveMeasure(argThat(new IsMeasure(CoreMetrics.WEIGHTED_VIOLATIONS, (double) (100 * 10 + 80 * 5 + 50 * 0))));
+ verify(context).saveMeasure(argThat(new IsMeasure(CoreMetrics.WEIGHTED_VIOLATIONS, "INFO=50;CRITICAL=80;BLOCKER=100")));
}
// SONAR-3092
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.base.Predicate;
-import com.google.common.collect.Lists;
-import org.junit.Test;
-import org.mockito.ArgumentMatcher;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.resources.Project;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RuleFinder;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.core.review.ReviewDao;
-import org.sonar.core.review.ReviewDto;
-
-import java.util.Date;
-
-import static org.mockito.Matchers.anyVararg;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class ManualViolationInjectorTest {
-
- @Test
- public void shouldInjectManualViolationsDefinedByReviews() {
- final Date createdAt = DateUtils.parseDate("2011-12-25");
- ReviewDto review = new ReviewDto().setRuleId(3).setViolationPermanentId(100).setCreatedAt(createdAt).setSeverity(RulePriority.BLOCKER.toString());
- ReviewDao dao = mock(ReviewDao.class);
- when(dao.selectOpenByResourceId(eq(100L), (Predicate<ReviewDto>[])anyVararg())).thenReturn(Lists.newArrayList(review));
- RuleFinder ruleFinder = mock(RuleFinder.class);
- when(ruleFinder.findById(3)).thenReturn(new Rule());
- DecoratorContext context = mock(DecoratorContext.class);
- ManualViolationInjector injector = new ManualViolationInjector(dao, ruleFinder);
-
- injector.decorate(new Project("key").setId(100), context);
-
- verify(context, times(1)).saveViolation(argThat(new ArgumentMatcher<Violation>() {
- @Override
- public boolean matches(Object o) {
- Violation v = (Violation) o;
- return v.getPermanentId() == 100 && v.getRule() != null && v.isManual() && v.getCreatedAt().equals(createdAt)
- && v.getSeverity().equals(RulePriority.BLOCKER);
- }
- }));
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.collect.Lists;
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.JavaFile;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.violations.ViolationQuery;
-import org.sonar.batch.index.ResourcePersister;
-import org.sonar.core.persistence.AbstractDaoTestCase;
-import org.sonar.core.review.ReviewDao;
-import org.sonar.core.review.ReviewDto;
-
-import java.util.Collections;
-
-import static org.fest.assertions.Assertions.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
-
-public class ReviewWorkflowDecoratorTest extends AbstractDaoTestCase {
- private ReviewWorkflowDecorator decorator;
- private ReviewNotifications notifications;
-
- @Before
- public void init() {
- notifications = mock(ReviewNotifications.class);
- ResourcePersister persister = mock(ResourcePersister.class);
- Snapshot snapshot = new Snapshot();
- snapshot.setId(1);
- snapshot.setResourceId(100);
- when(persister.getSnapshot(any(Resource.class))).thenReturn(snapshot);
-
- decorator = new ReviewWorkflowDecorator(notifications, new ReviewDao(getMyBatis()), persister);
- }
-
- @Test
- public void shouldExecuteOnProject() {
- Project project = mock(Project.class);
- when(project.isLatestAnalysis()).thenReturn(true);
- assertThat(decorator.shouldExecuteOnProject(project)).isTrue();
- }
-
- @Test
- public void shouldExecuteOnProject_not_if_past_inspection() {
- Project project = mock(Project.class);
- when(project.isLatestAnalysis()).thenReturn(false);
- assertThat(decorator.shouldExecuteOnProject(project)).isFalse();
- }
-
- @Test
- public void shouldCloseReviewsOnResolvedViolations() {
- setupData("shouldCloseReviewsOnResolvedViolations");
- DecoratorContext context = mock(DecoratorContext.class);
- when(context.getViolations(any(ViolationQuery.class))).thenReturn(Collections.<Violation>emptyList());
-
- Resource resource = new JavaFile("org.foo.Bar");
- decorator.decorate(resource, context);
-
- verify(notifications, times(2)).notifyClosed(any(ReviewDto.class), any(Project.class), eq(resource));
- checkTables("shouldCloseReviewsOnResolvedViolations", new String[]{"updated_at"}, "reviews");
- }
-
- @Test
- public void shouldCloseResolvedManualViolations() {
- setupData("shouldCloseResolvedManualViolations");
- DecoratorContext context = mock(DecoratorContext.class);
- when(context.getViolations(any(ViolationQuery.class))).thenReturn(Collections.<Violation>emptyList());
-
- Resource resource = new JavaFile("org.foo.Bar");
- decorator.decorate(resource, context);
-
- verify(notifications).notifyClosed(any(ReviewDto.class), any(Project.class), eq(resource));
- checkTables("shouldCloseResolvedManualViolations", new String[]{"updated_at"}, "reviews");
- }
-
- @Test
- public void shouldReopenViolations() {
- setupData("shouldReopenViolations");
- DecoratorContext context = mock(DecoratorContext.class);
- Violation violation = new Violation(new Rule());
- violation.setPermanentId(1000);
- when(context.getViolations(any(ViolationQuery.class))).thenReturn(Lists.newArrayList(violation));
-
- Resource resource = new JavaFile("org.foo.Bar");
- decorator.decorate(resource, context);
-
- verify(notifications).notifyReopened(any(ReviewDto.class), any(Project.class), eq(resource));
- checkTables("shouldReopenViolations", new String[]{"updated_at"}, "reviews");
- }
-
- @Test
- public void hasUpToDateInformation() {
- assertThat(ReviewWorkflowDecorator.hasUpToDateInformation(
- new ReviewDto().setTitle("Design").setLine(30),
- new Violation(new Rule()).setMessage("Design").setLineId(30)))
- .isTrue();
-
-
- // different title
- assertThat(ReviewWorkflowDecorator.hasUpToDateInformation(
- new ReviewDto().setTitle("Design").setLine(30),
- new Violation(new Rule()).setMessage("Other").setLineId(30))
- ).isFalse();
-
- // different line
- assertThat(ReviewWorkflowDecorator.hasUpToDateInformation(
- new ReviewDto().setTitle("Design").setLine(300),
- new Violation(new Rule()).setMessage("Design").setLineId(200)))
- .isFalse();
-
- assertThat(ReviewWorkflowDecorator.hasUpToDateInformation(
- new ReviewDto().setTitle("Design").setLine(300),
- new Violation(new Rule()).setMessage("Design").setLineId(null)))
- .isFalse();
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.collect.Maps;
-import org.apache.commons.lang.ObjectUtils;
-import org.apache.commons.lang.time.DateUtils;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.ArgumentMatcher;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.RuleMeasure;
-import org.sonar.api.resources.*;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.Violation;
-import org.sonar.batch.components.PastSnapshot;
-import org.sonar.batch.components.TimeMachineConfiguration;
-import org.sonar.core.review.ReviewDao;
-import org.sonar.core.review.ReviewDto;
-
-import java.util.Arrays;
-import java.util.Date;
-import java.util.Map;
-
-import static org.fest.assertions.Assertions.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyDouble;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Mockito.*;
-
-public class ReviewsMeasuresDecoratorTest {
-
- private ReviewsMeasuresDecorator decorator;
- private DecoratorContext context;
-
- private Date rightNow;
- private Date tenDaysAgo;
- private Date fiveDaysAgo;
-
- @Before
- public void setUp() {
- ReviewDao reviewDao = mock(ReviewDao.class);
-
- rightNow = new Date();
- tenDaysAgo = DateUtils.addDays(rightNow, -10);
- fiveDaysAgo = DateUtils.addDays(rightNow, -5);
-
- PastSnapshot pastSnapshot = mock(PastSnapshot.class);
- when(pastSnapshot.getIndex()).thenReturn(1);
- when(pastSnapshot.getTargetDate()).thenReturn(fiveDaysAgo);
-
- PastSnapshot pastSnapshot2 = mock(PastSnapshot.class);
- when(pastSnapshot2.getIndex()).thenReturn(2);
- when(pastSnapshot2.getTargetDate()).thenReturn(tenDaysAgo);
-
- TimeMachineConfiguration timeMachineConfiguration = mock(TimeMachineConfiguration.class);
- when(timeMachineConfiguration.getProjectPastSnapshots()).thenReturn(Arrays.asList(pastSnapshot, pastSnapshot2));
-
- decorator = new ReviewsMeasuresDecorator(reviewDao, timeMachineConfiguration);
- context = mock(DecoratorContext.class);
- when(context.getMeasure(CoreMetrics.VIOLATIONS)).thenReturn(new Measure(CoreMetrics.VIOLATIONS, 35d));
- }
-
- @Test
- public void shouldExecuteOnProject() {
- ReviewsMeasuresDecorator decorator = new ReviewsMeasuresDecorator(null, null);
- Project project = new Project("foo");
- project.setLatestAnalysis(true);
- assertThat(decorator.shouldExecuteOnProject(project)).isTrue();
- }
-
- @Test
- public void shouldNotDecoratePersistableResource() throws Exception {
- ReviewsMeasuresDecorator decorator = new ReviewsMeasuresDecorator(null, null);
- DecoratorContext context = mock(DecoratorContext.class);
- Resource<?> resource = Method.createMethod("foo", null).setId(1);
- decorator.decorate(resource, context);
- verify(context, never()).saveMeasure(any(Metric.class), anyDouble());
- }
-
- /**
- * SONAR-3746
- */
- @Test
- public void shouldDecorateUnitTest() throws Exception {
- DecoratorContext context = mock(DecoratorContext.class);
- File resource = new File("foo");
- resource.setQualifier(Qualifiers.UNIT_TEST_FILE);
- resource.setId(1);
- decorator.decorate(resource, context);
- verify(context, atLeast(1)).saveMeasure(any(Metric.class), anyDouble());
- }
-
- @Test
- public void shouldTrackNewViolationsWithoutReview() throws Exception {
- Resource<?> resource = new File("foo").setId(1);
- Violation v1 = Violation.create((Rule) null, resource).setPermanentId(1); // test the null case for the created_at date
- Violation v2 = Violation.create((Rule) null, resource).setPermanentId(2).setCreatedAt(rightNow);
- Violation v3 = Violation.create((Rule) null, resource).setPermanentId(3).setCreatedAt(fiveDaysAgo);
- Violation v4 = Violation.create((Rule) null, resource).setPermanentId(4).setCreatedAt(fiveDaysAgo);
- Violation v5 = Violation.create((Rule) null, resource).setPermanentId(5).setCreatedAt(fiveDaysAgo);
- Violation v6 = Violation.create((Rule) null, resource).setPermanentId(6).setCreatedAt(tenDaysAgo);
- when(context.getViolations()).thenReturn(Arrays.asList(v1, v2, v3, v4, v5, v6));
-
- Map<Integer, ReviewDto> openReviewsByViolationPermanentIds = Maps.newHashMap();
- openReviewsByViolationPermanentIds.put(1, new ReviewDto());
- openReviewsByViolationPermanentIds.put(3, new ReviewDto());
-
- decorator.trackNewViolationsWithoutReview(context, openReviewsByViolationPermanentIds);
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_UNREVIEWED_VIOLATIONS, 1.0, 3.0)));
- }
-
- private class IsVariationMeasure extends ArgumentMatcher<Measure> {
- private Metric metric = null;
- private Double var1 = null;
- private Double var2 = null;
-
- public IsVariationMeasure(Metric metric, Double var1, Double var2) {
- this.metric = metric;
- this.var1 = var1;
- this.var2 = var2;
- }
-
- public boolean matches(Object o) {
- if (!(o instanceof Measure)) {
- return false;
- }
- Measure m = (Measure) o;
- return ObjectUtils.equals(metric, m.getMetric()) &&
- ObjectUtils.equals(var1, m.getVariation1()) &&
- ObjectUtils.equals(var2, m.getVariation2()) &&
- !(m instanceof RuleMeasure);
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import org.junit.Test;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.rules.RulePriority;
-
-import static org.fest.assertions.Assertions.assertThat;
-
-
-public class SeverityUtilsTest {
- @Test
- public void shouldConvertToViolationMetric() {
- assertThat(SeverityUtils.severityToViolationMetric(RulePriority.INFO)).isEqualTo(CoreMetrics.INFO_VIOLATIONS);
- assertThat(SeverityUtils.severityToViolationMetric(RulePriority.BLOCKER)).isEqualTo(CoreMetrics.BLOCKER_VIOLATIONS);
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.base.Predicate;
-import com.google.common.collect.Lists;
-import org.hamcrest.core.Is;
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-import org.sonar.core.review.ReviewDao;
-import org.sonar.core.review.ReviewDto;
-
-import java.util.Arrays;
-
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.*;
-
-public class ViolationSeverityUpdaterTest {
-
- private Resource project;
-
- @Before
- public void setUp() {
- project = new Project("foo").setId(10);
- }
-
- @Test
- public void shouldUpdateSeverityFixedByEndUsers() {
- ReviewDao reviewDao = mock(ReviewDao.class);
- when(reviewDao.selectOpenByResourceId(anyInt(), (Predicate<ReviewDto>[])anyVararg())).thenReturn(Lists.newArrayList(
- new ReviewDto().setManualSeverity(true).setSeverity("BLOCKER").setViolationPermanentId(380)));
- DecoratorContext context = mock(DecoratorContext.class);
- Violation newViolation = Violation.create(new Rule(), project).setSeverity(RulePriority.MINOR);
- Violation unchangedViolation = Violation.create(new Rule(), project).setPermanentId(120).setSeverity(RulePriority.MINOR);
- Violation changedViolation = Violation.create(new Rule(), project).setPermanentId(380).setSeverity(RulePriority.MINOR);
- when(context.getViolations()).thenReturn(Arrays.<Violation>asList(newViolation, unchangedViolation, changedViolation));
-
- ViolationSeverityUpdater updater = new ViolationSeverityUpdater(reviewDao);
- updater.decorate(project, context);
-
- assertThat(newViolation.getSeverity(), Is.is(RulePriority.MINOR));
- assertThat(unchangedViolation.getSeverity(), Is.is(RulePriority.MINOR));
- assertThat(changedViolation.getSeverity(), Is.is(RulePriority.BLOCKER));
- }
-
- /**
- * Optimization
- */
- @Test
- public void shouldNotLoadReviewsIfNoTrackedViolations() {
- ReviewDao reviewDao = mock(ReviewDao.class);
- DecoratorContext context = mock(DecoratorContext.class);
- Violation newViolation = Violation.create(new Rule(), project).setSeverity(RulePriority.MINOR);
- when(context.getViolations()).thenReturn(Arrays.<Violation>asList(newViolation));
-
- ViolationSeverityUpdater updater = new ViolationSeverityUpdater(reviewDao);
- updater.decorate(project, context);
-
- assertThat(newViolation.getSeverity(), Is.is(RulePriority.MINOR));
- verifyZeroInteractions(reviewDao);
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import com.google.common.collect.Lists;
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.MeasuresFilter;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.resources.Scopes;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.test.IsRuleMeasure;
-
-import java.util.Collections;
-import java.util.List;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyDouble;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class ViolationsDecoratorTest {
- private Rule ruleA1;
- private Rule ruleA2;
- private Rule ruleB1;
- private ViolationsDecorator decorator;
- private Resource resource;
- private DecoratorContext context;
-
- @Before
- public void before() {
- ruleA1 = Rule.create().setRepositoryKey("ruleA1").setKey("ruleA1").setName("nameA1");
- ruleA2 = Rule.create().setRepositoryKey("ruleA2").setKey("ruleA2").setName("nameA2");
- ruleB1 = Rule.create().setRepositoryKey("ruleB1").setKey("ruleB1").setName("nameB1");
-
- decorator = new ViolationsDecorator();
- resource = mock(Resource.class);
- context = mock(DecoratorContext.class);
- when(context.getResource()).thenReturn(resource);
- }
-
- @Test
- public void shouldCountViolations() {
- when(resource.getScope()).thenReturn(Scopes.PROJECT);
- when(context.getViolations()).thenReturn(createViolations());
- when(context.getChildrenMeasures(any(MeasuresFilter.class))).thenReturn(Collections.<Measure> emptyList());
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.VIOLATIONS, 4.0);
- }
-
- /**
- * See http://jira.codehaus.org/browse/SONAR-1729
- */
- @Test
- public void shouldNotCountViolationsIfMeasureAlreadyExists() {
- when(resource.getScope()).thenReturn(Scopes.PROJECT);
- when(context.getViolations()).thenReturn(createViolations());
- when(context.getChildrenMeasures(any(MeasuresFilter.class))).thenReturn(Collections.<Measure> emptyList());
- when(context.getMeasure(CoreMetrics.VIOLATIONS)).thenReturn(new Measure(CoreMetrics.VIOLATIONS, 3000.0));
- when(context.getMeasure(CoreMetrics.MAJOR_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.MAJOR_VIOLATIONS, 500.0));
-
- decorator.decorate(resource, context);
-
- verify(context, never()).saveMeasure(eq(CoreMetrics.VIOLATIONS), anyDouble());// not changed
- verify(context, never()).saveMeasure(eq(CoreMetrics.MAJOR_VIOLATIONS), anyDouble());// not changed
- verify(context, times(1)).saveMeasure(eq(CoreMetrics.CRITICAL_VIOLATIONS), anyDouble());// did not exist
- }
-
- @Test
- public void shouldSaveZeroOnProjects() {
- when(resource.getScope()).thenReturn(Scopes.PROJECT);
- when(context.getViolations()).thenReturn(Collections.<Violation> emptyList());
- when(context.getChildrenMeasures(any(MeasuresFilter.class))).thenReturn(Collections.<Measure> emptyList());
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.VIOLATIONS, 0.0);
- }
-
- @Test
- public void shouldSaveZeroOnDirectories() {
- when(resource.getScope()).thenReturn(Scopes.DIRECTORY);
- when(context.getViolations()).thenReturn(Collections.<Violation> emptyList());
- when(context.getChildrenMeasures(any(MeasuresFilter.class))).thenReturn(Collections.<Measure> emptyList());
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.VIOLATIONS, 0.0);
- }
-
- @Test
- public void shouldCountViolationsBySeverity() {
- when(resource.getScope()).thenReturn(Scopes.PROJECT);
- when(context.getViolations()).thenReturn(createViolations());
- when(context.getChildrenMeasures(any(MeasuresFilter.class))).thenReturn(Collections.<Measure> emptyList());
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.BLOCKER_VIOLATIONS, 0.0);
- verify(context).saveMeasure(CoreMetrics.CRITICAL_VIOLATIONS, 2.0);
- verify(context).saveMeasure(CoreMetrics.MAJOR_VIOLATIONS, 1.0);
- verify(context).saveMeasure(CoreMetrics.MINOR_VIOLATIONS, 1.0);
- verify(context).saveMeasure(CoreMetrics.INFO_VIOLATIONS, 0.0);
- }
-
- @Test
- public void shouldCountViolationsPerRule() {
- List<Violation> violations = Lists.newArrayList();
- violations.add(Violation.create(ruleA1, resource).setSeverity(RulePriority.CRITICAL));
- violations.add(Violation.create(ruleA1, resource).setSeverity(RulePriority.CRITICAL));
- violations.add(Violation.create(ruleA2, resource).setSeverity(RulePriority.MAJOR));
- when(context.getViolations()).thenReturn(violations);
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.CRITICAL_VIOLATIONS, ruleA1, 2.0)));
- verify(context, never()).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MAJOR_VIOLATIONS, ruleA1, 0.0)));
- verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MAJOR_VIOLATIONS, ruleA2, 1.0)));
- }
-
- @Test
- public void sameRuleShouldHaveDifferentSeverities() {
- List<Violation> violations = Lists.newArrayList();
- violations.add(Violation.create(ruleA1, resource).setSeverity(RulePriority.CRITICAL));
- violations.add(Violation.create(ruleA1, resource).setSeverity(RulePriority.CRITICAL));
- violations.add(Violation.create(ruleA1, resource).setSeverity(RulePriority.MINOR));
- when(context.getViolations()).thenReturn(violations);
-
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.CRITICAL_VIOLATIONS, ruleA1, 2.0)));
- verify(context).saveMeasure(argThat(new IsRuleMeasure(CoreMetrics.MINOR_VIOLATIONS, ruleA1, 1.0)));
- }
-
- private List<Violation> createViolations() {
- List<Violation> violations = Lists.newArrayList();
- violations.add(Violation.create(ruleA1, resource).setSeverity(RulePriority.CRITICAL));
- violations.add(Violation.create(ruleA1, resource).setSeverity(RulePriority.CRITICAL));
- violations.add(Violation.create(ruleA2, resource).setSeverity(RulePriority.MAJOR));
- violations.add(Violation.create(ruleB1, resource).setSeverity(RulePriority.MINOR));
- return violations;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import org.junit.Test;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.resources.Resource;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.*;
-
-public class ViolationsDensityDecoratorTest {
-
- @Test
- public void calculateDensity() {
- assertThat(ViolationsDensityDecorator.calculate(4000, 200), is(0.0));
- assertThat(ViolationsDensityDecorator.calculate(200, 200), is(0.0));
- assertThat(ViolationsDensityDecorator.calculate(50, 200), is(75.0));
- assertThat(ViolationsDensityDecorator.calculate(0, 200), is(100.0));
- }
-
-
- @Test
- public void decorateDensity() {
- Resource resource = mock(Resource.class);
- when(resource.getScope()).thenReturn(Resource.SCOPE_SET);
-
- DecoratorContext context = mock(DecoratorContext.class);
- when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 200.0));
- when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 50.0));
-
- ViolationsDensityDecorator decorator = new ViolationsDensityDecorator();
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, 75.0);
- }
-
- @Test
- public void noDensityIfNoNcloc() {
- Resource resource = mock(Resource.class);
- when(resource.getScope()).thenReturn(Resource.SCOPE_SET);
-
- DecoratorContext context = mock(DecoratorContext.class);
- when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 0.0));
- when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 50.0));
-
- ViolationsDensityDecorator decorator = new ViolationsDensityDecorator();
- decorator.decorate(resource, context);
-
- verify(context, never()).saveMeasure(eq(CoreMetrics.VIOLATIONS_DENSITY), anyDouble());
- }
-
- @Test
- public void saveDensityIfValueIsZero() {
- Resource resource = mock(Resource.class);
- when(resource.getScope()).thenReturn(Resource.SCOPE_SET);
-
- DecoratorContext context = mock(DecoratorContext.class);
- when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 200.0));
- when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 5000.0));
-
- ViolationsDensityDecorator decorator = new ViolationsDensityDecorator();
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, 0.0);
- }
-
- @Test
- public void densityIsHundredWhenNoDebt() {
- Resource resource = mock(Resource.class);
- when(resource.getScope()).thenReturn(Resource.SCOPE_SET);
-
- DecoratorContext context = mock(DecoratorContext.class);
- when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 200.0));
-
- ViolationsDensityDecorator decorator = new ViolationsDensityDecorator();
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, 100.0);
- }
-
- @Test
- public void densityIsHundredWhenDebtIsZero() {
- Resource resource = mock(Resource.class);
- when(resource.getScope()).thenReturn(Resource.SCOPE_SET);
-
- DecoratorContext context = mock(DecoratorContext.class);
- when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 200.0));
- when(context.getMeasure(CoreMetrics.WEIGHTED_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.WEIGHTED_VIOLATIONS, 0.0));
-
- ViolationsDensityDecorator decorator = new ViolationsDensityDecorator();
- decorator.decorate(resource, context);
-
- verify(context).saveMeasure(CoreMetrics.VIOLATIONS_DENSITY, 100.0);
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.sensors;
-
-import org.hamcrest.core.Is;
-import org.junit.Test;
-import org.sonar.api.CoreProperties;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.config.Settings;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.test.IsMeasure;
-
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class WeightedViolationsDecoratorTest {
-
- @Test
- public void testWeightedViolations() {
- Settings settings = new Settings();
- settings.setProperty(CoreProperties.CORE_RULE_WEIGHTS_PROPERTY, "BLOCKER=10;CRITICAL=5;MAJOR=2;MINOR=1;INFO=0");
- WeightedViolationsDecorator decorator = new WeightedViolationsDecorator(settings);
- DecoratorContext context = mock(DecoratorContext.class);
- when(context.getMeasure(CoreMetrics.INFO_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.INFO_VIOLATIONS, 50.0));
- when(context.getMeasure(CoreMetrics.CRITICAL_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.CRITICAL_VIOLATIONS, 80.0));
- when(context.getMeasure(CoreMetrics.BLOCKER_VIOLATIONS)).thenReturn(new Measure(CoreMetrics.BLOCKER_VIOLATIONS, 100.0));
-
- decorator.start();
- decorator.decorate(context);
-
- verify(context).saveMeasure(argThat(new IsMeasure(CoreMetrics.WEIGHTED_VIOLATIONS, (double) (100 * 10 + 80 * 5 + 50 * 0))));
- verify(context).saveMeasure(argThat(new IsMeasure(CoreMetrics.WEIGHTED_VIOLATIONS, "INFO=50;CRITICAL=80;BLOCKER=100")));
- }
-
- // SONAR-3092
- @Test
- public void doSaveZero() {
- Settings settings = new Settings();
- settings.setProperty(CoreProperties.CORE_RULE_WEIGHTS_PROPERTY, "BLOCKER=10;CRITICAL=5;MAJOR=2;MINOR=1;INFO=0");
- DecoratorContext context = mock(DecoratorContext.class);
-
- WeightedViolationsDecorator decorator = new WeightedViolationsDecorator(settings);
- decorator.start();
- decorator.decorate(context);
-
- verify(context).saveMeasure(any(Measure.class));
- }
-
- @Test
- public void shouldLoadSeverityWeightsAtStartup() {
- Settings settings = new Settings();
- settings.setProperty(CoreProperties.CORE_RULE_WEIGHTS_PROPERTY, "BLOCKER=2;CRITICAL=1;MAJOR=0;MINOR=0;INFO=0");
-
- WeightedViolationsDecorator decorator = new WeightedViolationsDecorator(settings);
- decorator.start();
-
- assertThat(decorator.getWeightsBySeverity().get(RulePriority.BLOCKER), Is.is(2));
- assertThat(decorator.getWeightsBySeverity().get(RulePriority.CRITICAL), Is.is(1));
- assertThat(decorator.getWeightsBySeverity().get(RulePriority.MAJOR), Is.is(0));
- }
-
- @Test
- public void weightsSettingShouldBeOptional() {
- Settings settings = new Settings();
- settings.setProperty(CoreProperties.CORE_RULE_WEIGHTS_PROPERTY, "BLOCKER=2");
-
- WeightedViolationsDecorator decorator = new WeightedViolationsDecorator(settings);
- decorator.start();
-
- assertThat(decorator.getWeightsBySeverity().get(RulePriority.MAJOR), Is.is(1));
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.timemachine;
-
-import com.google.common.collect.Lists;
-import org.apache.commons.lang.ObjectUtils;
-import org.apache.commons.lang.time.DateUtils;
-import org.hamcrest.BaseMatcher;
-import org.hamcrest.Description;
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.batch.DecoratorContext;
-import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.measures.Measure;
-import org.sonar.api.measures.Metric;
-import org.sonar.api.measures.RuleMeasure;
-import org.sonar.api.notifications.Notification;
-import org.sonar.api.notifications.NotificationManager;
-import org.sonar.api.resources.File;
-import org.sonar.api.resources.Project;
-import org.sonar.api.resources.Qualifiers;
-import org.sonar.api.resources.Resource;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-import org.sonar.batch.components.PastSnapshot;
-import org.sonar.batch.components.TimeMachineConfiguration;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Calendar;
-import java.util.Date;
-import java.util.GregorianCalendar;
-import java.util.List;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.argThat;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
-
-public class NewViolationsDecoratorTest {
- private Rule rule1;
- private Rule rule2;
- private Rule rule3;
-
- private NewViolationsDecorator decorator;
- private DecoratorContext context;
- private Resource<?> resource;
- private NotificationManager notificationManager;
-
- private Date rightNow;
- private Date tenDaysAgo;
- private Date fiveDaysAgo;
- private TimeMachineConfiguration timeMachineConfiguration;
-
- @Before
- public void setUp() {
- rightNow = new Date();
- tenDaysAgo = DateUtils.addDays(rightNow, -10);
- fiveDaysAgo = DateUtils.addDays(rightNow, -5);
-
- PastSnapshot pastSnapshot = mock(PastSnapshot.class);
- when(pastSnapshot.getIndex()).thenReturn(1);
- when(pastSnapshot.getTargetDate()).thenReturn(fiveDaysAgo);
-
- PastSnapshot pastSnapshot2 = mock(PastSnapshot.class);
- when(pastSnapshot2.getIndex()).thenReturn(2);
- when(pastSnapshot2.getTargetDate()).thenReturn(tenDaysAgo);
-
- timeMachineConfiguration = mock(TimeMachineConfiguration.class);
- when(timeMachineConfiguration.getProjectPastSnapshots()).thenReturn(Arrays.asList(pastSnapshot, pastSnapshot2));
-
- context = mock(DecoratorContext.class);
- resource = new File("com/foo/bar");
- when(context.getResource()).thenReturn(resource);
-
- notificationManager = mock(NotificationManager.class);
- decorator = new NewViolationsDecorator(timeMachineConfiguration, notificationManager);
-
- rule1 = Rule.create().setRepositoryKey("rule1").setKey("rule1").setName("name1");
- rule2 = Rule.create().setRepositoryKey("rule2").setKey("rule2").setName("name2");
- rule3 = Rule.create().setRepositoryKey("rule3").setKey("rule3").setName("name3");
- }
-
- @Test
- public void shouldExecuteIfLastAnalysis() {
- Project project = mock(Project.class);
-
- when(project.isLatestAnalysis()).thenReturn(false);
- assertThat(decorator.shouldExecuteOnProject(project), is(false));
-
- when(project.isLatestAnalysis()).thenReturn(true);
- assertThat(decorator.shouldExecuteOnProject(project), is(true));
- }
-
- @Test
- public void shouldBeDependedUponMetric() {
- assertThat(decorator.generatesMetric().size(), is(6));
- }
-
- @Test
- public void shouldCountViolationsAfterDate() {
- List<Violation> violations = createViolations();
-
- assertThat(decorator.countViolations(null, fiveDaysAgo), is(0));
- assertThat(decorator.countViolations(violations, fiveDaysAgo), is(1)); // 1 rightNow
- assertThat(decorator.countViolations(violations, tenDaysAgo), is(3)); // 1 rightNow + 2 fiveDaysAgo
- }
-
- @Test
- public void shouldClearCacheAfterExecution() {
- Violation violation1 = Violation.create(rule1, resource).setSeverity(RulePriority.CRITICAL).setCreatedAt(rightNow);
- Violation violation2 = Violation.create(rule2, resource).setSeverity(RulePriority.CRITICAL).setCreatedAt(rightNow);
- when(context.getViolations()).thenReturn(Arrays.asList(violation1)).thenReturn(Arrays.asList(violation2));
-
- decorator.decorate(resource, context);
- decorator.decorate(resource, context);
-
- verify(context, times(2)).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS, 1.0, 1.0)));
- verify(context, never()).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS, 2.0, 2.0)));
- }
-
- @Test
- public void severityViolations() {
- when(context.getViolations()).thenReturn(createViolations());
-
- decorator.decorate(resource, context);
-
- // remember : period1 is 5daysAgo, period2 is 10daysAgo
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_BLOCKER_VIOLATIONS, 0.0, 0.0)));
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS, 1.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_MAJOR_VIOLATIONS, 0.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_MINOR_VIOLATIONS, 0.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationMeasure(CoreMetrics.NEW_INFO_VIOLATIONS, 0.0, 0.0)));
- }
-
- @Test
- public void ruleViolations() {
- when(context.getViolations()).thenReturn(createViolations());
-
- decorator.decorate(resource, context);
-
- // remember : period1 is 5daysAgo, period2 is 10daysAgo
- verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_CRITICAL_VIOLATIONS, rule1, 1.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_MAJOR_VIOLATIONS, rule2, 0.0, 1.0)));
- verify(context).saveMeasure(argThat(new IsVariationRuleMeasure(CoreMetrics.NEW_MINOR_VIOLATIONS, rule3, 0.0, 1.0)));
- }
-
- @Test
- public void shouldNotNotifyIfNotLastestAnalysis() {
- Project project = mock(Project.class);
- when(project.isLatestAnalysis()).thenReturn(false);
- assertThat(decorator.shouldExecuteOnProject(project), is(false));
- }
-
- @Test
- public void shouldNotNotifyIfNotRootProject() throws Exception {
- Project project = mock(Project.class);
- when(project.getQualifier()).thenReturn(Qualifiers.MODULE);
-
- decorator.decorate(project, context);
-
- verify(notificationManager, never()).scheduleForSending(any(Notification.class));
- }
-
- @Test
- public void shouldNotNotifyIfNoNotEnoughPastSnapshots() throws Exception {
- Project project = new Project("key");
- // the #setUp method adds 2 snapshots: if last period analysis is 3, then it's not enough
- when(timeMachineConfiguration.getProjectPastSnapshots()).thenReturn(new ArrayList<PastSnapshot>());
-
- decorator.notifyNewViolations(project, context);
- verify(notificationManager, never()).scheduleForSending(any(Notification.class));
- }
-
- @Test
- public void shouldNotNotifyIfNoNewViolations() throws Exception {
- Project project = new Project("key");
- Measure m = new Measure(CoreMetrics.NEW_VIOLATIONS);
- when(context.getMeasure(CoreMetrics.NEW_VIOLATIONS)).thenReturn(m);
-
- // NULL is returned here
- decorator.notifyNewViolations(project, context);
- verify(notificationManager, never()).scheduleForSending(any(Notification.class));
-
- // 0 will be returned now
- m.setVariation1(0.0);
- decorator.notifyNewViolations(project, context);
- verify(notificationManager, never()).scheduleForSending(any(Notification.class));
- }
-
- @Test
- public void shouldNotNotifyUserIfFirstAnalysis() throws Exception {
- Project project = new Project("key").setName("LongName");
- project.setId(45);
- // PastSnapshot with targetDate==null means first analysis
- PastSnapshot pastSnapshot = new PastSnapshot("", null);
- when(timeMachineConfiguration.getProjectPastSnapshots()).thenReturn(Lists.newArrayList(pastSnapshot));
- Measure m = new Measure(CoreMetrics.NEW_VIOLATIONS).setVariation1(0.0);
- when(context.getMeasure(CoreMetrics.NEW_VIOLATIONS)).thenReturn(m);
-
- decorator.decorate(project, context);
- verify(notificationManager, never()).scheduleForSending(any(Notification.class));
- }
-
- @Test
- public void shouldNotifyUserAboutNewViolations() throws Exception {
- Project project = new Project("key").setName("LongName");
- project.setId(45);
- Calendar pastDate = new GregorianCalendar(2011, 10, 25);
- PastSnapshot pastSnapshot = new PastSnapshot("", pastDate.getTime());
- when(timeMachineConfiguration.getProjectPastSnapshots()).thenReturn(Lists.newArrayList(pastSnapshot, pastSnapshot));
- Measure m = new Measure(CoreMetrics.NEW_VIOLATIONS).setVariation1(32.0);
- when(context.getMeasure(CoreMetrics.NEW_VIOLATIONS)).thenReturn(m);
-
- decorator.decorate(project, context);
-
- DateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
- Notification notification = new Notification("new-violations")
- .setDefaultMessage("32 new violations on LongName.")
- .setFieldValue("count", "32")
- .setFieldValue("projectName", "LongName")
- .setFieldValue("projectKey", "key")
- .setFieldValue("projectId", "45")
- .setFieldValue("fromDate", dateformat.format(pastDate.getTime()));
- verify(notificationManager, times(1)).scheduleForSending(eq(notification));
- }
-
- private List<Violation> createViolations() {
- List<Violation> violations = Lists.newLinkedList();
- violations.add(Violation.create(rule1, resource).setSeverity(RulePriority.CRITICAL).setCreatedAt(rightNow));
- violations.add(Violation.create(rule1, resource).setSeverity(RulePriority.CRITICAL).setCreatedAt(tenDaysAgo));
- violations.add(Violation.create(rule2, resource).setSeverity(RulePriority.MAJOR).setCreatedAt(fiveDaysAgo));
- violations.add(Violation.create(rule2, resource).setSeverity(RulePriority.MAJOR).setCreatedAt(tenDaysAgo));
- violations.add(Violation.create(rule3, resource).setSeverity(RulePriority.MINOR).setCreatedAt(fiveDaysAgo));
- violations.add(Violation.create(rule3, resource).setSeverity(RulePriority.MINOR).setCreatedAt(tenDaysAgo));
- return violations;
- }
-
- private class IsVariationRuleMeasure extends BaseMatcher<Measure> {
- private Metric metric = null;
- private Rule rule = null;
- private Double var1 = null;
- private Double var2 = null;
-
- public IsVariationRuleMeasure(Metric metric, Rule rule, Double var1, Double var2) {
- this.metric = metric;
- this.rule = rule;
- this.var1 = var1;
- this.var2 = var2;
- }
-
- public boolean matches(Object o) {
- if (!(o instanceof RuleMeasure)) {
- return false;
- }
- RuleMeasure m = (RuleMeasure) o;
- return ObjectUtils.equals(metric, m.getMetric()) &&
- ObjectUtils.equals(rule, m.getRule()) &&
- ObjectUtils.equals(var1, m.getVariation1()) &&
- ObjectUtils.equals(var2, m.getVariation2());
- }
-
- public void describeTo(Description arg0) {
- }
- }
-
- private class IsVariationMeasure extends BaseMatcher<Measure> {
- private Metric metric = null;
- private Double var1 = null;
- private Double var2 = null;
-
- public IsVariationMeasure(Metric metric, Double var1, Double var2) {
- this.metric = metric;
- this.var1 = var1;
- this.var2 = var2;
- }
-
- public boolean matches(Object o) {
- if (!(o instanceof Measure)) {
- return false;
- }
- Measure m = (Measure) o;
- return ObjectUtils.equals(metric, m.getMetric()) &&
- ObjectUtils.equals(var1, m.getVariation1()) &&
- ObjectUtils.equals(var2, m.getVariation2()) &&
- !(m instanceof RuleMeasure);
- }
-
- public void describeTo(Description o) {
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.timemachine;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.database.model.RuleFailureModel;
-import org.sonar.api.database.model.Snapshot;
-import org.sonar.api.resources.JavaFile;
-import org.sonar.api.resources.Project;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.RulePriority;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.batch.index.ResourcePersister;
-import org.sonar.core.rule.DefaultRuleFinder;
-import org.sonar.jpa.test.AbstractDbUnitTestCase;
-
-import java.util.Arrays;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class ViolationPersisterDecoratorTest extends AbstractDbUnitTestCase {
-
- private ViolationPersisterDecorator decorator;
- private Rule rule1 = Rule.create("checkstyle", "com.puppycrawl.tools.checkstyle.checks.header.HeaderCheck", "Check Header");
- private Rule rule2 = Rule.create("checkstyle", "com.puppycrawl.tools.checkstyle.checks.coding.EqualsAvoidNullCheck", "Equals Avoid Null");
- private JavaFile javaFile = new JavaFile("org.foo.Bar");
- Project project = new Project("project");
- private ViolationTrackingDecorator tracker;
-
- @Before
- public void before() {
- setupData("shared");
- Snapshot snapshot = getSession().getSingleResult(Snapshot.class, "id", 1000);
- ResourcePersister resourcePersister = mock(ResourcePersister.class);
- when(resourcePersister.saveResource(any(Project.class), eq(javaFile))).thenReturn(snapshot);
- when(resourcePersister.getSnapshot(javaFile)).thenReturn(snapshot);
- tracker = mock(ViolationTrackingDecorator.class);
- decorator = new ViolationPersisterDecorator(tracker, resourcePersister, new DefaultRuleFinder(getSessionFactory()), getSession());
- }
-
- @Test
- public void shouldSaveViolations() {
- Violation violation1a = Violation.create(rule1, javaFile)
- .setSeverity(RulePriority.CRITICAL).setLineId(20).setCost(55.6).setMessage("the message")
- .setChecksum("checksum").setCreatedAt(DateUtils.parseDate("2010-12-25"));
- Violation violation1b = Violation.create(rule1, javaFile)
- .setSeverity(RulePriority.CRITICAL).setLineId(50).setCost(80.0);
- Violation violation2 = Violation.create(rule2, javaFile)
- .setSeverity(RulePriority.MINOR).setSwitchedOff(true);
-
- decorator.saveViolations(project, Arrays.asList(violation1a, violation1b, violation2));
-
- checkTables("shouldSaveViolations", "rule_failures");
- }
-
- @Test
- public void shouldCopyPermanentIdFromReferenceViolation() {
- RuleFailureModel referenceViolation = getSession().getSingleResult(RuleFailureModel.class, "id", 1);
- Violation violation = Violation.create(rule1, javaFile).setSeverity(RulePriority.MAJOR).setMessage("new message");
- when(tracker.getReferenceViolation(violation)).thenReturn(referenceViolation);
-
- decorator.saveViolations(project, Arrays.asList(violation));
-
- checkTables("shouldCopyPermanentIdFromReferenceViolation", "rule_failures");
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.timemachine;
-
-import com.google.common.collect.Lists;
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.database.model.RuleFailureModel;
-import org.sonar.api.resources.Project;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.utils.DateUtils;
-
-import java.util.Collections;
-import java.util.Date;
-import java.util.Map;
-
-import static org.fest.assertions.Assertions.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class ViolationTrackingDecoratorTest {
-
- private ViolationTrackingDecorator decorator;
- private final Date analysisDate = DateUtils.parseDate("2010-12-25");
-
- @Before
- public void setUp() {
- Project project = mock(Project.class);
- when(project.getAnalysisDate()).thenReturn(analysisDate);
- decorator = new ViolationTrackingDecorator(project, null, null);
- }
-
- @Test
- public void permanentIdShouldBeThePrioritaryFieldToCheck() {
- RuleFailureModel referenceViolation1 = newReferenceViolation("message", 10, 1, "checksum1").setPermanentId(100);
- RuleFailureModel referenceViolation2 = newReferenceViolation("message", 18, 1, "checksum2").setPermanentId(200);
- Violation newViolation = newViolation("message", 10, 1, "checksum1"); // exactly the fields of referenceViolation1
- newViolation.setPermanentId(200);
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation1, referenceViolation2));
- assertThat(decorator.getReferenceViolation(newViolation)).isSameAs(referenceViolation2); // same permanent id
- assertThat(newViolation.isNew()).isFalse();
- }
-
- @Test
- public void checksumShouldHaveGreaterPriorityThanLine() {
- RuleFailureModel referenceViolation1 = newReferenceViolation("message", 1, 50, "checksum1");
- RuleFailureModel referenceViolation2 = newReferenceViolation("message", 3, 50, "checksum2");
-
- Violation newViolation1 = newViolation("message", 3, 50, "checksum1");
- Violation newViolation2 = newViolation("message", 5, 50, "checksum2");
-
- decorator.mapViolations(Lists.newArrayList(newViolation1, newViolation2), Lists.newArrayList(referenceViolation1, referenceViolation2));
- assertThat(decorator.getReferenceViolation(newViolation1)).isSameAs(referenceViolation1);
- assertThat(newViolation1.isNew()).isFalse();
- assertThat(decorator.getReferenceViolation(newViolation2)).isSameAs(referenceViolation2);
- assertThat(newViolation2.isNew()).isFalse();
- }
-
- /**
- * SONAR-2928
- */
- @Test
- public void sameRuleAndNullLineAndChecksumButDifferentMessages() {
- Violation newViolation = newViolation("new message", null, 50, "checksum1");
- RuleFailureModel referenceViolation = newReferenceViolation("old message", null, 50, "checksum1");
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isSameAs(referenceViolation);
- assertThat(newViolation.isNew()).isFalse();
- }
-
- @Test
- public void sameRuleAndLineAndChecksumButDifferentMessages() {
- Violation newViolation = newViolation("new message", 1, 50, "checksum1");
- RuleFailureModel referenceViolation = newReferenceViolation("old message", 1, 50, "checksum1");
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isSameAs(referenceViolation);
- assertThat(newViolation.isNew()).isFalse();
- }
-
- @Test
- public void sameRuleAndLineMessage() {
- Violation newViolation = newViolation("message", 1, 50, "checksum1");
- RuleFailureModel referenceViolation = newReferenceViolation("message", 1, 50, "checksum2");
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isSameAs(referenceViolation);
- assertThat(newViolation.isNew()).isFalse();
- }
-
- @Test
- public void shouldIgnoreReferenceMeasureWithoutChecksum() {
- Violation newViolation = newViolation("message", 1, 50, null);
- RuleFailureModel referenceViolation = newReferenceViolation("message", 1, 51, null);
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isNull();
- assertThat(newViolation.isNew()).isTrue();
- }
-
- @Test
- public void sameRuleAndMessageAndChecksumButDifferentLine() {
- Violation newViolation = newViolation("message", 1, 50, "checksum1");
- RuleFailureModel referenceViolation = newReferenceViolation("message", 2, 50, "checksum1");
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isSameAs(referenceViolation);
- assertThat(newViolation.isNew()).isFalse();
- }
-
- /**
- * SONAR-2812
- */
- @Test
- public void sameChecksumAndRuleButDifferentLineAndDifferentMessage() {
- Violation newViolation = newViolation("new message", 1, 50, "checksum1");
- RuleFailureModel referenceViolation = newReferenceViolation("old message", 2, 50, "checksum1");
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isSameAs(referenceViolation);
- assertThat(newViolation.isNew()).isFalse();
- }
-
- @Test
- public void shouldCreateNewViolationWhenSameRuleSameMessageButDifferentLineAndChecksum() {
- Violation newViolation = newViolation("message", 1, 50, "checksum1");
- RuleFailureModel referenceViolation = newReferenceViolation("message", 2, 50, "checksum2");
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isNull();
- assertThat(newViolation.isNew()).isTrue();
- }
-
- @Test
- public void shouldNotTrackViolationIfDifferentRule() {
- Violation newViolation = newViolation("message", 1, 50, "checksum1");
- RuleFailureModel referenceViolation = newReferenceViolation("message", 1, 51, "checksum1");
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isNull();
- assertThat(newViolation.isNew()).isTrue();
- }
-
- @Test
- public void shouldCompareViolationsWithDatabaseFormat() {
- // violation messages are trimmed and can be abbreviated when persisted in database.
- // Comparing violation messages must use the same format.
- Violation newViolation = newViolation(" message ", 1, 50, "checksum1");
- RuleFailureModel referenceViolation = newReferenceViolation(" message ", 1, 50, "checksum2");
-
- decorator.mapViolations(Lists.newArrayList(newViolation), Lists.newArrayList(referenceViolation));
- assertThat(decorator.getReferenceViolation(newViolation)).isSameAs(referenceViolation);
- assertThat(newViolation.isNew()).isFalse();
- }
-
- @Test
- public void shouldSetDateOfNewViolations() {
- Violation newViolation = newViolation("message", 1, 50, "checksum");
- assertThat(newViolation.getCreatedAt()).isNull();
-
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(Lists.newArrayList(newViolation), Collections.<RuleFailureModel> emptyList());
- assertThat(mapping.size()).isEqualTo(0);
- assertThat(newViolation.getCreatedAt()).isEqualTo(analysisDate);
- assertThat(newViolation.isNew()).isTrue();
- }
-
- @Test
- public void shouldCopyDateWhenNotNew() {
- Violation newViolation = newViolation("message", 1, 50, "checksum");
- RuleFailureModel referenceViolation = newReferenceViolation("", 1, 50, "checksum");
- Date referenceDate = DateUtils.parseDate("2009-05-18");
- referenceViolation.setCreatedAt(referenceDate);
- assertThat(newViolation.getCreatedAt()).isNull();
-
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(Lists.newArrayList(newViolation), Lists.<RuleFailureModel> newArrayList(referenceViolation));
- assertThat(mapping.size()).isEqualTo(1);
- assertThat(newViolation.getCreatedAt()).isEqualTo(referenceDate);
- assertThat(newViolation.isNew()).isFalse();
- }
-
- private Violation newViolation(String message, Integer lineId, int ruleId) {
- Rule rule = Rule.create().setKey("rule");
- rule.setId(ruleId);
- return Violation.create(rule, null).setLineId(lineId).setMessage(message);
- }
-
- private Violation newViolation(String message, Integer lineId, int ruleId, String lineChecksum) {
- return newViolation(message, lineId, ruleId).setChecksum(lineChecksum);
- }
-
- private RuleFailureModel newReferenceViolation(String message, Integer lineId, int ruleId, String lineChecksum) {
- RuleFailureModel referenceViolation = new RuleFailureModel();
- referenceViolation.setId(violationId++);
- referenceViolation.setLine(lineId);
- referenceViolation.setMessage(message);
- referenceViolation.setRuleId(ruleId);
- referenceViolation.setChecksum(lineChecksum);
- return referenceViolation;
- }
-
- private int violationId = 0;
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.plugins.core.timemachine;
-
-import com.google.common.base.Charsets;
-import com.google.common.io.Resources;
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.database.model.RuleFailureModel;
-import org.sonar.api.resources.Project;
-import org.sonar.api.rules.Rule;
-import org.sonar.api.rules.Violation;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.batch.scan.LastSnapshots;
-
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.Date;
-import java.util.Map;
-
-import static org.hamcrest.Matchers.equalTo;
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class ViolationTrackingTest {
-
- private final Date analysisDate = DateUtils.parseDate("2010-12-25");
-
- private ViolationTrackingDecorator decorator;
-
- private Project project;
- private LastSnapshots lastSnapshots;
-
- @Before
- public void setUp() {
- project = mock(Project.class);
- when(project.getAnalysisDate()).thenReturn(analysisDate);
- lastSnapshots = mock(LastSnapshots.class);
- decorator = new ViolationTrackingDecorator(project, lastSnapshots, null);
- }
-
- @Test
- public void pastViolationNotAssiciatedWithLineShouldNotCauseNPE() throws Exception {
- when(lastSnapshots.getSource(project)).thenReturn(load("example2-v1"));
- String source = load("example2-v2");
-
- RuleFailureModel referenceViolation1 = newReferenceViolation("2 branches need to be covered", null, 50);
-
- Violation newViolation1 = newViolation("Indentation", 9, 50);
- newViolation1.setChecksum("foo");
-
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(
- Arrays.asList(newViolation1),
- Arrays.asList(referenceViolation1),
- source, project);
-
- assertThat(mapping.isEmpty(), is(true));
- assertThat(newViolation1.isNew(), is(true));
- }
-
- @Test
- public void newViolationNotAssiciatedWithLineShouldNotCauseNPE() throws Exception {
- when(lastSnapshots.getSource(project)).thenReturn(load("example2-v1"));
- String source = load("example2-v2");
-
- RuleFailureModel referenceViolation1 = newReferenceViolation("Indentation", 7, 50);
-
- Violation newViolation1 = newViolation("1 branch need to be covered", null, 50);
- newViolation1.setChecksum("foo");
-
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(
- Arrays.asList(newViolation1),
- Arrays.asList(referenceViolation1),
- source, project);
-
- assertThat(mapping.isEmpty(), is(true));
- assertThat(newViolation1.isNew(), is(true));
- }
-
- /**
- * SONAR-2928
- */
- @Test
- public void violationNotAssociatedWithLine() throws Exception {
- when(lastSnapshots.getSource(project)).thenReturn(load("example2-v1"));
- String source = load("example2-v2");
-
- RuleFailureModel referenceViolation1 = newReferenceViolation("2 branches need to be covered", null, 50);
-
- Violation newViolation1 = newViolation("1 branch need to be covered", null, 50);
-
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(
- Arrays.asList(newViolation1),
- Arrays.asList(referenceViolation1),
- source, project);
-
- assertThat(newViolation1.isNew(), is(false));
- assertThat(mapping.get(newViolation1), equalTo(referenceViolation1));
- }
-
- /**
- * SONAR-3072
- */
- @Test
- public void example1() throws Exception {
- when(lastSnapshots.getSource(project)).thenReturn(load("example1-v1"));
- String source = load("example1-v2");
-
- RuleFailureModel referenceViolation1 = newReferenceViolation("Indentation", 7, 50);
- RuleFailureModel referenceViolation2 = newReferenceViolation("Indentation", 11, 50);
-
- Violation newViolation1 = newViolation("Indentation", 9, 50);
- Violation newViolation2 = newViolation("Indentation", 13, 50);
- Violation newViolation3 = newViolation("Indentation", 17, 50);
- Violation newViolation4 = newViolation("Indentation", 21, 50);
-
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(
- Arrays.asList(newViolation1, newViolation2, newViolation3, newViolation4),
- Arrays.asList(referenceViolation1, referenceViolation2),
- source, project);
-
- assertThat(newViolation1.isNew(), is(true));
- assertThat(newViolation2.isNew(), is(true));
- assertThat(newViolation3.isNew(), is(false));
- assertThat(mapping.get(newViolation3), equalTo(referenceViolation1));
- assertThat(newViolation4.isNew(), is(false));
- assertThat(mapping.get(newViolation4), equalTo(referenceViolation2));
- }
-
- /**
- * SONAR-3072
- */
- @Test
- public void example2() throws Exception {
- when(lastSnapshots.getSource(project)).thenReturn(load("example2-v1"));
- String source = load("example2-v2");
-
- RuleFailureModel referenceViolation1 = newReferenceViolation("SystemPrintln", 5, 50);
-
- Violation newViolation1 = newViolation("SystemPrintln", 6, 50);
- Violation newViolation2 = newViolation("SystemPrintln", 10, 50);
- Violation newViolation3 = newViolation("SystemPrintln", 14, 50);
-
- Map<Violation, RuleFailureModel> mapping = decorator.mapViolations(
- Arrays.asList(newViolation1, newViolation2, newViolation3),
- Arrays.asList(referenceViolation1),
- source, project);
-
- assertThat(newViolation1.isNew(), is(true));
- assertThat(newViolation2.isNew(), is(false));
- assertThat(mapping.get(newViolation2), equalTo(referenceViolation1));
- assertThat(newViolation3.isNew(), is(true));
- }
-
- private Violation newViolation(String message, Integer lineId, int ruleId) {
- Rule rule = Rule.create().setKey("rule");
- rule.setId(ruleId);
- return Violation.create(rule, null).setLineId(lineId).setMessage(message);
- }
-
- private RuleFailureModel newReferenceViolation(String message, Integer lineId, int ruleId) {
- RuleFailureModel referenceViolation = new RuleFailureModel();
- referenceViolation.setId(violationId++);
- referenceViolation.setLine(lineId);
- referenceViolation.setMessage(message);
- referenceViolation.setRuleId(ruleId);
- return referenceViolation;
- }
-
- private int violationId = 0;
-
- private static String load(String name) throws IOException {
- return Resources.toString(ViolationTrackingTest.class.getResource("ViolationTrackingTest/" + name + ".txt"), Charsets.UTF_8);
- }
-
-}
+++ /dev/null
-<dataset>
-
- <snapshots id="1" purge_status="[null]" project_id="100" status="P" islast="false"/>
-
-
- <reviews id="1" project_id="[null]" resource_id="100" status="OPEN" rule_failure_permanent_id="1000"
- resolution="[null]" created_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="true" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
- <reviews id="2" project_id="[null]" resource_id="100" status="CLOSED" rule_failure_permanent_id="1000"
- resolution="FIXED" created_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="true" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
-
-</dataset>
\ No newline at end of file
+++ /dev/null
-<dataset>
-
- <snapshots id="1" purge_status="[null]" project_id="100" status="P" islast="false"/>
-
-
- <reviews id="1" project_id="[null]" resource_id="100" status="OPEN" rule_failure_permanent_id="1000"
- resolution="[null]" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="true" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
- <reviews id="2" project_id="[null]" resource_id="100" status="RESOLVED" rule_failure_permanent_id="1000"
- resolution="FIXED" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="true" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
-
-</dataset>
\ No newline at end of file
+++ /dev/null
-<dataset>
-
- <snapshots id="1" purge_status="[null]" project_id="100" status="P" islast="false"/>
-
- <projects long_name="[null]" id="1" scope="PRJ" qualifier="TRK" kee="org.foo.Bar" name="org.foo.Bar"
- root_id="[null]"
- description="[null]"
- enabled="true" language="java" copy_resource_id="[null]" person_id="[null]"/>
-
- <reviews id="1" project_id="[null]" resource_id="100" status="OPEN" rule_failure_permanent_id="1000"
- resolution="[null]" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="true" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
- <reviews id="2" project_id="[null]" resource_id="100" status="RESOLVED" rule_failure_permanent_id="1000"
- resolution="FIXED" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="true" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
-
-</dataset>
\ No newline at end of file
+++ /dev/null
-<dataset>
-
- <snapshots id="1" purge_status="[null]" project_id="100" status="P" islast="false"/>
-
-
- <!-- open reviews ==> CLOSED -->
- <reviews id="1" project_id="[null]" resource_id="100" status="CLOSED" rule_failure_permanent_id="1000"
- resolution="[null]" created_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
- <reviews id="2" project_id="[null]" resource_id="100" status="CLOSED" rule_failure_permanent_id="1001"
- resolution="FALSE-POSITIVE" created_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
- <!-- closed reviews -->
- <reviews id="3" project_id="[null]" resource_id="100" status="CLOSED" rule_failure_permanent_id="1002"
- resolution="RESOLVED" created_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
-
- <!-- other resource -->
- <reviews id="4" project_id="[null]" resource_id="101" status="OPEN" rule_failure_permanent_id="1100"
- resolution="[null]" created_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-</dataset>
\ No newline at end of file
+++ /dev/null
-<dataset>
-
- <snapshots id="1" purge_status="[null]" project_id="100" status="P" islast="false"/>
-
-
- <!-- open reviews -->
- <reviews id="1" project_id="[null]" resource_id="100" status="OPEN" rule_failure_permanent_id="1000"
- resolution="[null]" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
- <reviews id="2" project_id="[null]" resource_id="100" status="RESOLVED" rule_failure_permanent_id="1001"
- resolution="FALSE-POSITIVE" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
- <!-- closed reviews -->
- <reviews id="3" project_id="[null]" resource_id="100" status="CLOSED" rule_failure_permanent_id="1002"
- resolution="RESOLVED" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
-
- <!-- other resource -->
- <reviews id="4" project_id="[null]" resource_id="101" status="OPEN" rule_failure_permanent_id="1100"
- resolution="[null]" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-</dataset>
\ No newline at end of file
+++ /dev/null
-<dataset>
-
- <snapshots id="1" purge_status="[null]" project_id="100" status="P" islast="false"/>
-
-
- <reviews id="1" project_id="[null]" resource_id="100" status="REOPENED" rule_failure_permanent_id="1000"
- resolution="[null]" created_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
-
-</dataset>
\ No newline at end of file
+++ /dev/null
-<dataset>
-
- <snapshots id="1" purge_status="[null]" project_id="100" status="P" islast="false"/>
-
-
- <reviews id="1" project_id="[null]" resource_id="100" status="RESOLVED" rule_failure_permanent_id="1000"
- resolution="FIXED" created_at="[null]" updated_at="[null]"
- resource_line="[null]" severity="[null]" user_id="[null]" rule_id="[null]" manual_violation="false" manual_severity="false"
- title="[null]" assignee_id="[null]" data="[null]"/>
-
-
-</dataset>
\ No newline at end of file
+++ /dev/null
-<dataset>
- <reviews
- id="1"
- status="OPEN"
- rule_failure_permanent_id="1"
- resource_id="1"
- title="message OLD"
- resource_line="0"
- resolution="[null]"
- created_at="[null]"
- updated_at="[null]"
- project_id="[null]"
- severity="[null]"
- user_id="[null]"
- rule_id="[null]"
- manual_violation="false"
- manual_severity="false"
- data="[null]"/>
- <reviews
- id="2"
- status="OPEN"
- rule_failure_permanent_id="2"
- resource_id="1"
- title="message 2"
- resource_line="2"
- rule_id="[null]"
- manual_violation="false"
- manual_severity="false"
- data="[null]"/>
- <reviews
- id="3"
- status="OPEN"
- rule_failure_permanent_id="3"
- resource_id="1"
- title="message 3"
- resource_line="0"
- rule_id="[null]"
- manual_violation="false"
- manual_severity="false"
- data="[null]"/>
- <reviews
- id="4"
- status="OPEN"
- rule_failure_permanent_id="4"
- resource_id="1"
- title="message OLD"
- resource_line="4"
- rule_id="[null]"
- manual_violation="false"
- manual_severity="false"
- data="[null]"/>
- <reviews
- id="5"
- status="OPEN"
- rule_failure_permanent_id="5"
- resource_id="1"
- title="message 5"
- resource_line="[null]"
- rule_id="[null]"
- manual_violation="false"
- manual_severity="false"
- data="[null]"/>
- <reviews
- id="6"
- status="OPEN"
- rule_failure_permanent_id="6"
- resource_id="1"
- title="message OLD"
- resource_line="[null]"
- rule_id="[null]"
- manual_violation="false"
- manual_severity="false"
- data="[null]"/>
-
-</dataset>
\ No newline at end of file
scope="FIL" qualifier="CLA" created_at="2008-11-01 13:58:00.00" build_date="2008-11-01 13:58:00.00" version="[null]" path=""
status="U" islast="false" depth="3"/>
- <rule_failures switched_off="false" permanent_id="1" ID="1" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="3" MESSAGE="old message" LINE="10" COST="[null]"
- created_at="2008-11-01 13:58:00.00" checksum="[null]" person_id="[null]"/>
- <rule_failures switched_off="true" permanent_id="2" ID="2" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="3" MESSAGE="old message" LINE="10" COST="[null]"
- created_at="2008-11-01 13:58:00.00" checksum="[null]" person_id="[null]"/>
</dataset>
scope="FIL" qualifier="CLA" created_at="2008-11-01 13:58:00.00" build_date="2008-11-01 13:58:00.00" version="[null]" path=""
status="U" islast="false" depth="3"/>
- <rule_failures switched_off="false" permanent_id="1" ID="1" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="3" MESSAGE="old message" LINE="10" COST="[null]"
- created_at="2008-11-01 13:58:00.00" checksum="[null]" person_id="[null]"/>
- <rule_failures switched_off="true" permanent_id="2" ID="2" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="3" MESSAGE="old message" LINE="10" COST="[null]"
- created_at="2008-11-01 13:58:00.00" checksum="[null]" person_id="[null]"/>
-
- <rule_failures switched_off="false" permanent_id="1" ID="3" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="2" MESSAGE="new message" LINE="[null]" COST="[null]"
- created_at="[null]" checksum="[null]" person_id="[null]"/>
</dataset>
scope="FIL" qualifier="CLA" created_at="2008-11-01 13:58:00.00" build_date="2008-11-01 13:58:00.00" version="[null]" path=""
status="U" islast="false" depth="3"/>
- <rule_failures switched_off="false" permanent_id="1" ID="1" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="3" MESSAGE="old message" LINE="10" COST="[null]"
- created_at="2008-11-01 13:58:00.00" checksum="[null]" person_id="[null]"/>
- <rule_failures switched_off="true" permanent_id="2" ID="2" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="3" MESSAGE="old message" LINE="10" COST="[null]"
- created_at="2008-11-01 13:58:00.00" checksum="[null]" person_id="[null]"/>
- <rule_failures switched_off="false" permanent_id="3" ID="3" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="3" MESSAGE="the message" LINE="20" COST="55.6"
- created_at="2010-12-25 00:00:00.00" checksum="checksum" person_id="[null]"/>
- <rule_failures switched_off="false" permanent_id="4" ID="4" SNAPSHOT_ID="1000" RULE_ID="30" FAILURE_LEVEL="3" MESSAGE="[null]" LINE="50" COST="80" created_at="[null]"
- checksum="[null]" person_id="[null]"/>
- <rule_failures switched_off="true" permanent_id="5" ID="5" SNAPSHOT_ID="1000" RULE_ID="31" FAILURE_LEVEL="1" MESSAGE="[null]" LINE="[null]" COST="[null]" created_at="[null]"
- checksum="[null]" person_id="[null]"/>
</dataset>
import org.sonar.api.config.Settings;
import org.sonar.api.database.DatabaseSession;
import org.sonar.api.database.model.ResourceModel;
-import org.sonar.api.database.model.RuleFailureModel;
import org.sonar.api.database.model.Snapshot;
import org.sonar.api.database.model.SnapshotSource;
import org.sonar.api.resources.Resource;
import org.sonar.api.utils.HttpDownloader;
import org.sonar.batch.bootstrap.ServerClient;
-import javax.annotation.CheckForNull;
import javax.persistence.Query;
-import java.util.List;
-
public class LastSnapshots implements BatchComponent {
private final Settings settings;
this.server = server;
}
- /**
- * Return null if this is the first scan (no last scan).
- */
- @CheckForNull
- public List<RuleFailureModel> getViolations(Resource resource) {
- Snapshot snapshot = getSnapshot(resource);
- if (snapshot != null) {
- return session.getResults(RuleFailureModel.class, "snapshotId", snapshot.getId());
- }
- return null;
- }
-
public String getSource(Resource resource) {
String source = "";
if (ResourceUtils.isFile(resource)) {
import org.junit.rules.ExpectedException;
import org.sonar.api.CoreProperties;
import org.sonar.api.config.Settings;
-import org.sonar.api.database.model.RuleFailureModel;
import org.sonar.api.resources.File;
import org.sonar.api.resources.Project;
import org.sonar.api.utils.HttpDownloader;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.List;
import static org.fest.assertions.Assertions.assertThat;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.verifyZeroInteractions;
-import static org.mockito.Mockito.when;
+import static org.mockito.Mockito.*;
public class LastSnapshotsTest extends AbstractDbUnitTestCase {
@Rule
public ExpectedException thrown = ExpectedException.none();
- @Test
- public void should_return_null_violations_if_no_last_snapshot() {
- setupData("no_last_snapshot");
- ServerClient server = mock(ServerClient.class);
-
- LastSnapshots lastSnapshots = new LastSnapshots(new Settings(), getSession(), server);
-
- assertThat(lastSnapshots.getViolations(new File("org/foo", "Bar.c"))).isNull();
- verifyZeroInteractions(server);
- }
-
- @Test
- public void should_get_violations_of_last_snapshot() {
- setupData("last_snapshot");
- ServerClient server = mock(ServerClient.class);
-
- LastSnapshots lastSnapshots = new LastSnapshots(new Settings(), getSession(), server);
-
- List<RuleFailureModel> violations = lastSnapshots.getViolations(newFile());
- assertThat(violations).hasSize(1);
- assertThat(violations.get(0).getChecksum()).isEqualTo("ABCDE");
- verifyZeroInteractions(server);
- }
-
@Test
public void should_get_source_of_last_snapshot() {
setupData("last_snapshot");
<SNAPSHOT_SOURCES ID="1" SNAPSHOT_ID="4" DATA="source code of Class1"/>
<SNAPSHOT_SOURCES ID="2" SNAPSHOT_ID="5" DATA="source code of Class2"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="1" SNAPSHOT_ID="4" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg1" COST="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="2" SNAPSHOT_ID="4" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg2" COST="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="3" SNAPSHOT_ID="4" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg3" COST="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="4" SNAPSHOT_ID="4" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg4" COST="[null]"/>
-
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="5" SNAPSHOT_ID="5" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg5" COST="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="6" SNAPSHOT_ID="5" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg6" COST="[null]"/>
-
<!-- measures at project level -->
<project_measures characteristic_id="[null]" url="[null]" variation_value_1="[null]" variation_value_2="[null]" variation_value_3="[null]" variation_value_4="[null]" variation_value_5="[null]"
rule_priority="[null]"
<SNAPSHOT_SOURCES ID="1" SNAPSHOT_ID="4" DATA="source code of Class1"/>
<SNAPSHOT_SOURCES ID="2" SNAPSHOT_ID="5" DATA="source code of Class2"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="1" SNAPSHOT_ID="4" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg1" COST="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="2" SNAPSHOT_ID="4" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg2" COST="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="3" SNAPSHOT_ID="4" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg3" COST="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="4" SNAPSHOT_ID="4" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg4" COST="[null]"/>
-
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="5" SNAPSHOT_ID="5" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg5" COST="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="6" SNAPSHOT_ID="5" RULE_ID="1" FAILURE_LEVEL="2" MESSAGE="msg6" COST="[null]"/>
-
<!-- measures at project level -->
<project_measures characteristic_id="[null]" url="[null]" variation_value_1="[null]" variation_value_2="[null]" variation_value_3="[null]" variation_value_4="[null]" variation_value_5="[null]"
rule_priority="[null]"
<snapshots id="1000" project_id="100" status="P" islast="[false]" purge_status="[null]"/>
<snapshots id="1100" project_id="100" status="P" islast="[true]" purge_status="[null]"/>
<snapshot_sources ID="10000" SNAPSHOT_ID="1100" DATA="this is bar"/>
- <rule_failures ID="1000000" SNAPSHOT_ID="1100" RULE_ID="1"
- switched_off="[null]" permanent_id="[null]" FAILURE_LEVEL="2"
- MESSAGE="msg1" LINE="[null]" COST="[null]"
- created_at="2008-12-02 13:58:00.00"
- checksum="ABCDE" person_id="[null]"/>
</dataset>
\ No newline at end of file
import org.sonar.core.resource.ResourceDao;
import org.sonar.core.resource.ResourceIndexerDao;
import org.sonar.core.resource.ResourceKeyUpdaterDao;
-import org.sonar.core.review.ReviewCommentDao;
-import org.sonar.core.review.ReviewDao;
import org.sonar.core.rule.RuleDao;
import org.sonar.core.source.jdbc.SnapshotDataDao;
import org.sonar.core.template.LoadedTemplateDao;
ResourceIndexerDao.class,
ResourceDao.class,
ResourceKeyUpdaterDao.class,
- ReviewCommentDao.class,
- ReviewDao.class,
RuleDao.class,
SemaphoreDao.class,
SnapshotDataDao.class,
*/
static final String[] TABLE_NAMES = {
"action_plans",
- "action_plans_reviews",
"active_dashboards",
"active_rules",
"active_rule_changes",
"properties",
"quality_models",
"resource_index",
- "reviews",
- "review_comments",
"rules",
"rules_parameters",
"rules_profiles",
- "rule_failures",
"semaphores",
"schema_migrations",
"snapshots",
import org.sonar.api.issue.Issue;
import org.sonar.api.platform.ServerFileSystem;
import org.sonar.api.utils.SonarException;
-import org.sonar.core.review.ReviewDto;
import javax.annotation.Nullable;
import javax.sql.DataSource;
-
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
String snapshotCondition = "islast=" + database.getDialect().getTrueSqlValue() + " and (project_id=" + projectId + " or root_project_id=" + projectId + ")";
template
.copyTable(source, dest, "projects", "(id=" + projectId + " or root_id=" + projectId + ")")
- .copyTable(source, dest, "reviews", "project_id=" + projectId, "status<>'" + ReviewDto.STATUS_CLOSED + "'")
- .copyTable(source, dest, "rule_failures", "snapshot_id in (select id from snapshots where " + snapshotCondition + ")")
- .copyTable(source, dest, "issues", "resource_id in (" + projectsConditionForIssues + ")", "status<>'"+ Issue.STATUS_CLOSED + "'")
+ .copyTable(source, dest, "issues", "resource_id in (" + projectsConditionForIssues + ")", "status<>'" + Issue.STATUS_CLOSED + "'")
.copyTable(source, dest, "snapshots", snapshotCondition);
}
}
import org.sonar.core.purge.PurgeMapper;
import org.sonar.core.purge.PurgeableSnapshotDto;
import org.sonar.core.resource.*;
-import org.sonar.core.review.ReviewCommentDto;
-import org.sonar.core.review.ReviewCommentMapper;
-import org.sonar.core.review.ReviewDto;
-import org.sonar.core.review.ReviewMapper;
import org.sonar.core.rule.RuleDto;
import org.sonar.core.rule.RuleMapper;
import org.sonar.core.source.jdbc.SnapshotDataDto;
loadAlias(conf, "Resource", ResourceDto.class);
loadAlias(conf, "ResourceIndex", ResourceIndexDto.class);
loadAlias(conf, "ResourceSnapshot", ResourceSnapshotDto.class);
- loadAlias(conf, "Review", ReviewDto.class);
- loadAlias(conf, "ReviewComment", ReviewCommentDto.class);
loadAlias(conf, "Rule", RuleDto.class);
loadAlias(conf, "Snapshot", SnapshotDto.class);
loadAlias(conf, "Semaphore", SemaphoreDto.class);
Class<?>[] mappers = {ActiveDashboardMapper.class, AuthorMapper.class, DashboardMapper.class,
DependencyMapper.class, DuplicationMapper.class, GraphDtoMapper.class, IssueMapper.class, IssueChangeMapper.class, LoadedTemplateMapper.class,
MeasureFilterMapper.class, PropertiesMapper.class, PurgeMapper.class, ResourceKeyUpdaterMapper.class, ResourceIndexerMapper.class, ResourceMapper.class,
- ResourceSnapshotMapper.class, ReviewCommentMapper.class, ReviewMapper.class, RoleMapper.class, RuleMapper.class, SchemaMigrationMapper.class,
+ ResourceSnapshotMapper.class, RoleMapper.class, RuleMapper.class, SchemaMigrationMapper.class,
SemaphoreMapper.class, UserMapper.class, WidgetMapper.class, WidgetPropertyMapper.class, MeasureMapper.class, SnapshotDataMapper.class,
SnapshotSourceMapper.class, ActionPlanMapper.class, ActionPlanStatsMapper.class
};
}
private void loadMapper(Configuration configuration, String mapperName) {
- InputStream input = null;
- try {
- input = getClass().getResourceAsStream("/" + mapperName.replace('.', '/') + ".xml");
- new XMLMapperBuilder(input, configuration, mapperName, configuration.getSqlFragments()).parse();
- configuration.addLoadedResource(mapperName);
- } finally {
- Closeables.closeQuietly(input);
- }
+ InputStream input = null;
+ try {
+ input = getClass().getResourceAsStream("/" + mapperName.replace('.', '/') + ".xml");
+ new XMLMapperBuilder(input, configuration, mapperName, configuration.getSqlFragments()).parse();
+ configuration.addLoadedResource(mapperName);
+ } finally {
+ Closeables.closeQuietly(input);
}
+ }
private void loadAlias(Configuration conf, String alias, Class dtoClass) {
conf.getTypeAliasRegistry().registerAlias(alias, dtoClass);
session.commit();
profiler.stop();
- profiler.start("deleteResourceReviewComments (review_comments)");
- for (Long resourceId : resourceIds) {
- purgeMapper.deleteResourceReviewComments(resourceId);
- }
- session.commit();
- profiler.stop();
-
- profiler.start("deleteResourceActionPlansReviews (action_plans_reviews)");
- for (Long resourceId : resourceIds) {
- purgeMapper.deleteResourceActionPlansReviews(resourceId);
- }
- session.commit();
- profiler.stop();
-
- profiler.start("deleteResourceReviews (reviews)");
- for (Long resourceId : resourceIds) {
- purgeMapper.deleteResourceReviews(resourceId);
- }
- session.commit();
- profiler.stop();
-
profiler.start("deleteResourceIssueChanges (issue_changes)");
for (Long resourceId : resourceIds) {
purgeMapper.deleteResourceIssueChanges(resourceId);
deleteSnapshotSources(snapshotIds);
- deleteSnapshotViolations(snapshotIds);
-
deleteSnapshotGraphs(snapshotIds);
deleteSnapshotData(snapshotIds);
deleteSnapshotSources(snapshotIds);
- deleteSnapshotViolations(snapshotIds);
-
deleteSnapshotGraphs(snapshotIds);
deleteSnapshotData(snapshotIds);
profiler.stop();
}
- private void deleteSnapshotViolations(final List<Long> snapshotIds) {
- profiler.start("deleteSnapshotViolations (rule_failures)");
- for (Long snapshotId : snapshotIds) {
- purgeMapper.deleteSnapshotViolations(snapshotId);
- }
- session.commit();
- profiler.stop();
- }
-
private void deleteSnapshotSources(final List<Long> snapshotIds) {
profiler.start("deleteSnapshotSource (snapshot_sources)");
for (Long snapshotId : snapshotIds) {
mapper.deleteResourceIndex(resourceId);
mapper.setSnapshotIsLastToFalse(resourceId);
mapper.disableResource(resourceId);
- mapper.closeResourceReviews(resourceId);
+ //TODO mapper.closeResourceReviews(resourceId);
}
public PurgeDao deleteSnapshots(PurgeSnapshotQuery query) {
void deleteSnapshotSource(long snapshotId);
- void deleteSnapshotViolations(long snapshotId);
-
void deleteSnapshotGraphs(long snapshotId);
List<Long> selectMetricIdsWithoutHistoricalData();
void deleteResourceManualMeasures(long resourceId);
- void deleteResourceReviews(long resourceId);
-
void deleteResourceEvents(long resourceId);
void deleteResourceActionPlans(long resourceId);
void deleteAuthors(long developerId);
- void closeResourceReviews(long resourceId);
-
List<PurgeableSnapshotDto> selectPurgeableSnapshotsWithEvents(long resourceId);
List<PurgeableSnapshotDto> selectPurgeableSnapshotsWithoutEvents(long resourceId);
List<Long> selectResourceIdsByRootId(long rootProjectId);
- void deleteResourceReviewComments(long resourceId);
-
- void deleteResourceActionPlansReviews(long resourceId);
-
void deleteSnapshotData(long snapshotId);
void deleteResourceIssueChanges(long resourceId);
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import org.apache.ibatis.session.SqlSession;
-import org.sonar.api.BatchComponent;
-import org.sonar.api.ServerComponent;
-import org.sonar.core.persistence.MyBatis;
-
-/**
- * @since 3.1
- */
-public class ReviewCommentDao implements BatchComponent, ServerComponent {
- private final MyBatis mybatis;
-
- public ReviewCommentDao(MyBatis mybatis) {
- this.mybatis = mybatis;
- }
-
- public void insert(ReviewCommentDto reviewCommentDto) {
- SqlSession session = mybatis.openSession();
- ReviewCommentMapper mapper = session.getMapper(ReviewCommentMapper.class);
- try {
- mapper.insert(reviewCommentDto);
- session.commit();
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import org.apache.commons.lang.builder.ToStringBuilder;
-import org.apache.commons.lang.builder.ToStringStyle;
-
-import java.util.Date;
-
-/**
- * @since 3.1
- */
-public final class ReviewCommentDto {
-
- private Long id;
- private Long reviewId;
- private Long userId;
- private String text;
- private Date createdAt;
- private Date updatedAt;
-
- public Long getId() {
- return id;
- }
-
- public ReviewCommentDto setId(Long id) {
- this.id = id;
- return this;
- }
-
- public Long getUserId() {
- return userId;
- }
-
- public ReviewCommentDto setUserId(Long userId) {
- this.userId = userId;
- return this;
- }
-
- public Long getReviewId() {
- return reviewId;
- }
-
- public ReviewCommentDto setReviewId(Long reviewId) {
- this.reviewId = reviewId;
- return this;
- }
-
- public String getText() {
- return text;
- }
-
- public ReviewCommentDto setText(String text) {
- this.text = text;
- return this;
- }
-
- public Date getCreatedAt() {
- return createdAt;
- }
-
- public ReviewCommentDto setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- return this;
- }
-
- public Date getUpdatedAt() {
- return updatedAt;
- }
-
- public ReviewCommentDto setUpdatedAt(Date updatedAt) {
- this.updatedAt = updatedAt;
- return this;
- }
-
- @Override
- public String toString() {
- return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- ReviewCommentDto reviewDto = (ReviewCommentDto) o;
- return !(id != null ? !id.equals(reviewDto.id) : reviewDto.id != null);
- }
-
- @Override
- public int hashCode() {
- return id != null ? id.hashCode() : 0;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-/**
- * @since 3.1
- */
-public interface ReviewCommentMapper {
- void insert(ReviewCommentDto reviewCommentDto);
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.base.Predicates;
-import com.google.common.cache.Cache;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.collect.Collections2;
-import org.apache.ibatis.session.SqlSession;
-import org.sonar.api.BatchComponent;
-import org.sonar.api.ServerComponent;
-import org.sonar.core.persistence.MyBatis;
-
-import javax.annotation.Nullable;
-
-import java.util.Collection;
-
-public class ReviewDao implements BatchComponent, ServerComponent {
- private final MyBatis mybatis;
- private final Cache<Long, Collection<ReviewDto>> cacheByResource;
-
- public ReviewDao(MyBatis mybatis) {
- this.mybatis = mybatis;
- this.cacheByResource = CacheBuilder.newBuilder()
- .weakValues()
- .build(new CacheLoader<Long, Collection<ReviewDto>>() {
- @Override
- public Collection<ReviewDto> load(Long resourceId) {
- return doSelectOpenByResourceId(resourceId);
- }
- });
- }
-
- /**
- * @since 3.1
- */
- public ReviewDto findById(long reviewId) {
- SqlSession session = mybatis.openSession();
- try {
- ReviewMapper mapper = session.getMapper(ReviewMapper.class);
- return mapper.findById(reviewId);
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- public Collection<ReviewDto> selectOpenByResourceId(long resourceId, @Nullable Predicate<ReviewDto>... predicates) {
- Collection<ReviewDto> reviews = cacheByResource.getUnchecked(resourceId);
- if (!reviews.isEmpty() && predicates != null) {
- reviews = Collections2.filter(reviews, Predicates.and(predicates));
- }
- return reviews;
- }
-
- public Collection<ReviewDto> selectOnDeletedResources(long rootProjectId, long rootSnapshotId) {
- SqlSession session = mybatis.openSession();
- try {
- ReviewMapper mapper = session.getMapper(ReviewMapper.class);
- return mapper.selectOnDeletedResources(rootProjectId, rootSnapshotId);
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- private Collection<ReviewDto> doSelectOpenByResourceId(long resourceId) {
- SqlSession session = mybatis.openSession();
- try {
- ReviewMapper mapper = session.getMapper(ReviewMapper.class);
- return mapper.selectByResourceId(resourceId);
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- public ReviewDao update(Collection<ReviewDto> reviews) {
- Preconditions.checkNotNull(reviews);
-
- SqlSession session = mybatis.openBatchSession();
- try {
- ReviewMapper mapper = session.getMapper(ReviewMapper.class);
- for (ReviewDto review : reviews) {
- mapper.update(review);
- }
- session.commit();
- return this;
-
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import org.apache.ibatis.annotations.Param;
-
-import java.util.List;
-
-/**
- * @since 2.13
- */
-public interface ReviewMapper {
- ReviewDto findById(long reviewId);
-
- List<ReviewDto> selectByResourceId(long resourceId);
-
- void update(ReviewDto review);
-
- List<ReviewDto> selectOnDeletedResources(@Param("rootProjectId") long rootProjectId, @Param("rootSnapshotId") long rootSnapshotId);
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import com.google.common.base.Predicate;
-import org.apache.commons.lang.ArrayUtils;
-
-import javax.annotation.Nullable;
-
-/**
- * @since 2.14
- */
-public final class ReviewPredicates {
-
- private ReviewPredicates() {
- }
-
- public static Predicate<ReviewDto> status(String... statuses) {
- return new StatusPredicate(statuses);
- }
-
- public static Predicate<ReviewDto> resolution(String... resolutions) {
- return new ResolutionPredicate(resolutions);
- }
-
- public static Predicate<ReviewDto> manualViolation() {
- return ManualViolationPredicate.INSTANCE;
- }
-
- public static Predicate<ReviewDto> manualSeverity() {
- return ManualSeverityPredicate.INSTANCE;
- }
-
- private static final class StatusPredicate implements Predicate<ReviewDto> {
- private String[] statuses;
-
- private StatusPredicate(String... statuses) {
- this.statuses = statuses;
- }
-
- public boolean apply(@Nullable ReviewDto review) {
- return review!=null && ArrayUtils.contains(statuses, review.getStatus());
- }
- }
-
- private static final class ResolutionPredicate implements Predicate<ReviewDto> {
- private String[] resolutions;
-
- private ResolutionPredicate(String... resolutions) {
- this.resolutions = resolutions;
- }
-
- public boolean apply(@Nullable ReviewDto review) {
- return review!=null && ArrayUtils.contains(resolutions, review.getResolution());
- }
- }
-
- private static final class ManualViolationPredicate implements Predicate<ReviewDto> {
- private static final ManualViolationPredicate INSTANCE = new ManualViolationPredicate();
-
- private ManualViolationPredicate() {
- }
-
- public boolean apply(@Nullable ReviewDto review) {
- return review!=null && review.isManualViolation();
- }
- }
-
- private static final class ManualSeverityPredicate implements Predicate<ReviewDto> {
- private static final ManualSeverityPredicate INSTANCE = new ManualSeverityPredicate();
-
- private ManualSeverityPredicate() {
- }
-
- public boolean apply(@Nullable ReviewDto review) {
- return review!=null && review.isManualSeverity();
- }
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-@ParametersAreNonnullByDefault
-package org.sonar.core.review;
-
-import javax.annotation.ParametersAreNonnullByDefault;
\ No newline at end of file
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.workflow;
-
-import com.google.common.annotations.VisibleForTesting;
-import org.apache.ibatis.session.SqlSession;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.sonar.api.ServerComponent;
-import org.sonar.api.config.Settings;
-import org.sonar.api.utils.KeyValueFormat;
-import org.sonar.core.persistence.MyBatis;
-import org.sonar.core.properties.PropertiesMapper;
-import org.sonar.core.properties.PropertyDto;
-import org.sonar.core.review.ReviewCommentDto;
-import org.sonar.core.review.ReviewCommentMapper;
-import org.sonar.core.review.ReviewDto;
-import org.sonar.core.review.ReviewMapper;
-import org.sonar.api.workflow.Comment;
-import org.sonar.api.workflow.internal.DefaultReview;
-import java.util.Date;
-import java.util.List;
-
-public class ReviewDatabaseStore implements ReviewStore, ServerComponent {
- private static final Logger LOG = LoggerFactory.getLogger(ReviewDatabaseStore.class);
-
- private MyBatis mybatis;
-
- public ReviewDatabaseStore(MyBatis mb) {
- this.mybatis = mb;
- }
-
- public void store(DefaultReview review) {
- store(review, new Date());
- }
-
- @VisibleForTesting
- void store(DefaultReview review, Date now) {
- if (review.getReviewId() == null) {
- LOG.error("Review has no id. Violation id is: " + review.getViolationId());
- return;
- }
-
- SqlSession session = mybatis.openSession();
- ReviewMapper mapper = session.getMapper(ReviewMapper.class);
- ReviewCommentMapper commentMapper = session.getMapper(ReviewCommentMapper.class);
- try {
- ReviewDto dto = mapper.findById(review.getReviewId());
- dto.setResolution(review.getResolution());
- dto.setStatus(review.getStatus());
- dto.setData(KeyValueFormat.format(review.getProperties()));
- dto.setUpdatedAt(now);
- mapper.update(dto);
-
- for (Comment comment : review.getNewComments()) {
- ReviewCommentDto commentDto = new ReviewCommentDto();
- commentDto.setReviewId(dto.getId());
- commentDto.setText(comment.getMarkdownText());
- commentDto.setCreatedAt(now);
- commentDto.setUpdatedAt(now);
- commentDto.setUserId(comment.getUserId());
- commentMapper.insert(commentDto);
- }
- session.commit();
-
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-
- public void completeProjectSettings(Long projectId, Settings settings, List<String> propertyKeys) {
- if (propertyKeys.isEmpty()) {
- return;
- }
-
- SqlSession session = mybatis.openSession();
- PropertiesMapper mapper = session.getMapper(PropertiesMapper.class);
- try {
- List<PropertyDto> dtos = mapper.selectSetOfResourceProperties(projectId, propertyKeys);
- for (PropertyDto dto : dtos) {
- settings.setProperty(dto.getKey(), dto.getValue());
- }
-
- } finally {
- MyBatis.closeQuietly(session);
- }
- }
-}
<class>org.sonar.api.measures.Metric</class>
<class>org.sonar.api.database.model.ResourceModel</class>
<class>org.sonar.api.database.model.SnapshotSource</class>
- <class>org.sonar.api.database.model.RuleFailureModel</class>
<class>org.sonar.api.rules.Rule</class>
<class>org.sonar.api.rules.RuleParam</class>
<class>org.sonar.api.resources.ProjectLink</class>
"END_LINE" INTEGER NOT NULL
);
-CREATE TABLE "REVIEW_COMMENTS" (
- "ID" INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1),
- "CREATED_AT" TIMESTAMP,
- "UPDATED_AT" TIMESTAMP,
- "REVIEW_ID" INTEGER,
- "USER_ID" INTEGER,
- "REVIEW_TEXT" VARCHAR(16777215)
-);
-
CREATE TABLE "ACTIVE_RULE_CHANGES" (
"ID" INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1),
"USERNAME" VARCHAR(200),
"CREATED_AT" TIMESTAMP
);
-CREATE TABLE "REVIEWS" (
- "ID" INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1),
- "CREATED_AT" TIMESTAMP,
- "UPDATED_AT" TIMESTAMP,
- "USER_ID" INTEGER,
- "ASSIGNEE_ID" INTEGER,
- "TITLE" VARCHAR(500),
- "STATUS" VARCHAR(10),
- "SEVERITY" VARCHAR(10),
- "RULE_FAILURE_PERMANENT_ID" INTEGER,
- "PROJECT_ID" INTEGER,
- "RESOURCE_ID" INTEGER,
- "RESOURCE_LINE" INTEGER,
- "RESOLUTION" VARCHAR(200),
- "RULE_ID" INTEGER,
- "MANUAL_VIOLATION" BOOLEAN NOT NULL,
- "MANUAL_SEVERITY" BOOLEAN NOT NULL,
- "DATA" VARCHAR(4000)
-);
-
CREATE TABLE "MANUAL_MEASURES" (
"ID" BIGINT NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1),
"METRIC_ID" INTEGER NOT NULL,
"UPDATED_AT" TIMESTAMP
);
-CREATE TABLE "RULE_FAILURES" (
- "ID" INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1),
- "SNAPSHOT_ID" INTEGER NOT NULL,
- "RULE_ID" INTEGER NOT NULL,
- "FAILURE_LEVEL" INTEGER NOT NULL,
- "MESSAGE" VARCHAR(4000),
- "LINE" INTEGER,
- "COST" DOUBLE,
- "CREATED_AT" TIMESTAMP,
- "CHECKSUM" VARCHAR(1000),
- "PERMANENT_ID" INTEGER,
- "SWITCHED_OFF" BOOLEAN,
- "PERSON_ID" INTEGER
-);
-
CREATE TABLE "METRICS" (
"ID" INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1),
"NAME" VARCHAR(64) NOT NULL,
"UPDATED_AT" TIMESTAMP
);
-CREATE TABLE "ACTION_PLANS_REVIEWS" (
- "ACTION_PLAN_ID" INTEGER,
- "REVIEW_ID" INTEGER
-);
-
CREATE TABLE "ACTIVE_RULE_NOTES" (
"ID" INTEGER NOT NULL GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1),
"ACTIVE_RULE_ID" INTEGER,
CREATE INDEX "MEASURE_DATA_MEASURE_ID" ON "MEASURE_DATA" ("MEASURE_ID");
-CREATE INDEX "RF_PERMANENT_ID" ON "RULE_FAILURES" ("PERMANENT_ID");
-
-CREATE INDEX "RULE_FAILURE_RULE_ID" ON "RULE_FAILURES" ("RULE_ID");
-
-CREATE INDEX "RULE_FAILURE_SNAPSHOT_ID" ON "RULE_FAILURES" ("SNAPSHOT_ID");
-
CREATE INDEX "EVENTS_SNAPSHOT_ID" ON "EVENTS" ("SNAPSHOT_ID");
CREATE INDEX "EVENTS_RESOURCE_ID" ON "EVENTS" ("RESOURCE_ID");
CREATE INDEX "INDEX_ACTION_PLANS_ON_PROJET_ID" ON "ACTION_PLANS" ("PROJECT_ID");
-CREATE INDEX "INDEX_ACTION_PLANS_REVIEWS_ON_ACTION_PLAN_ID" ON "ACTION_PLANS_REVIEWS" ("ACTION_PLAN_ID");
-
-CREATE INDEX "INDEX_ACTION_PLANS_REVIEWS_ON_REVIEW_ID" ON "ACTION_PLANS_REVIEWS" ("REVIEW_ID");
-
CREATE INDEX "INDEX_ACTIVE_RULE_NOTES_ON_ACTIVE_RULE_ID" ON "ACTIVE_RULE_NOTES" ("ACTIVE_RULE_ID");
CREATE INDEX "INDEX_RULE_NOTES_ON_ACTIVE_RULE_ID" ON "RULE_NOTES" ("RULE_ID");
-CREATE INDEX "REVIEWS_RID" ON "REVIEWS" ("RESOURCE_ID");
-
CREATE UNIQUE INDEX "UNIQ_SEMAPHORE_CHECKSUMS" ON "SEMAPHORES" ("CHECKSUM");
CREATE INDEX "SEMAPHORE_NAMES" ON "SEMAPHORES" ("NAME");
delete from snapshot_sources where snapshot_id=#{id}
</delete>
- <delete id="deleteSnapshotViolations" parameterType="long">
- delete from rule_failures where snapshot_id=#{id}
- </delete>
-
<delete id="deleteSnapshotGraphs" parameterType="long">
delete from graphs where snapshot_id=#{id}
</delete>
update projects set enabled=${_false} where id=#{id}
</update>
- <update id="closeResourceReviews" parameterType="long">
- update reviews set status='CLOSED', updated_at=CURRENT_TIMESTAMP where resource_id=#{id}
- </update>
-
-
<delete id="deleteResourceIndex" parameterType="long">
delete from resource_index where resource_id=#{id}
</delete>
delete from manual_measures where resource_id=#{id}
</delete>
- <delete id="deleteResourceReviews" parameterType="long">
- delete from reviews where resource_id=#{id}
- </delete>
-
<delete id="deleteResourceEvents" parameterType="long">
delete from events where resource_id=#{id}
</delete>
update snapshots set islast=${_false} where project_id=#{id}
</update>
- <delete id="deleteResourceReviewComments" parameterType="long">
- delete from review_comments rc where exists (select * from reviews r where rc.review_id=r.id and
- r.resource_id=#{id})
- </delete>
-
- <delete id="deleteResourceActionPlansReviews" parameterType="long">
- delete from action_plans_reviews apr where exists (select * from action_plans ap where ap.id=apr.action_plan_id and
- ap.project_id=#{id})
- </delete>
-
<delete id="deleteSnapshotData" parameterType="long">
delete from snapshot_data where snapshot_id=#{id}
</delete>
- <!-- Mssql -->
- <delete id="deleteResourceReviewComments" databaseId="mssql" parameterType="long">
- delete review_comments from review_comments
- inner join reviews on review_comments.review_id=reviews.id
- where reviews.resource_id=#{id}
- </delete>
-
- <delete id="deleteResourceActionPlansReviews" databaseId="mssql" parameterType="long">
- delete action_plans_reviews from action_plans_reviews
- inner join action_plans on action_plans.id=action_plans_reviews.action_plan_id
- where action_plans.project_id=#{id}
- </delete>
-
- <!-- Mysql -->
- <delete id="deleteResourceReviewComments" databaseId="mysql" parameterType="long">
- delete rc from review_comments as rc, reviews as r where rc.review_id=r.id and r.resource_id=#{id}
- </delete>
-
- <delete id="deleteResourceActionPlansReviews" databaseId="mysql" parameterType="long">
- delete apr from action_plans_reviews as apr, action_plans as ap where ap.id=apr.action_plan_id and ap.project_id=#{id}
- </delete>
-
<delete id="deleteResourceIssueChanges" parameterType="long">
delete from issue_changes ic
where exists (select * from issues i where i.kee=ic.issue_key and i.resource_id=#{id})
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
-<mapper namespace="org.sonar.core.review.ReviewCommentMapper">
-
- <insert id="insert" parameterType="ReviewComment" useGeneratedKeys="true" keyProperty ="id">
- INSERT INTO review_comments (review_id, user_id, review_text, created_at, updated_at)
- VALUES (#{reviewId}, #{userId}, #{text},
- #{createdAt}, #{updatedAt})
- </insert>
-
- <!-- Oracle -->
- <insert id="insert" databaseId="oracle" parameterType="ReviewComment" keyColumn="id" useGeneratedKeys="true" keyProperty ="id">
- <selectKey order="BEFORE" resultType="Long" keyProperty="id" >
- select review_comments_seq.NEXTVAL from DUAL
- </selectKey>
- INSERT INTO review_comments (id, review_id, user_id, review_text, created_at, updated_at)
- VALUES (#{id}, #{reviewId}, #{userId}, #{text},
- #{createdAt}, #{updatedAt})
- </insert>
-
-</mapper>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" ?>
-<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
-
-<mapper namespace="org.sonar.core.review.ReviewMapper">
-
- <sql id="reviewColumns">
- r.id, r.created_at as createdAt, r.updated_at as updatedAt, r.user_id as userId, r.assignee_id as assigneeId,
- r.status as status, r.resolution as resolution, r.title as title, r.severity as severity,
- r.rule_failure_permanent_id as violationPermanentId, r.project_id as projectId, r.resource_id as resourceId, r.resource_line as line, r.rule_id as ruleId,
- r.manual_severity as manualSeverity, r.manual_violation as manualViolation, r.data as data
- </sql>
-
- <select id="findById" parameterType="long" resultType="Review">
- select <include refid="reviewColumns"/>, apr.action_plan_id as actionPlanId
- from reviews r left outer join action_plans_reviews apr on r.id=apr.review_id
- where r.id=#{id}
- </select>
-
- <select id="selectByResourceId" parameterType="long" resultType="Review">
- select <include refid="reviewColumns"/>, apr.action_plan_id as actionPlanId
- from reviews r left outer join action_plans_reviews apr on r.id=apr.review_id
- where r.resource_id=#{id} and r.status <> 'CLOSED'
- </select>
-
- <update id="update" parameterType="Review">
- update reviews set
- created_at=#{createdAt},
- updated_at=#{updatedAt},
- user_id=#{userId},
- assignee_id=#{assigneeId},
- status=#{status},
- resolution=#{resolution},
- title=#{title},
- severity=#{severity},
- rule_failure_permanent_id=#{violationPermanentId},
- project_id=#{projectId},
- resource_id=#{resourceId},
- resource_line=#{line},
- rule_id=#{ruleId},
- manual_severity=#{manualSeverity},
- manual_violation=#{manualViolation},
- data=#{data}
- where id = #{id}
- </update>
-
- <select id="selectOnDeletedResources" parameterType="long" resultType="Review">
- select <include refid="reviewColumns"/>
- from reviews r
- where r.status <> 'CLOSED' and r.project_id=#{rootProjectId} and r.resource_id in (
- select prev.project_id from snapshots prev where prev.root_project_id=#{rootProjectId}
- and prev.islast=${_true} and not exists(
- select cur.id from snapshots cur where root_snapshot_id=#{rootSnapshotId} and cur.created_at > prev.created_at AND cur.root_project_id=#{rootProjectId} AND
- cur.project_id=prev.project_id))
- </select>
-</mapper>
-
assertThat(rowCount("projects")).isEqualTo(1);
}
- @Test
- public void should_create_database_with_violations_and_reviews() throws IOException, SQLException {
- setupData("should_create_database_with_violations_and_reviews");
-
- when(serverFileSystem.getTempDir()).thenReturn(temporaryFolder.getRoot());
-
- byte[] database = localDatabaseFactory.createDatabaseForDryRun(123L);
- dataSource = createDatabase(database);
-
- assertThat(rowCount("rule_failures")).isEqualTo(1);
- assertThat(rowCount("reviews")).isEqualTo(1);
- }
-
@Test
public void should_create_database_with_issues() throws IOException, SQLException {
setupData("should_create_database_with_issues");
MyBatis.closeQuietly(session);
}
checkTables("shouldDeleteSnapshot",
- "snapshots", "project_measures", "measure_data", "rule_failures", "snapshot_sources", "duplications_index", "events", "dependencies", "snapshot_data");
+ "snapshots", "project_measures", "measure_data", "snapshot_sources", "duplications_index", "events", "dependencies", "snapshot_data");
}
/**
MyBatis.closeQuietly(session);
}
checkTables("shouldPurgeSnapshot",
- "snapshots", "project_measures", "measure_data", "rule_failures", "snapshot_sources", "duplications_index", "events", "dependencies", "reviews", "snapshot_data");
+ "snapshots", "project_measures", "measure_data", "snapshot_sources", "duplications_index", "events", "dependencies", "snapshot_data");
}
@Test
} finally {
MyBatis.closeQuietly(session);
}
- assertEmptyTables("projects", "snapshots", "events", "reviews", "review_comments", "issues", "issue_changes", "authors");
+ assertEmptyTables("projects", "snapshots", "events", "issues", "issue_changes", "authors");
}
}
checkTables("shouldDeleteAbortedBuilds", "snapshots");
}
- @Test
- public void shouldCloseReviewWhenDisablingResource() {
- setupData("shouldCloseReviewWhenDisablingResource");
-
- SqlSession session = getMyBatis().openSession();
- try {
- dao.disableResource(1L, session.getMapper(PurgeMapper.class));
-
- // the above method does not commit and close the session
- session.commit();
-
- } finally {
- MyBatis.closeQuietly(session);
- }
- checkTables("shouldCloseReviewWhenDisablingResource", /* excluded column */new String[] {"updated_at"}, "reviews");
- }
-
@Test
public void shouldPurgeProject() {
setupData("shouldPurgeProject");
public void shouldDeleteProject() {
setupData("shouldDeleteProject");
dao.deleteResourceTree(1L);
- assertEmptyTables("projects", "snapshots", "action_plans", "action_plans_reviews", "reviews", "review_comments", "issues", "issue_changes");
+ assertEmptyTables("projects", "snapshots", "action_plans", "issues", "issue_changes");
}
static final class SnapshotMatcher extends BaseMatcher<PurgeableSnapshotDto> {
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.core.persistence.AbstractDaoTestCase;
-
-import java.util.Date;
-
-public class ReviewCommentDaoTest extends AbstractDaoTestCase {
-
- private ReviewCommentDao dao;
-
- @Before
- public void createDao() {
- dao = new ReviewCommentDao(getMyBatis());
- }
-
- @Test
- public void shouldFindReviewById() {
- setupData("insert");
-
- ReviewCommentDto reviewCommentDto = new ReviewCommentDto();
- reviewCommentDto.setReviewId(12L);
- reviewCommentDto.setUserId(8L);
- reviewCommentDto.setText("Hello");
- Date today = new Date();
- reviewCommentDto.setCreatedAt(today);
- reviewCommentDto.setUpdatedAt(today);
-
- dao.insert(reviewCommentDto);
-
- checkTables("insert", new String[] {"id", "created_at", "updated_at"}, "review_comments");
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.core.persistence.AbstractDaoTestCase;
-
-import java.util.Collection;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertThat;
-
-public class ReviewDaoTest extends AbstractDaoTestCase {
-
- private ReviewDao dao;
-
- @Before
- public void createDao() {
- dao = new ReviewDao(getMyBatis());
- }
-
- @Test
- public void shouldFindReviewById() {
- setupData("shared");
-
- ReviewDto review = dao.findById(100L);
- assertThat(review.getId(), is(100L));
- assertThat(review.getStatus(), is("OPEN"));
- assertThat(review.getResolution(), is(nullValue()));
- assertThat(review.getProjectId(), is(20));
- assertThat(review.getViolationPermanentId(), is(1));
- assertThat(review.getSeverity(), is("BLOCKER"));
- assertThat(review.getUserId(), is(300));
- assertThat(review.getResourceId(), is(400));
- assertThat(review.getRuleId(), is(500));
- assertThat(review.getManualViolation(), is(true));
- assertThat(review.getActionPlanId(), is(1));
- }
-
- @Test
- public void shouldSelectOpenByResourceId() {
- setupData("shared");
-
- // only a single review is open on this resource
- Collection<ReviewDto> reviews = dao.selectOpenByResourceId(400L);
- assertThat(reviews.size(), is(1));
- ReviewDto review = reviews.iterator().next();
- assertThat(review.getId(), is(100L));
- assertThat(review.getStatus(), is("OPEN"));
- assertThat(review.getResolution(), is(nullValue()));
- assertThat(review.getProjectId(), is(20));
- assertThat(review.getViolationPermanentId(), is(1));
- assertThat(review.getSeverity(), is("BLOCKER"));
- assertThat(review.getUserId(), is(300));
- assertThat(review.getResourceId(), is(400));
- assertThat(review.getRuleId(), is(500));
- assertThat(review.getManualViolation(), is(true));
- assertThat(review.getActionPlanId(), is(1));
- }
-
- @Test
- public void shouldReturnEmptyCollectionIfResourceNotFound() {
- setupData("shared");
- assertThat(dao.selectOpenByResourceId(123456789L).isEmpty(), is(true));
- }
-
- @Test
- public void shouldFilterResults() {
- setupData("shared");
- Collection<ReviewDto> reviews = dao.selectOpenByResourceId(401L,
- ReviewPredicates.status(ReviewDto.STATUS_REOPENED));
-
- assertThat(reviews.size(), is(1));
- ReviewDto review = reviews.iterator().next();
- assertThat(review.getId(), is(103L));
- assertThat(review.getStatus(), is(ReviewDto.STATUS_REOPENED));
- }
-
- @Test
- public void update() {
- setupData("update");
- Collection<ReviewDto> reviews = dao.selectOpenByResourceId(400L);
- ReviewDto review = reviews.iterator().next();
- review.setLine(1000);
- review.setResolution("NEW_RESOLUTION");
- review.setStatus("NEW_STATUS");
- review.setSeverity("NEW_SEV");
- review.setAssigneeId(1001L);
- review.setManualSeverity(true);
- review.setManualViolation(false);
- review.setTitle("NEW_TITLE");
- review.setCreatedAt(DateUtils.parseDate("2012-05-18"));
- review.setUpdatedAt(DateUtils.parseDate("2012-07-01"));
- review.setData("big=bang");
-
- dao.update(reviews);
-
- checkTables("update", "reviews");
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.junit.rules.ExpectedException;
-
-public class ReviewDtoTest {
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Test
- public void setData_check_maximal_length() {
- thrown.expect(IllegalArgumentException.class);
- thrown.expectMessage("Review data must not exceed 4000 characters: ");
-
- StringBuilder s = new StringBuilder(4500);
- for (int i=0 ; i<4500 ; i++) {
- s.append('a');
- }
- new ReviewDto().setData(s.toString());
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.review;
-
-import com.google.common.base.Predicate;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.Lists;
-import org.junit.Test;
-
-import java.util.Collection;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
-
-public class ReviewPredicatesTest {
- @Test
- public void testStatusPredicate() {
- Predicate<ReviewDto> predicate = ReviewPredicates.status(ReviewDto.STATUS_REOPENED);
- Collection<ReviewDto> filtered = Collections2.filter(Lists.<ReviewDto>newArrayList(
- new ReviewDto().setStatus(ReviewDto.STATUS_OPEN),
- new ReviewDto().setStatus(ReviewDto.STATUS_REOPENED),
- new ReviewDto().setStatus(ReviewDto.STATUS_REOPENED)), predicate);
-
- assertThat(filtered.size(), is(2));
- }
-
- @Test
- public void testResolutionPredicate() {
- Predicate<ReviewDto> predicate = ReviewPredicates.resolution(ReviewDto.RESOLUTION_FALSE_POSITIVE);
- Collection<ReviewDto> filtered = Collections2.filter(Lists.<ReviewDto>newArrayList(
- new ReviewDto().setResolution(null),
- new ReviewDto().setResolution(ReviewDto.RESOLUTION_FALSE_POSITIVE),
- new ReviewDto().setResolution(ReviewDto.RESOLUTION_FIXED)), predicate);
-
- assertThat(filtered.size(), is(1));
- }
-
- @Test
- public void testManualViolationPredicate() {
- Predicate<ReviewDto> predicate = ReviewPredicates.manualViolation();
- Collection<ReviewDto> filtered = Collections2.filter(Lists.<ReviewDto>newArrayList(
- new ReviewDto().setManualViolation(false),
- new ReviewDto().setManualViolation(false),
- new ReviewDto().setManualViolation(true)), predicate);
-
- assertThat(filtered.size(), is(1));
- }
-
- @Test
- public void testManualSeverityPredicate() {
- Predicate<ReviewDto> predicate = ReviewPredicates.manualSeverity();
- Collection<ReviewDto> filtered = Collections2.filter(Lists.<ReviewDto>newArrayList(
- new ReviewDto().setManualSeverity(false),
- new ReviewDto().setManualSeverity(false),
- new ReviewDto().setManualSeverity(true)), predicate);
-
- assertThat(filtered.size(), is(1));
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.core.workflow;
-
-import org.junit.Test;
-import org.sonar.api.config.Settings;
-import org.sonar.api.utils.DateUtils;
-import org.sonar.api.workflow.Comment;
-import org.sonar.api.workflow.internal.DefaultReview;
-import org.sonar.core.persistence.AbstractDaoTestCase;
-
-import java.util.Arrays;
-import java.util.Date;
-
-import static org.fest.assertions.Assertions.assertThat;
-
-public class ReviewDatabaseStoreTest extends AbstractDaoTestCase {
-
- @Test
- public void store() {
- setupData("store");
- ReviewDatabaseStore store = new ReviewDatabaseStore(getMyBatis());
- DefaultReview review = new DefaultReview().setReviewId(1234L);
- review.setStatus("CLOSED");
- review.setResolution("RESOLVED");
- review.setProperty("who", "me");
- review.setProperty("why", "because");
- Comment comment = review.createComment();
- comment.setMarkdownText("this is a comment");
- comment.setUserId(555L);
-
- Date now = DateUtils.parseDate("2012-05-18");
- store.store(review, now);
-
- checkTables("store", "reviews");
- checkTables("store", new String[]{"id"}, "review_comments");
- }
-
- @Test
- public void completeProjectSettings() {
- setupData("completeProjectSettings");
- ReviewDatabaseStore store = new ReviewDatabaseStore(getMyBatis());
-
- Settings settings = new Settings();
- store.completeProjectSettings(100L, settings, Arrays.asList("not.available.on.project", "jira.project.key"));
-
- assertThat(settings.getString("not.available.on.project")).isNull();
-
- // project property
- assertThat(settings.getString("jira.project.key")).isEqualTo("FOO");
- }
-}
+++ /dev/null
-<dataset>
- <metrics id="1" name="ncloc" VAL_TYPE="INT" DESCRIPTION="[null]" domain="[null]" short_name=""
- enabled="[true]" worst_value="[null]" optimized_best_value="[null]" best_value="[null]" direction="0" hidden="[false]" delete_historical_data="[null]"/>
- <metrics id="2" name="coverage" VAL_TYPE="INT" DESCRIPTION="[null]" domain="[null]" short_name=""
- enabled="[true]" worst_value="0" optimized_best_value="[true]" best_value="100" direction="1" hidden="[false]" delete_historical_data="[null]"/>
-
- <rules_profiles id="1" name="Sonar way with Findbugs" language="java" parent_name="" version="1"
- used_profile="[false]"/>
-
-
- <projects id="123" root_id="[null]" scope="PRJ" qualifier="TRK" kee="org.struts:struts" name="Struts"
- description="[null]" long_name="Apache Struts"
- enabled="[true]" language="java" copy_resource_id="[null]" person_id="[null]" created_at="2013-01-25 02:04:06.00"/>
-
- <snapshots id="1000" project_id="123" root_project_id="123" root_snapshot_id="1000" parent_snapshot_id="[null]"
- scope="PRJ" qualifier="TRK" path="1000." depth="1"
- purge_status="[null]" period1_mode="[null]" period1_param="[null]" period1_date="[null]"
- period2_mode="[null]" period2_param="[null]" period2_date="[null]" period3_mode="[null]"
- period3_param="[null]" period3_date="[null]" period4_mode="[null]" period4_param="[null]"
- period4_date="[null]" period5_mode="[null]" period5_param="[null]" period5_date="[null]"
- created_at="2013-01-25 02:04:06.00" build_date="2013-01-25 02:04:06.00"
- version="1.0" status="P" islast="[true]"/>
-
- <rule_failures id="1" snapshot_id="1000" rule_id="1" failure_level="2" message="msg1" cost="[null]" switched_off="[null]" permanent_id="[null]"/>
-
- <reviews id="1" project_id="123" resource_id="2" status="OPEN"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]"/>
-
-</dataset>
\ No newline at end of file
<events id="1" name="Version 1.0" resource_id="1" snapshot_id="1" category="VERSION" description="[null]"
event_date="2008-12-02 13:58:00.00" created_at="[null]"/>
- <reviews id="1" project_id="1" resource_id="1" status="CLOSED"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]"/>
-
- <review_comments id="1" created_at="[null]" updated_at="[null]" review_id="1" user_id="1223" review_text="abc"/>
-
<issues id="1" kee="ABCDE" resource_id="1" status="CLOSED" resolution="[null]" line="200" severity="BLOCKER"
reporter="perceval" assignee="arthur" rule_id="500"
manual_severity="[false]"
path="[null]"/>
<snapshot_sources ID="1" SNAPSHOT_ID="1" DATA="foo"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="1" SNAPSHOT_ID="1" RULE_ID="1" FAILURE_LEVEL="2"
- MESSAGE="msg1" LINE="[null]" COST="[null]"
- created_at="2008-12-02 13:58:00.00"
- checksum="[null]" person_id="[null]"/>
<project_measures ID="1" characteristic_id="[null]" url="[null]" variation_value_1="[null]" variation_value_2="[null]"
variation_value_3="[null]" variation_value_4="[null]"
variation_value_5="[null]"
version="[null]" path="[null]"/>
<snapshot_sources ID="1" SNAPSHOT_ID="1" DATA="foo"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="1" SNAPSHOT_ID="1" RULE_ID="1" FAILURE_LEVEL="2"
- MESSAGE="msg1" LINE="[null]" COST="[null]"
- created_at="2008-12-02 13:58:00.00"
- checksum="[null]" person_id="[null]"/>
<project_measures ID="1" characteristic_id="[null]" url="[null]" variation_value_1="[null]" variation_value_2="[null]"
variation_value_3="[null]" variation_value_4="[null]"
variation_value_5="[null]"
version="[null]" path="[null]"/>
<snapshot_sources ID="2" SNAPSHOT_ID="5" DATA="foo"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="3" SNAPSHOT_ID="5" RULE_ID="1" FAILURE_LEVEL="2"
- MESSAGE="msg3" LINE="[null]" COST="[null]"
- created_at="2008-12-02 13:58:00.00"
- checksum="[null]" person_id="[null]"/>
- <rule_failures switched_off="[null]" permanent_id="[null]" ID="4" SNAPSHOT_ID="5" RULE_ID="1" FAILURE_LEVEL="2"
- MESSAGE="msg4" LINE="[null]" COST="[null]"
- created_at="2008-12-02 13:58:00.00"
- checksum="[null]" person_id="[null]"/>
<project_measures ID="2" characteristic_id="[null]" url="[null]" variation_value_1="[null]" variation_value_2="[null]"
variation_value_3="[null]" variation_value_4="[null]"
variation_value_5="[null]"
<!--<snapshot_sources ID="1" SNAPSHOT_ID="1" DATA="foo"/>-->
- <!--<rule_failures ID="1" SNAPSHOT_ID="1"-->
<!--switched_off="[null]" permanent_id="[null]" RULE_ID="1" FAILURE_LEVEL="2"-->
<!--MESSAGE="msg1" LINE="[null]" COST="[null]"-->
<!--created_at="2008-12-02 13:58:00.00"-->
<!--<duplications_index id="1" project_snapshot_id="1" snapshot_id="1"-->
<!--hash="bb" index_in_file="0" start_line="0" end_line="0"/>-->
- <reviews id="1" project_id="1" resource_id="1" status="OPEN"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" updated_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]" data="[null]"/>
-
<!-- The following is not purged but is kept for DBUnit -->
<snapshots id="2"
<snapshot_sources ID="2" SNAPSHOT_ID="2" DATA="foo"/>
- <rule_failures ID="2" SNAPSHOT_ID="2"
- switched_off="[null]" permanent_id="[null]" RULE_ID="1" FAILURE_LEVEL="2"
- MESSAGE="msg1" LINE="[null]" COST="[null]"
- created_at="2008-12-02 13:58:00.00"
- checksum="[null]" person_id="[null]"/>
-
<project_measures ID="2" project_id="2" SNAPSHOT_ID="2" RULE_ID="[null]" characteristic_id="[null]"
url="[null]" variation_value_1="[null]" variation_value_2="[null]" variation_value_3="[null]" variation_value_4="[null]"
variation_value_5="[null]" rule_priority="[null]" alert_text="[null]" VALUE="10.0" METRIC_ID="1" rules_category_id="[null]"
<duplications_index id="2" project_snapshot_id="2" snapshot_id="2"
hash="bb" index_in_file="0" start_line="0" end_line="0"/>
- <reviews id="2" project_id="2" resource_id="2" status="OPEN"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" updated_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]" data="[null]"/>
-
<snapshot_data id="2" resource_id="5" snapshot_id="5" snapshot_data="0,10,k" data_type="highlight_syntax" created_at="[null]" updated_at="[null]" />
</dataset>
<snapshot_sources ID="1" SNAPSHOT_ID="1" DATA="foo"/>
- <rule_failures ID="1" SNAPSHOT_ID="1"
- switched_off="[null]" permanent_id="[null]" RULE_ID="1" FAILURE_LEVEL="2"
- MESSAGE="msg1" LINE="[null]" COST="[null]"
- created_at="2008-12-02 13:58:00.00"
- checksum="[null]" person_id="[null]"/>
-
<project_measures ID="1" project_id="1" SNAPSHOT_ID="1" RULE_ID="[null]" characteristic_id="[null]"
url="[null]" variation_value_1="[null]" variation_value_2="[null]" variation_value_3="[null]" variation_value_4="[null]"
variation_value_5="[null]" rule_priority="[null]" alert_text="[null]" VALUE="10.0" METRIC_ID="1" rules_category_id="[null]"
<duplications_index id="1" project_snapshot_id="1" snapshot_id="1"
hash="bb" index_in_file="0" start_line="0" end_line="0"/>
- <reviews id="1" project_id="1" resource_id="1" status="OPEN"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" updated_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]" data="[null]"/>
-
<snapshot_data id="1" resource_id="1" snapshot_id="1" snapshot_data="0,10,k" data_type="highlight_syntax" created_at="[null]" updated_at="[null]" />
<snapshot_sources ID="2" SNAPSHOT_ID="2" DATA="foo"/>
- <rule_failures ID="2" SNAPSHOT_ID="2"
- switched_off="[null]" permanent_id="[null]" RULE_ID="1" FAILURE_LEVEL="2"
- MESSAGE="msg1" LINE="[null]" COST="[null]"
- created_at="2008-12-02 13:58:00.00"
- checksum="[null]" person_id="[null]"/>
-
<project_measures ID="2" project_id="2" SNAPSHOT_ID="2" RULE_ID="[null]" characteristic_id="[null]"
url="[null]" variation_value_1="[null]" variation_value_2="[null]" variation_value_3="[null]" variation_value_4="[null]"
variation_value_5="[null]" rule_priority="[null]" alert_text="[null]" VALUE="10.0" METRIC_ID="1" rules_category_id="[null]"
<duplications_index id="2" project_snapshot_id="2" snapshot_id="2"
hash="bb" index_in_file="0" start_line="0" end_line="0"/>
- <reviews id="2" project_id="2" resource_id="2" status="OPEN"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" updated_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]" data="[null]"/>
-
<snapshot_data id="2" resource_id="5" snapshot_id="5" snapshot_data="0,10,k" data_type="highlight_syntax" created_at="[null]" updated_at="[null]" />
</dataset>
+++ /dev/null
-<!--
-
-Changes:
-* review.status=CLOSED
-
-Note that the column updated_at has been removed because it's excluded from DBUnit comparison.
--->
-
-<dataset>
-
- <reviews id="1" project_id="1" resource_id="1" status="CLOSED"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]" data="[null]"/>
-
-</dataset>
\ No newline at end of file
+++ /dev/null
-<dataset>
-
- <snapshots id="1"
- project_id="1" parent_snapshot_id="[null]" root_project_id="1" root_snapshot_id="[null]"
- status="P" islast="[true]" purge_status="[null]"
- period1_mode="[null]" period1_param="[null]" period1_date="[null]"
- period2_mode="[null]" period2_param="[null]" period2_date="[null]"
- period3_mode="[null]" period3_param="[null]" period3_date="[null]"
- period4_mode="[null]" period4_param="[null]" period4_date="[null]"
- period5_mode="[null]" period5_param="[null]" period5_date="[null]"
- depth="[null]" scope="PRJ" qualifier="TRK" created_at="2008-12-02 13:58:00.00" build_date="2008-12-02 13:58:00.00" version="[null]" path="[null]"/>
-
- <reviews id="1" project_id="1" resource_id="1" status="OPEN"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" updated_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]" data="[null]"/>
-</dataset>
\ No newline at end of file
<action_plans id="1" kee="ABCD" project_id="1" name="SHORT_TERM" description="[null]" deadline="[null]"
user_login="igor" status="[null]" created_at="[null]" updated_at="[null]" />
- <action_plans_reviews action_plan_id="1" review_id="250" />
-
- <reviews id="1" project_id="1" resource_id="1" status="CLOSED"
- rule_failure_permanent_id="1" resolution="[null]" created_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]"/>
-
- <reviews id="2" project_id="1" resource_id="1" status="CLOSED"
- rule_failure_permanent_id="2" resolution="[null]" created_at="[null]" resource_line="200" severity="BLOCKER"
- user_id="300" assignee_id="300" rule_id="500" manual_violation="[true]" manual_severity="[false]" title="[null]"/>
-
- <review_comments id="1" created_at="[null]" updated_at="[null]" review_id="2" user_id="1223" review_text="abc"/>
-
<issues id="1" kee="ABCDE" resource_id="1" status="CLOSED" resolution="[null]" line="200" severity="BLOCKER"
reporter="perceval" assignee="arthur" rule_id="500"
manual_severity="[false]"
+++ /dev/null
-<dataset>
-
- <review_comments
- review_id="12"
- user_id="8"
- review_text="Hello"
- />
-
-</dataset>
+++ /dev/null
-<dataset>
-
-</dataset>
+++ /dev/null
-<dataset>
-
- <action_plans_reviews action_plan_id="1" review_id="100"/>
- <action_plans_reviews action_plan_id="2" review_id="101"/>
-
- <!-- First resource -->
- <reviews
- id="100"
- status="OPEN"
- rule_failure_permanent_id="1"
- resolution="[null]"
- created_at="[null]"
- updated_at="[null]"
- project_id="20"
- resource_line="200"
- severity="BLOCKER"
- user_id="300"
- assignee_id="300"
- resource_id="400"
- rule_id="500"
- manual_violation="[true]"
- manual_severity="[false]"/>
-
- <reviews
- id="101"
- status="CLOSED"
- rule_failure_permanent_id="1"
- resolution="FIXED"
- created_at="[null]"
- updated_at="[null]"
- project_id="30"
- resource_line="120"
- severity="MAJOR"
- user_id="300"
- assignee_id="[null]"
- resource_id="400"
- rule_id="505"
- manual_violation="[false]"
- manual_severity="[false]"/>
-
-
- <!-- Second resource -->
- <reviews
- id="102"
- status="OPEN"
- rule_failure_permanent_id="1"
- resolution="[null]"
- created_at="[null]"
- updated_at="[null]"
- project_id="20"
- resource_line="200"
- severity="BLOCKER"
- user_id="300"
- assignee_id="300"
- resource_id="401"
- rule_id="500"
- manual_violation="[true]"
- manual_severity="[false]"/>
-
- <reviews
- id="103"
- status="REOPENED"
- rule_failure_permanent_id="1"
- resolution="[null]"
- created_at="[null]"
- updated_at="[null]"
- project_id="20"
- resource_line="200"
- severity="BLOCKER"
- user_id="300"
- assignee_id="[null]"
- resource_id="401"
- rule_id="500"
- manual_violation="[false]"
- manual_severity="[false]"/>
-
- <reviews
- id="104"
- status="RESOLVED"
- rule_failure_permanent_id="1"
- resolution="FALSE-POSITIVE"
- created_at="[null]"
- updated_at="[null]"
- project_id="20"
- resource_line="200"
- severity="BLOCKER"
- user_id="300"
- assignee_id="300"
- resource_id="401"
- rule_id="500"
- manual_violation="[false]"
- manual_severity="[false]"/>
-
-</dataset>
+++ /dev/null
-<dataset>
-
- <reviews
- id="100"
- status="NEW_STATUS"
- rule_failure_permanent_id="100"
- resolution="NEW_RESOLUTION"
- created_at="2012-05-18"
- updated_at="2012-07-01"
- project_id="20"
- resource_line="1000"
- severity="NEW_SEV"
- user_id="300"
- assignee_id="1001"
- title="NEW_TITLE"
- resource_id="400"
- rule_id="500"
- manual_severity="[true]"
- manual_violation="[false]"
- data="big=bang"
- />
-
-</dataset>
+++ /dev/null
-<dataset>
-
- <reviews
- id="100"
- status="OPEN"
- rule_failure_permanent_id="100"
- resolution="RESOLVE"
- created_at="[null]"
- updated_at="[null]"
- project_id="20"
- resource_line="200"
- severity="BLOCKER"
- user_id="300"
- assignee_id="[null]"
- title="[null]"
- resource_id="400"
- rule_id="500"
- manual_violation="[false]"
- manual_severity="[false]"
- data="prop1=foo;prop2=bar"/>
-
-</dataset>
+++ /dev/null
-<dataset>
-
- <!-- global -->
- <properties id="1" prop_key="jira.url" text_value="http://jira.mycompany.com" resource_id="[null]" user_id="[null]"/>
-
- <!-- project -->
- <properties id="2" prop_key="jira.project.key" text_value="FOO" resource_id="100" user_id="[null]"/>
-
- <!-- user -->
- <properties id="3" prop_key="user.key" text_value="new_user" resource_id="[null]" user_id="100"/>
-
-</dataset>
+++ /dev/null
-<dataset>
-
- <reviews
- id="1234"
- rule_failure_permanent_id="1"
- created_at="2012-01-01"
- project_id="20"
- title="[null]"
- resource_line="200"
- severity="BLOCKER"
- user_id="300"
- assignee_id="33"
- resource_id="400"
- rule_id="500"
- manual_violation="[true]"
- manual_severity="[false]"
-
- updated_at="2012-05-18"
- status="CLOSED"
- resolution="RESOLVED"
- data="who=me;why=because"
- />
-
- <review_comments
- review_id="1234"
- user_id="555"
- review_text="this is a comment"
- created_at="2012-05-18"
- updated_at="2012-05-18"
- />
-</dataset>
+++ /dev/null
-<dataset>
-
- <reviews
- id="1234"
- rule_failure_permanent_id="1"
- created_at="2012-01-01"
- project_id="20"
- title="[null]"
- resource_line="200"
- severity="BLOCKER"
- user_id="300"
- assignee_id="33"
- resource_id="400"
- rule_id="500"
- manual_violation="[true]"
- manual_severity="[false]"
-
- updated_at="[null]"
- status="OPEN"
- resolution="[null]"
- data="[null]"
- />
-
-</dataset>
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.api.database.model;
-
-import org.apache.commons.lang.StringUtils;
-import org.apache.commons.lang.builder.EqualsBuilder;
-import org.apache.commons.lang.builder.HashCodeBuilder;
-import org.apache.commons.lang.builder.ReflectionToStringBuilder;
-import org.sonar.api.database.BaseIdentifiable;
-import org.sonar.api.rules.RulePriority;
-
-import javax.persistence.*;
-import java.util.Date;
-
-@Entity
-@Table(name = "rule_failures")
-public class RuleFailureModel extends BaseIdentifiable {
-
- public static final int MESSAGE_COLUMN_SIZE = 4000;
-
- @Column(name = "snapshot_id")
- protected Integer snapshotId;
-
- @Column(name = "rule_id", updatable = false, nullable = false)
- private Integer ruleId;
-
- @Column(name = "failure_level", updatable = true, nullable = false)
- @Enumerated(EnumType.ORDINAL)
- private RulePriority priority;
-
- @Column(name = "message", updatable = false, nullable = true, length = MESSAGE_COLUMN_SIZE)
- private String message;
-
- @Column(name = "line", updatable = true, nullable = true)
- private Integer line;
-
- @Column(name = "cost", updatable = true, nullable = true)
- private Double cost;
-
- @Temporal(TemporalType.TIMESTAMP)
- @Column(name = "created_at", updatable = true, nullable = true)
- private Date createdAt;
-
- @Column(name = "checksum", updatable = true, nullable = true, length = 1000)
- private String checksum;
-
- @Column(name = "permanent_id", updatable = true, nullable = true)
- private Integer permanentId;
-
- @Column(name = "switched_off", updatable = true, nullable = true)
- private Boolean switchedOff = Boolean.FALSE;
-
- @Column(name = "person_id", updatable = true, nullable = true)
- private Integer personId;
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = abbreviateMessage(message);
- }
-
- public static String abbreviateMessage(String message) {
- return StringUtils.abbreviate(StringUtils.trim(message), MESSAGE_COLUMN_SIZE);
- }
-
- public Integer getRuleId() {
- return ruleId;
- }
-
- public void setRuleId(Integer ruleId) {
- this.ruleId = ruleId;
- }
-
- public Integer getLine() {
- return line;
- }
-
- public RulePriority getPriority() {
- return priority;
- }
-
- public Integer getSnapshotId() {
- return snapshotId;
- }
-
- public void setSnapshotId(Integer i) {
- this.snapshotId = i;
- }
-
- public void setPriority(RulePriority priority) {
- this.priority = priority;
- }
-
- public void setLine(Integer line) {
- this.line = line;
- }
-
- public Double getCost() {
- return cost;
- }
-
- public RuleFailureModel setCost(Double d) {
- this.cost = d;
- return this;
- }
-
- public Date getCreatedAt() {
- return createdAt;
- }
-
- public void setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- }
-
- public String getChecksum() {
- return checksum;
- }
-
- public void setChecksum(String checksum) {
- this.checksum = checksum;
- }
-
- public Integer getPermanentId() {
- return permanentId;
- }
-
- public RuleFailureModel setPermanentId(Integer i) {
- this.permanentId = i;
- return this;
- }
-
- public boolean isSwitchedOff() {
- return (switchedOff != null && switchedOff.booleanValue());
- }
-
- public RuleFailureModel setSwitchedOff(boolean b) {
- this.switchedOff = b;
- return this;
- }
-
- public Integer getPersonId() {
- return personId;
- }
-
- public RuleFailureModel setPersonId(Integer i) {
- this.personId = i;
- return this;
- }
-
- @Override
- public boolean equals(Object obj) {
- if (!(obj instanceof RuleFailureModel)) {
- return false;
- }
- if (this == obj) {
- return true;
- }
- RuleFailureModel other = (RuleFailureModel) obj;
- return new EqualsBuilder()
- .append(getId(), other.getId()).isEquals();
- }
-
- @Override
- public int hashCode() {
- return new HashCodeBuilder(17, 37).
- append(getId()).toHashCode();
- }
-
- @Override
- public String toString() {
- return ReflectionToStringBuilder.toString(this);
- }
-}
public static String DOMAIN_DOCUMENTATION = "Documentation";
public static String DOMAIN_RULES = "Rules";
public static String DOMAIN_SCM = "SCM";
+
+ /**
+ * @deprecated in 3.6. Replaced by concept of issues.
+ */
+ @Deprecated
public static String DOMAIN_REVIEWS = "Reviews";
public static String DOMAIN_ISSUES = "Issues";
public static final String LINES_KEY = "lines";
public static final Metric LINES = new Metric.Builder(LINES_KEY, "Lines", Metric.ValueType.INT)
- .setDescription("Lines")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Lines")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String GENERATED_LINES_KEY = "generated_lines";
public static final Metric GENERATED_LINES = new Metric.Builder(GENERATED_LINES_KEY, "Generated Lines", Metric.ValueType.INT)
- .setDescription("Number of generated lines")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Number of generated lines")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String NCLOC_KEY = "ncloc";
public static final Metric NCLOC = new Metric.Builder(NCLOC_KEY, "Lines of code", Metric.ValueType.INT)
- .setDescription("Non Commenting Lines of Code")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Non Commenting Lines of Code")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String GENERATED_NCLOC_KEY = "generated_ncloc";
public static final Metric GENERATED_NCLOC = new Metric.Builder(GENERATED_NCLOC_KEY, "Generated lines of code", Metric.ValueType.INT)
- .setDescription("Generated non Commenting Lines of Code")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Generated non Commenting Lines of Code")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String CLASSES_KEY = "classes";
public static final Metric CLASSES = new Metric.Builder(CLASSES_KEY, "Classes", Metric.ValueType.INT)
- .setDescription("Classes")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Classes")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String FILES_KEY = "files";
public static final Metric FILES = new Metric.Builder(FILES_KEY, "Files", Metric.ValueType.INT)
- .setDescription("Number of files")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .create();
+ .setDescription("Number of files")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .create();
public static final String DIRECTORIES_KEY = "directories";
public static final Metric DIRECTORIES = new Metric.Builder(DIRECTORIES_KEY, "Directories", Metric.ValueType.INT)
- .setDescription("Directories")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .create();
+ .setDescription("Directories")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .create();
public static final String PACKAGES_KEY = "packages";
public static final Metric PACKAGES = new Metric.Builder(PACKAGES_KEY, "Packages", Metric.ValueType.INT)
- .setDescription("Packages")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Packages")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String FUNCTIONS_KEY = "functions";
public static final Metric FUNCTIONS = new Metric.Builder(FUNCTIONS_KEY, "Methods", Metric.ValueType.INT)
- .setDescription("Methods")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Methods")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String ACCESSORS_KEY = "accessors";
public static final Metric ACCESSORS = new Metric.Builder(ACCESSORS_KEY, "Accessors", Metric.ValueType.INT)
- .setDescription("Accessors")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Accessors")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String STATEMENTS_KEY = "statements";
public static final Metric STATEMENTS = new Metric.Builder(STATEMENTS_KEY, "Statements", Metric.ValueType.INT)
- .setDescription("Number of statements")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Number of statements")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String PUBLIC_API_KEY = "public_api";
public static final Metric PUBLIC_API = new Metric.Builder(PUBLIC_API_KEY, "Public API", Metric.ValueType.INT)
- .setDescription("Public API")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Public API")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
/**
* @since 3.0
* @since 3.0
*/
public static final Metric PROJECTS = new Metric.Builder(PROJECTS_KEY, "Projects", Metric.ValueType.INT)
- .setDescription("Number of projects")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_SIZE)
- .create();
+ .setDescription("Number of projects")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_SIZE)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
public static final String COMMENT_LINES_KEY = "comment_lines";
public static final Metric COMMENT_LINES = new Metric.Builder(COMMENT_LINES_KEY, "Comment lines", Metric.ValueType.INT)
- .setDescription("Number of comment lines")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(false)
- .setDomain(DOMAIN_DOCUMENTATION)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Number of comment lines")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DOCUMENTATION)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String COMMENT_LINES_DENSITY_KEY = "comment_lines_density";
public static final Metric COMMENT_LINES_DENSITY = new Metric.Builder(COMMENT_LINES_DENSITY_KEY, "Comments (%)", Metric.ValueType.PERCENT)
- .setDescription("Comments balanced by ncloc + comment lines")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_DOCUMENTATION)
- .create();
+ .setDescription("Comments balanced by ncloc + comment lines")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DOCUMENTATION)
+ .create();
/**
* @deprecated since 3.3 - see SONAR-3768
*/
@Deprecated
public static final Metric COMMENT_BLANK_LINES = new Metric.Builder(COMMENT_BLANK_LINES_KEY, "Blank comments", Metric.ValueType.INT)
- .setDescription("Comments that do not contain comments")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_DOCUMENTATION)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Comments that do not contain comments")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DOCUMENTATION)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String PUBLIC_DOCUMENTED_API_DENSITY_KEY = "public_documented_api_density";
public static final Metric PUBLIC_DOCUMENTED_API_DENSITY = new Metric.Builder(PUBLIC_DOCUMENTED_API_DENSITY_KEY, "Public documented API (%)", Metric.ValueType.PERCENT)
- .setDescription("Public documented classes and methods balanced by ncloc")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_DOCUMENTATION)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Public documented classes and methods balanced by ncloc")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DOCUMENTATION)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String PUBLIC_UNDOCUMENTED_API_KEY = "public_undocumented_api";
public static final Metric PUBLIC_UNDOCUMENTED_API = new Metric.Builder(PUBLIC_UNDOCUMENTED_API_KEY, "Public undocumented API", Metric.ValueType.INT)
- .setDescription("Public undocumented classes, methods and variables")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DOCUMENTATION)
- .setBestValue(0.0)
- .setDirection(Metric.DIRECTION_WORST)
- .setOptimizedBestValue(true)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Public undocumented classes, methods and variables")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DOCUMENTATION)
+ .setBestValue(0.0)
+ .setDirection(Metric.DIRECTION_WORST)
+ .setOptimizedBestValue(true)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String COMMENTED_OUT_CODE_LINES_KEY = "commented_out_code_lines";
public static final Metric COMMENTED_OUT_CODE_LINES = new Metric.Builder(COMMENTED_OUT_CODE_LINES_KEY, "Commented-out LOC", Metric.ValueType.INT)
- .setDescription("Commented lines of code")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DOCUMENTATION)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Commented lines of code")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DOCUMENTATION)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
public static final String COMPLEXITY_KEY = "complexity";
public static final Metric COMPLEXITY = new Metric.Builder(COMPLEXITY_KEY, "Complexity", Metric.ValueType.INT)
- .setDescription("Cyclomatic complexity")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Cyclomatic complexity")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String FILE_COMPLEXITY_KEY = "file_complexity";
public static final Metric FILE_COMPLEXITY = new Metric.Builder(FILE_COMPLEXITY_KEY, "Complexity /file", Metric.ValueType.FLOAT)
- .setDescription("Complexity average by file")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FILES))
- .create();
+ .setDescription("Complexity average by file")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(AverageFormula.create(CoreMetrics.COMPLEXITY, CoreMetrics.FILES))
+ .create();
/**
* @since 3.6
* @since 3.6
*/
public static final Metric COMPLEXITY_IN_CLASSES = new Metric.Builder(COMPLEXITY_IN_CLASSES_KEY, "Complexity in classes", Metric.ValueType.INT)
- .setDescription("Cyclomatic complexity in classes")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Cyclomatic complexity in classes")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String CLASS_COMPLEXITY_KEY = "class_complexity";
* If the complexity in classes is not available, the complexity of the file is used.
*/
public static final Metric CLASS_COMPLEXITY = new Metric.Builder(CLASS_COMPLEXITY_KEY, "Complexity /class", Metric.ValueType.FLOAT)
- .setDescription("Complexity average by class")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(AverageFormula.create(CoreMetrics.COMPLEXITY_IN_CLASSES, CoreMetrics.CLASSES).setFallbackForMainMetric(CoreMetrics.COMPLEXITY))
- .create();
+ .setDescription("Complexity average by class")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(AverageFormula.create(CoreMetrics.COMPLEXITY_IN_CLASSES, CoreMetrics.CLASSES).setFallbackForMainMetric(CoreMetrics.COMPLEXITY))
+ .create();
/**
* @since 3.6
* @since 3.6
*/
public static final Metric COMPLEXITY_IN_FUNCTIONS = new Metric.Builder(COMPLEXITY_IN_FUNCTIONS_KEY, "Complexity in functions", Metric.ValueType.INT)
- .setDescription("Cyclomatic complexity in methods")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Cyclomatic complexity in methods")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String FUNCTION_COMPLEXITY_KEY = "function_complexity";
* If the complexity in functions is not available, the complexity of the file is used.
*/
public static final Metric FUNCTION_COMPLEXITY = new Metric.Builder(FUNCTION_COMPLEXITY_KEY, "Complexity /method", Metric.ValueType.FLOAT)
- .setDescription("Complexity average by method")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(AverageFormula.create(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.FUNCTIONS).setFallbackForMainMetric(CoreMetrics.COMPLEXITY))
- .create();
+ .setDescription("Complexity average by method")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(AverageFormula.create(CoreMetrics.COMPLEXITY_IN_FUNCTIONS, CoreMetrics.FUNCTIONS).setFallbackForMainMetric(CoreMetrics.COMPLEXITY))
+ .create();
/**
*/
@Deprecated
public static final Metric CLASS_COMPLEXITY_DISTRIBUTION = new Metric.Builder(CLASS_COMPLEXITY_DISTRIBUTION_KEY, "Classes distribution /complexity", Metric.ValueType.DISTRIB)
- .setDescription("Classes distribution /complexity")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(true)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
- .create();
+ .setDescription("Classes distribution /complexity")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(true)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
+ .create();
public static final String FUNCTION_COMPLEXITY_DISTRIBUTION_KEY = "function_complexity_distribution";
public static final Metric FUNCTION_COMPLEXITY_DISTRIBUTION = new Metric.Builder(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, "Functions distribution /complexity",
- Metric.ValueType.DISTRIB)
- .setDescription("Functions distribution /complexity")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(true)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
- .create();
+ Metric.ValueType.DISTRIB)
+ .setDescription("Functions distribution /complexity")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(true)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
+ .create();
public static final String FILE_COMPLEXITY_DISTRIBUTION_KEY = "file_complexity_distribution";
public static final Metric FILE_COMPLEXITY_DISTRIBUTION = new Metric.Builder(FILE_COMPLEXITY_DISTRIBUTION_KEY, "Files distribution /complexity", Metric.ValueType.DISTRIB)
- .setDescription("Files distribution /complexity")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(true)
- .setDomain(DOMAIN_COMPLEXITY)
- .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
- .create();
+ .setDescription("Files distribution /complexity")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(true)
+ .setDomain(DOMAIN_COMPLEXITY)
+ .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
* </ul>
*/
public static final Metric TESTS = new Metric.Builder(TESTS_KEY, "Unit tests", Metric.ValueType.INT)
- .setDescription("Number of unit tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_TESTS)
- .create();
+ .setDescription("Number of unit tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_TESTS)
+ .create();
public static final String TEST_EXECUTION_TIME_KEY = "test_execution_time";
public static final Metric TEST_EXECUTION_TIME = new Metric.Builder(TEST_EXECUTION_TIME_KEY, "Unit tests duration", Metric.ValueType.MILLISEC)
- .setDescription("Execution duration of unit tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_TESTS)
- .create();
+ .setDescription("Execution duration of unit tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_TESTS)
+ .create();
public static final String TEST_ERRORS_KEY = "test_errors";
public static final Metric TEST_ERRORS = new Metric.Builder(TEST_ERRORS_KEY, "Unit test errors", Metric.ValueType.INT)
- .setDescription("Number of unit test errors")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Number of unit test errors")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String SKIPPED_TESTS_KEY = "skipped_tests";
public static final Metric SKIPPED_TESTS = new Metric.Builder(SKIPPED_TESTS_KEY, "Skipped unit tests", Metric.ValueType.INT)
- .setDescription("Number of skipped unit tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Number of skipped unit tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String TEST_FAILURES_KEY = "test_failures";
public static final Metric TEST_FAILURES = new Metric.Builder(TEST_FAILURES_KEY, "Unit test failures", Metric.ValueType.INT)
- .setDescription("Number of unit test failures")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Number of unit test failures")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String TEST_SUCCESS_DENSITY_KEY = "test_success_density";
public static final Metric TEST_SUCCESS_DENSITY = new Metric.Builder(TEST_SUCCESS_DENSITY_KEY, "Unit test success (%)", Metric.ValueType.PERCENT)
- .setDescription("Density of successful unit tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Density of successful unit tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String TEST_DATA_KEY = "test_data";
public static final Metric TEST_DATA = new Metric.Builder(TEST_DATA_KEY, "Unit tests details", Metric.ValueType.DATA)
- .setDescription("Unit tests details")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_TESTS)
- .create();
+ .setDescription("Unit tests details")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_TESTS)
+ .create();
public static final String COVERAGE_KEY = "coverage";
public static final Metric COVERAGE = new Metric.Builder(COVERAGE_KEY, "Coverage", Metric.ValueType.PERCENT)
- .setDescription("Coverage by unit tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .create();
+ .setDescription("Coverage by unit tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .create();
public static final String NEW_COVERAGE_KEY = "new_coverage";
public static final Metric NEW_COVERAGE = new Metric.Builder(NEW_COVERAGE_KEY, "New coverage", Metric.ValueType.PERCENT)
- .setDescription("Coverage of new/changed code")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Coverage of new/changed code")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String LINES_TO_COVER_KEY = "lines_to_cover";
* Use {@link CoverageMeasuresBuilder} to build measure for this metric.
*/
public static final Metric LINES_TO_COVER = new Metric.Builder(LINES_TO_COVER_KEY, "Lines to cover", Metric.ValueType.INT)
- .setDescription("Lines to cover")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(false)
- .setDomain(DOMAIN_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Lines to cover")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(false)
+ .setDomain(DOMAIN_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String NEW_LINES_TO_COVER_KEY = "new_lines_to_cover";
public static final Metric NEW_LINES_TO_COVER = new Metric.Builder(NEW_LINES_TO_COVER_KEY, "New lines to cover", Metric.ValueType.INT)
- .setDescription("New lines to cover")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New lines to cover")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setDeleteHistoricalData(true)
+ .create();
public static final String UNCOVERED_LINES_KEY = "uncovered_lines";
* Use {@link CoverageMeasuresBuilder} to build measure for this metric.
*/
public static final Metric UNCOVERED_LINES = new Metric.Builder(UNCOVERED_LINES_KEY, "Uncovered lines", Metric.ValueType.INT)
- .setDescription("Uncovered lines")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .create();
+ .setDescription("Uncovered lines")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .create();
public static final String NEW_UNCOVERED_LINES_KEY = "new_uncovered_lines";
public static final Metric NEW_UNCOVERED_LINES = new Metric.Builder(NEW_UNCOVERED_LINES_KEY, "New uncovered lines", Metric.ValueType.INT)
- .setDescription("New uncovered lines")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New uncovered lines")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String LINE_COVERAGE_KEY = "line_coverage";
public static final Metric LINE_COVERAGE = new Metric.Builder(LINE_COVERAGE_KEY, "Line coverage", Metric.ValueType.PERCENT)
- .setDescription("Line coverage")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .create();
+ .setDescription("Line coverage")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .create();
public static final String NEW_LINE_COVERAGE_KEY = "new_line_coverage";
public static final Metric NEW_LINE_COVERAGE = new Metric.Builder(NEW_LINE_COVERAGE_KEY, "New line coverage", Metric.ValueType.PERCENT)
- .setDescription("Line coverage of added/changed code")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDomain(DOMAIN_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Line coverage of added/changed code")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDomain(DOMAIN_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String COVERAGE_LINE_HITS_DATA_KEY = "coverage_line_hits_data";
* Use {@link CoverageMeasuresBuilder} to build measure for this metric.
*/
public static final Metric COVERAGE_LINE_HITS_DATA = new Metric.Builder(COVERAGE_LINE_HITS_DATA_KEY, "Coverage hits by line", Metric.ValueType.DATA)
- .setDomain(DOMAIN_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDomain(DOMAIN_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String CONDITIONS_TO_COVER_KEY = "conditions_to_cover";
* Use {@link CoverageMeasuresBuilder} to build measure for this metric.
*/
public static final Metric CONDITIONS_TO_COVER = new Metric.Builder(CONDITIONS_TO_COVER_KEY, "Conditions to cover", Metric.ValueType.INT)
- .setDescription("Conditions to cover")
- .setDomain(DOMAIN_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setHidden(true)
- .create();
+ .setDescription("Conditions to cover")
+ .setDomain(DOMAIN_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setHidden(true)
+ .create();
public static final String NEW_CONDITIONS_TO_COVER_KEY = "new_conditions_to_cover";
public static final Metric NEW_CONDITIONS_TO_COVER = new Metric.Builder(NEW_CONDITIONS_TO_COVER_KEY, "New conditions to cover", Metric.ValueType.INT)
- .setDescription("New conditions to cover")
- .setDomain(DOMAIN_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setDeleteHistoricalData(true)
- .setHidden(true)
- .create();
+ .setDescription("New conditions to cover")
+ .setDomain(DOMAIN_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setDeleteHistoricalData(true)
+ .setHidden(true)
+ .create();
public static final String UNCOVERED_CONDITIONS_KEY = "uncovered_conditions";
* Use {@link CoverageMeasuresBuilder} to build measure for this metric.
*/
public static final Metric UNCOVERED_CONDITIONS = new Metric.Builder(UNCOVERED_CONDITIONS_KEY, "Uncovered conditions", Metric.ValueType.INT)
- .setDescription("Uncovered conditions")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .create();
+ .setDescription("Uncovered conditions")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .create();
public static final String NEW_UNCOVERED_CONDITIONS_KEY = "new_uncovered_conditions";
public static final Metric NEW_UNCOVERED_CONDITIONS = new Metric.Builder(NEW_UNCOVERED_CONDITIONS_KEY, "New uncovered conditions", Metric.ValueType.INT)
- .setDescription("New uncovered conditions")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New uncovered conditions")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String BRANCH_COVERAGE_KEY = "branch_coverage";
public static final Metric BRANCH_COVERAGE = new Metric.Builder(BRANCH_COVERAGE_KEY, "Branch coverage", Metric.ValueType.PERCENT)
- .setDescription("Branch coverage")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .create();
+ .setDescription("Branch coverage")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .create();
public static final String NEW_BRANCH_COVERAGE_KEY = "new_branch_coverage";
public static final Metric NEW_BRANCH_COVERAGE = new Metric.Builder(NEW_BRANCH_COVERAGE_KEY, "New branch coverage", Metric.ValueType.PERCENT)
- .setDescription("Branch coverage of new/changed code")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Branch coverage of new/changed code")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @deprecated in 2.7. Replaced by {@link #CONDITIONS_BY_LINE_KEY} and {@link #COVERED_CONDITIONS_BY_LINE_KEY}
*/
@Deprecated
public static final Metric BRANCH_COVERAGE_HITS_DATA = new Metric.Builder(BRANCH_COVERAGE_HITS_DATA_KEY, "Branch coverage hits", Metric.ValueType.DATA)
- .setDomain(DOMAIN_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDomain(DOMAIN_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String CONDITIONS_BY_LINE_KEY = "conditions_by_line";
* @since 2.7
*/
public static final Metric CONDITIONS_BY_LINE = new Metric.Builder(CONDITIONS_BY_LINE_KEY, "Conditions by line", Metric.ValueType.DATA)
- .setDomain(DOMAIN_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDomain(DOMAIN_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String COVERED_CONDITIONS_BY_LINE_KEY = "covered_conditions_by_line";
* @since 2.7
*/
public static final Metric COVERED_CONDITIONS_BY_LINE = new Metric.Builder(COVERED_CONDITIONS_BY_LINE_KEY, "Covered conditions by line", Metric.ValueType.DATA)
- .setDomain(DOMAIN_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDomain(DOMAIN_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
* @since 2.12
*/
public static final Metric IT_COVERAGE = new Metric.Builder(IT_COVERAGE_KEY, "IT coverage", Metric.ValueType.PERCENT)
- .setDescription("Coverage by integration tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .create();
+ .setDescription("Coverage by integration tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric NEW_IT_COVERAGE = new Metric.Builder(NEW_IT_COVERAGE_KEY, "New coverage by IT", Metric.ValueType.PERCENT)
- .setDescription("Integration Tests Coverage of new/changed code")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Integration Tests Coverage of new/changed code")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_LINES_TO_COVER = new Metric.Builder(IT_LINES_TO_COVER_KEY, "IT lines to cover", Metric.ValueType.INT)
- .setDescription("Lines to cover by Integration Tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setQualitative(false)
- .setFormula(new SumChildValuesFormula(false))
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Lines to cover by Integration Tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setQualitative(false)
+ .setFormula(new SumChildValuesFormula(false))
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric NEW_IT_LINES_TO_COVER = new Metric.Builder(NEW_IT_LINES_TO_COVER_KEY, "New lines to cover by IT", Metric.ValueType.INT)
- .setDescription("New lines to cover by Integration Tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New lines to cover by Integration Tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_UNCOVERED_LINES = new Metric.Builder(IT_UNCOVERED_LINES_KEY, "IT uncovered lines", Metric.ValueType.INT)
- .setDescription("IT uncovered lines")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("IT uncovered lines")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric NEW_IT_UNCOVERED_LINES = new Metric.Builder(NEW_IT_UNCOVERED_LINES_KEY, "New uncovered lines by IT", Metric.ValueType.INT)
- .setDescription("New uncovered lines by Integration Tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New uncovered lines by Integration Tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_LINE_COVERAGE = new Metric.Builder(IT_LINE_COVERAGE_KEY, "IT line coverage", Metric.ValueType.PERCENT)
- .setDescription("IT line coverage")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .create();
+ .setDescription("IT line coverage")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric NEW_IT_LINE_COVERAGE = new Metric.Builder(NEW_IT_LINE_COVERAGE_KEY, "New line coverage by IT", Metric.ValueType.PERCENT)
- .setDescription("Line Coverage by Integration Tests of added/changed code")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Line Coverage by Integration Tests of added/changed code")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_COVERAGE_LINE_HITS_DATA = new Metric.Builder(IT_COVERAGE_LINE_HITS_DATA_KEY, "IT coverage hits data", Metric.ValueType.DATA)
- .setDescription("IT Code coverage line hits data")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("IT Code coverage line hits data")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_CONDITIONS_TO_COVER = new Metric.Builder(IT_CONDITIONS_TO_COVER_KEY, "IT branches to cover", Metric.ValueType.INT)
- .setDescription("IT Conditions to cover")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(false)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setHidden(true)
- .create();
+ .setDescription("IT Conditions to cover")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(false)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setHidden(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric NEW_IT_CONDITIONS_TO_COVER = new Metric.Builder(NEW_IT_CONDITIONS_TO_COVER_KEY, "New conditions to cover by IT", Metric.ValueType.INT)
- .setDescription("New conditions to cover by Integration Tests")
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setDeleteHistoricalData(true)
- .setHidden(true)
- .create();
+ .setDescription("New conditions to cover by Integration Tests")
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setDeleteHistoricalData(true)
+ .setHidden(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_UNCOVERED_CONDITIONS = new Metric.Builder(IT_UNCOVERED_CONDITIONS_KEY, "IT uncovered branches", Metric.ValueType.INT)
- .setDescription("IT Uncovered conditions")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("IT Uncovered conditions")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric NEW_IT_UNCOVERED_CONDITIONS = new Metric.Builder(NEW_IT_UNCOVERED_CONDITIONS_KEY, "New uncovered conditions by IT", Metric.ValueType.INT)
- .setDescription("New uncovered conditions by Integration Tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New uncovered conditions by Integration Tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_BRANCH_COVERAGE = new Metric.Builder(IT_BRANCH_COVERAGE_KEY, "IT branch coverage", Metric.ValueType.PERCENT)
- .setDescription("IT Branch coverage")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .create();
+ .setDescription("IT Branch coverage")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric NEW_IT_BRANCH_COVERAGE = new Metric.Builder(NEW_IT_BRANCH_COVERAGE_KEY, "New branch coverage by IT", Metric.ValueType.PERCENT)
- .setDescription("Branch coverage by Integration Tests of new/changed code")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Branch coverage by Integration Tests of new/changed code")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_CONDITIONS_BY_LINE = new Metric.Builder(IT_CONDITIONS_BY_LINE_KEY, "IT branches by line", Metric.ValueType.DATA)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.12
* @since 2.12
*/
public static final Metric IT_COVERED_CONDITIONS_BY_LINE = new Metric.Builder(IT_COVERED_CONDITIONS_BY_LINE_KEY, "IT covered branches by line", Metric.ValueType.DATA)
- .setDomain(DOMAIN_INTEGRATION_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDomain(DOMAIN_INTEGRATION_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
* @since 3.3
*/
public static final Metric OVERALL_COVERAGE = new Metric.Builder(OVERALL_COVERAGE_KEY, "Overall coverage", Metric.ValueType.PERCENT)
- .setDescription("Overall test coverage")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .create();
+ .setDescription("Overall test coverage")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric NEW_OVERALL_COVERAGE = new Metric.Builder(NEW_OVERALL_COVERAGE_KEY, "Overall new coverage", Metric.ValueType.PERCENT)
- .setDescription("Overall coverage of new/changed code")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Overall coverage of new/changed code")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_LINES_TO_COVER = new Metric.Builder(OVERALL_LINES_TO_COVER_KEY, "Overall lines to cover", Metric.ValueType.INT)
- .setDescription("Overall lines to cover by all tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setQualitative(false)
- .setFormula(new SumChildValuesFormula(false))
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Overall lines to cover by all tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setQualitative(false)
+ .setFormula(new SumChildValuesFormula(false))
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric NEW_OVERALL_LINES_TO_COVER = new Metric.Builder(NEW_OVERALL_LINES_TO_COVER_KEY, "Overall new lines to cover", Metric.ValueType.INT)
- .setDescription("New lines to cover by all tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New lines to cover by all tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_UNCOVERED_LINES = new Metric.Builder(OVERALL_UNCOVERED_LINES_KEY, "Overall uncovered lines", Metric.ValueType.INT)
- .setDescription("Uncovered lines by all tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Uncovered lines by all tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric NEW_OVERALL_UNCOVERED_LINES = new Metric.Builder(NEW_OVERALL_UNCOVERED_LINES_KEY, "Overall new lines uncovered", Metric.ValueType.INT)
- .setDescription("New lines that are not covered by any tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New lines that are not covered by any tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_LINE_COVERAGE = new Metric.Builder(OVERALL_LINE_COVERAGE_KEY, "Overall line coverage", Metric.ValueType.PERCENT)
- .setDescription("Line coverage by all tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .create();
+ .setDescription("Line coverage by all tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric NEW_OVERALL_LINE_COVERAGE = new Metric.Builder(NEW_OVERALL_LINE_COVERAGE_KEY, "Overall new line coverage", Metric.ValueType.PERCENT)
- .setDescription("Line coverage of added/changed code by all tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Line coverage of added/changed code by all tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_COVERAGE_LINE_HITS_DATA = new Metric.Builder(OVERALL_COVERAGE_LINE_HITS_DATA_KEY, "Overall coverage hits by line", Metric.ValueType.DATA)
- .setDescription("Coverage hits by all tests and by line")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Coverage hits by all tests and by line")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_CONDITIONS_TO_COVER = new Metric.Builder(OVERALL_CONDITIONS_TO_COVER_KEY, "Overall branches to cover", Metric.ValueType.INT)
- .setDescription("Branches to cover by all tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(false)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setHidden(true)
- .create();
+ .setDescription("Branches to cover by all tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(false)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setHidden(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric NEW_OVERALL_CONDITIONS_TO_COVER = new Metric.Builder(NEW_OVERALL_CONDITIONS_TO_COVER_KEY, "Overall new branches to cover", Metric.ValueType.INT)
- .setDescription("New branches to cover by all tests")
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setDeleteHistoricalData(true)
- .setHidden(true)
- .create();
+ .setDescription("New branches to cover by all tests")
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setDeleteHistoricalData(true)
+ .setHidden(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_UNCOVERED_CONDITIONS = new Metric.Builder(OVERALL_UNCOVERED_CONDITIONS_KEY, "Overall uncovered branches", Metric.ValueType.INT)
- .setDescription("Uncovered branches by all tests")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Uncovered branches by all tests")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric NEW_OVERALL_UNCOVERED_CONDITIONS = new Metric.Builder(NEW_OVERALL_UNCOVERED_CONDITIONS_KEY, "Overall new branches uncovered", Metric.ValueType.INT)
- .setDescription("New branches that are not covered by any test")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New branches that are not covered by any test")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_BRANCH_COVERAGE = new Metric.Builder(OVERALL_BRANCH_COVERAGE_KEY, "Overall branch coverage", Metric.ValueType.PERCENT)
- .setDescription("Branch coverage by all tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .create();
+ .setDescription("Branch coverage by all tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric NEW_OVERALL_BRANCH_COVERAGE = new Metric.Builder(NEW_OVERALL_BRANCH_COVERAGE_KEY, "Overall new branch coverage", Metric.ValueType.PERCENT)
- .setDescription("Branch coverage of new/changed code by all tests")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setWorstValue(0.0)
- .setBestValue(100.0)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Branch coverage of new/changed code by all tests")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setWorstValue(0.0)
+ .setBestValue(100.0)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_CONDITIONS_BY_LINE = new Metric.Builder(OVERALL_CONDITIONS_BY_LINE_KEY, "Overall branches by line", Metric.ValueType.DATA)
- .setDescription("Overall branches by all tests and by line")
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Overall branches by all tests and by line")
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 3.3
* @since 3.3
*/
public static final Metric OVERALL_COVERED_CONDITIONS_BY_LINE = new Metric.Builder(OVERALL_COVERED_CONDITIONS_BY_LINE_KEY, "Overall covered branches by line",
- Metric.ValueType.DATA)
- .setDescription("Overall covered branches by all tests and by line")
- .setDomain(DOMAIN_OVERALL_TESTS)
- .setDeleteHistoricalData(true)
- .create();
+ Metric.ValueType.DATA)
+ .setDescription("Overall covered branches by all tests and by line")
+ .setDomain(DOMAIN_OVERALL_TESTS)
+ .setDeleteHistoricalData(true)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
public static final String DUPLICATED_LINES_KEY = "duplicated_lines";
public static final Metric DUPLICATED_LINES = new Metric.Builder(DUPLICATED_LINES_KEY, "Duplicated lines", Metric.ValueType.INT)
- .setDescription("Duplicated lines")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DUPLICATION)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Duplicated lines")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DUPLICATION)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String DUPLICATED_BLOCKS_KEY = "duplicated_blocks";
public static final Metric DUPLICATED_BLOCKS = new Metric.Builder(DUPLICATED_BLOCKS_KEY, "Duplicated blocks", Metric.ValueType.INT)
- .setDescription("Duplicated blocks")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DUPLICATION)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Duplicated blocks")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DUPLICATION)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String DUPLICATED_FILES_KEY = "duplicated_files";
* For other resources: amount of files under this resource with duplicates.
*/
public static final Metric DUPLICATED_FILES = new Metric.Builder(DUPLICATED_FILES_KEY, "Duplicated files", Metric.ValueType.INT)
- .setDescription("Duplicated files")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DUPLICATION)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Duplicated files")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DUPLICATION)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String DUPLICATED_LINES_DENSITY_KEY = "duplicated_lines_density";
public static final Metric DUPLICATED_LINES_DENSITY = new Metric.Builder(DUPLICATED_LINES_DENSITY_KEY, "Duplicated lines (%)", Metric.ValueType.PERCENT)
- .setDescription("Duplicated lines balanced by statements")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DUPLICATION)
- .setWorstValue(50.0)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Duplicated lines balanced by statements")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DUPLICATION)
+ .setWorstValue(50.0)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String DUPLICATIONS_DATA_KEY = "duplications_data";
* </p>
*/
public static final Metric DUPLICATIONS_DATA = new Metric.Builder(DUPLICATIONS_DATA_KEY, "Duplications details", Metric.ValueType.DATA)
- .setDescription("Duplications details")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_DUPLICATION)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Duplications details")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DUPLICATION)
+ .setDeleteHistoricalData(true)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
*/
@Deprecated
public static final Metric USABILITY = new Metric(USABILITY_KEY, "Usability", "Usability", Metric.ValueType.PERCENT,
- Metric.DIRECTION_BETTER, true, DOMAIN_RULE_CATEGORIES).setBestValue(100.0).setOptimizedBestValue(true);
+ Metric.DIRECTION_BETTER, true, DOMAIN_RULE_CATEGORIES).setBestValue(100.0).setOptimizedBestValue(true);
/**
* @deprecated since 2.5 See SONAR-2007
*/
@Deprecated
public static final Metric RELIABILITY = new Metric(RELIABILITY_KEY, "Reliability", "Reliability", Metric.ValueType.PERCENT,
- Metric.DIRECTION_BETTER, true, DOMAIN_RULE_CATEGORIES).setBestValue(100.0).setOptimizedBestValue(true);
+ Metric.DIRECTION_BETTER, true, DOMAIN_RULE_CATEGORIES).setBestValue(100.0).setOptimizedBestValue(true);
/**
* @deprecated since 2.5 See SONAR-2007
*/
@Deprecated
public static final Metric EFFICIENCY = new Metric(EFFICIENCY_KEY, "Efficiency", "Efficiency", Metric.ValueType.PERCENT,
- Metric.DIRECTION_BETTER, true, DOMAIN_RULE_CATEGORIES).setBestValue(100.0).setOptimizedBestValue(true);
+ Metric.DIRECTION_BETTER, true, DOMAIN_RULE_CATEGORIES).setBestValue(100.0).setOptimizedBestValue(true);
/**
* @deprecated since 2.5 See SONAR-2007
*/
@Deprecated
public static final Metric PORTABILITY = new Metric(PORTABILITY_KEY, "Portability", "Portability", Metric.ValueType.PERCENT,
- Metric.DIRECTION_BETTER, true, DOMAIN_RULE_CATEGORIES).setBestValue(100.0).setOptimizedBestValue(true);
+ Metric.DIRECTION_BETTER, true, DOMAIN_RULE_CATEGORIES).setBestValue(100.0).setOptimizedBestValue(true);
/**
* @deprecated since 2.5 See SONAR-2007
*/
@Deprecated
public static final Metric MAINTAINABILITY = new Metric.Builder(MAINTAINABILITY_KEY, "Maintainability", Metric.ValueType.PERCENT)
- .setDescription("Maintainability")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_RULE_CATEGORIES)
- .setBestValue(100.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Maintainability")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULE_CATEGORIES)
+ .setBestValue(100.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String WEIGHTED_VIOLATIONS_KEY = "weighted_violations";
- public static final Metric WEIGHTED_VIOLATIONS = new Metric.Builder(WEIGHTED_VIOLATIONS_KEY, "Weighted violations", Metric.ValueType.INT)
- .setDescription("Weighted Violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ public static final Metric WEIGHTED_VIOLATIONS = new Metric.Builder(WEIGHTED_VIOLATIONS_KEY, "Weighted issues", Metric.ValueType.INT)
+ .setDescription("Weighted Issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String VIOLATIONS_DENSITY_KEY = "violations_density";
public static final Metric VIOLATIONS_DENSITY = new Metric.Builder(VIOLATIONS_DENSITY_KEY, "Rules compliance", Metric.ValueType.PERCENT)
- .setDescription("Rules compliance")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .create();
+ .setDescription("Rules compliance")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .create();
public static final String VIOLATIONS_KEY = "violations";
- public static final Metric VIOLATIONS = new Metric.Builder(VIOLATIONS_KEY, "Violations", Metric.ValueType.INT)
- .setDescription("Violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ public static final Metric VIOLATIONS = new Metric.Builder(VIOLATIONS_KEY, "Issues", Metric.ValueType.INT)
+ .setDescription("Issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String BLOCKER_VIOLATIONS_KEY = "blocker_violations";
- public static final Metric BLOCKER_VIOLATIONS = new Metric.Builder(BLOCKER_VIOLATIONS_KEY, "Blocker violations", Metric.ValueType.INT)
- .setDescription("Blocker violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ public static final Metric BLOCKER_VIOLATIONS = new Metric.Builder(BLOCKER_VIOLATIONS_KEY, "Blocker issues", Metric.ValueType.INT)
+ .setDescription("Blocker issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String CRITICAL_VIOLATIONS_KEY = "critical_violations";
- public static final Metric CRITICAL_VIOLATIONS = new Metric.Builder(CRITICAL_VIOLATIONS_KEY, "Critical violations", Metric.ValueType.INT)
- .setDescription("Critical violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ public static final Metric CRITICAL_VIOLATIONS = new Metric.Builder(CRITICAL_VIOLATIONS_KEY, "Critical issues", Metric.ValueType.INT)
+ .setDescription("Critical issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String MAJOR_VIOLATIONS_KEY = "major_violations";
- public static final Metric MAJOR_VIOLATIONS = new Metric.Builder(MAJOR_VIOLATIONS_KEY, "Major violations", Metric.ValueType.INT)
- .setDescription("Major violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ public static final Metric MAJOR_VIOLATIONS = new Metric.Builder(MAJOR_VIOLATIONS_KEY, "Major issues", Metric.ValueType.INT)
+ .setDescription("Major issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String MINOR_VIOLATIONS_KEY = "minor_violations";
- public static final Metric MINOR_VIOLATIONS = new Metric.Builder(MINOR_VIOLATIONS_KEY, "Minor violations", Metric.ValueType.INT)
- .setDescription("Minor violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ public static final Metric MINOR_VIOLATIONS = new Metric.Builder(MINOR_VIOLATIONS_KEY, "Minor issues", Metric.ValueType.INT)
+ .setDescription("Minor issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String INFO_VIOLATIONS_KEY = "info_violations";
- public static final Metric INFO_VIOLATIONS = new Metric.Builder(INFO_VIOLATIONS_KEY, "Info violations", Metric.ValueType.INT)
- .setDescription("Info violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ public static final Metric INFO_VIOLATIONS = new Metric.Builder(INFO_VIOLATIONS_KEY, "Info issues", Metric.ValueType.INT)
+ .setDescription("Info issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
public static final String NEW_VIOLATIONS_KEY = "new_violations";
- public static final Metric NEW_VIOLATIONS = new Metric.Builder(NEW_VIOLATIONS_KEY, "New Violations", Metric.ValueType.INT)
- .setDescription("New Violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
+ public static final Metric NEW_VIOLATIONS = new Metric.Builder(NEW_VIOLATIONS_KEY, "New issues", Metric.ValueType.INT)
+ .setDescription("New Issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String NEW_BLOCKER_VIOLATIONS_KEY = "new_blocker_violations";
- public static final Metric NEW_BLOCKER_VIOLATIONS = new Metric.Builder(NEW_BLOCKER_VIOLATIONS_KEY, "New Blocker violations", Metric.ValueType.INT)
- .setDescription("New Blocker violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
+ public static final Metric NEW_BLOCKER_VIOLATIONS = new Metric.Builder(NEW_BLOCKER_VIOLATIONS_KEY, "New Blocker issues", Metric.ValueType.INT)
+ .setDescription("New Blocker issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String NEW_CRITICAL_VIOLATIONS_KEY = "new_critical_violations";
- public static final Metric NEW_CRITICAL_VIOLATIONS = new Metric.Builder(NEW_CRITICAL_VIOLATIONS_KEY, "New Critical violations", Metric.ValueType.INT)
- .setDescription("New Critical violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
+ public static final Metric NEW_CRITICAL_VIOLATIONS = new Metric.Builder(NEW_CRITICAL_VIOLATIONS_KEY, "New Critical issues", Metric.ValueType.INT)
+ .setDescription("New Critical issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String NEW_MAJOR_VIOLATIONS_KEY = "new_major_violations";
- public static final Metric NEW_MAJOR_VIOLATIONS = new Metric.Builder(NEW_MAJOR_VIOLATIONS_KEY, "New Major violations", Metric.ValueType.INT)
- .setDescription("New Major violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
+ public static final Metric NEW_MAJOR_VIOLATIONS = new Metric.Builder(NEW_MAJOR_VIOLATIONS_KEY, "New Major issues", Metric.ValueType.INT)
+ .setDescription("New Major issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String NEW_MINOR_VIOLATIONS_KEY = "new_minor_violations";
- public static final Metric NEW_MINOR_VIOLATIONS = new Metric.Builder(NEW_MINOR_VIOLATIONS_KEY, "New Minor violations", Metric.ValueType.INT)
- .setDescription("New Minor violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
+ public static final Metric NEW_MINOR_VIOLATIONS = new Metric.Builder(NEW_MINOR_VIOLATIONS_KEY, "New Minor issues", Metric.ValueType.INT)
+ .setDescription("New Minor issues")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String NEW_INFO_VIOLATIONS_KEY = "new_info_violations";
- public static final Metric NEW_INFO_VIOLATIONS = new Metric.Builder(NEW_INFO_VIOLATIONS_KEY, "New Info violations", Metric.ValueType.INT)
- .setDescription("New Info violations")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_RULES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
-
- // --------------------------------------------------------------------------------------------------------------------
- //
- // ISSUES
- //
- // --------------------------------------------------------------------------------------------------------------------
-
- /**
- * @since 3.6
- */
- public static final String ISSUES_KEY = "issues";
-
- /**
- * @since 3.6
- */
- public static final Metric ISSUES = new Metric.Builder(ISSUES_KEY, "Issues", Metric.ValueType.INT)
- .setDescription("Issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String WEIGHTED_ISSUES_KEY = "weighted_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric WEIGHTED_ISSUES = new Metric.Builder(WEIGHTED_ISSUES_KEY, "Weighted issues", Metric.ValueType.INT)
- .setDescription("Weighted issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String ISSUES_DENSITY_KEY = "issues_density";
-
- /**
- * @since 3.6
- */
- public static final Metric ISSUES_DENSITY = new Metric.Builder(ISSUES_DENSITY_KEY, "Rules compliance", Metric.ValueType.PERCENT)
- .setDescription("Rules compliance")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String BLOCKER_ISSUES_KEY = "blocker_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric BLOCKER_ISSUES = new Metric.Builder(BLOCKER_ISSUES_KEY, "Blocker issues", Metric.ValueType.INT)
- .setDescription("Blocker issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String CRITICAL_ISSUES_KEY = "critical_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric CRITICAL_ISSUES = new Metric.Builder(CRITICAL_ISSUES_KEY, "Critical issues", Metric.ValueType.INT)
- .setDescription("Critical issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String MAJOR_ISSUES_KEY = "major_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric MAJOR_ISSUES = new Metric.Builder(MAJOR_ISSUES_KEY, "Major issues", Metric.ValueType.INT)
- .setDescription("Major issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String MINOR_ISSUES_KEY = "minor_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric MINOR_ISSUES = new Metric.Builder(MINOR_ISSUES_KEY, "Minor issues", Metric.ValueType.INT)
- .setDescription("Minor issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String INFO_ISSUES_KEY = "info_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric INFO_ISSUES = new Metric.Builder(INFO_ISSUES_KEY, "Info issues", Metric.ValueType.INT)
- .setDescription("Info issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String NEW_ISSUES_KEY = "new_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric NEW_ISSUES = new Metric.Builder(NEW_ISSUES_KEY, "New issues", Metric.ValueType.INT)
- .setDescription("New issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String NEW_BLOCKER_ISSUES_KEY = "new_blocker_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric NEW_BLOCKER_ISSUES = new Metric.Builder(NEW_BLOCKER_ISSUES_KEY, "New Blocker issues", Metric.ValueType.INT)
- .setDescription("New Blocker issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String NEW_CRITICAL_ISSUES_KEY = "new_critical_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric NEW_CRITICAL_ISSUES = new Metric.Builder(NEW_CRITICAL_ISSUES_KEY, "New Critical issues", Metric.ValueType.INT)
- .setDescription("New Critical issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String NEW_MAJOR_ISSUES_KEY = "new_major_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric NEW_MAJOR_ISSUES = new Metric.Builder(NEW_MAJOR_ISSUES_KEY, "New Major issues", Metric.ValueType.INT)
- .setDescription("New Major issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String NEW_MINOR_ISSUES_KEY = "new_minor_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric NEW_MINOR_ISSUES = new Metric.Builder(NEW_MINOR_ISSUES_KEY, "New Minor issues", Metric.ValueType.INT)
- .setDescription("New Minor issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String NEW_INFO_ISSUES_KEY = "new_info_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric NEW_INFO_ISSUES = new Metric.Builder(NEW_INFO_ISSUES_KEY, "New Info issues", Metric.ValueType.INT)
- .setDescription("New Info issues")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_ISSUES)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
-
- /**
- * @since 3.6
- */
- public static final String FALSE_POSITIVE_ISSUES_KEY = "false_positive_issues";
-
- /**
- * @since 3.6
- */
- public static final Metric FALSE_POSITIVE_ISSUES = new Metric.Builder(FALSE_POSITIVE_ISSUES_KEY, "False-positive issues", Metric.ValueType.INT)
- .setDescription("Active false-positive issues")
+ public static final Metric NEW_INFO_VIOLATIONS = new Metric.Builder(NEW_INFO_VIOLATIONS_KEY, "New Info issues", Metric.ValueType.INT)
+ .setDescription("New Info issues")
.setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_ISSUES)
+ .setQualitative(true)
+ .setDomain(DOMAIN_RULES)
.setBestValue(0.0)
.setOptimizedBestValue(true)
+ .setDeleteHistoricalData(true)
.create();
/**
* @since 3.6
*/
- public static final String UNASSIGNED_ISSUES_KEY = "unassigned_issues";
+ public static final String FALSE_POSITIVE_ISSUES_KEY = "false_positive_issues";
/**
* @since 3.6
*/
- public static final Metric UNASSIGNED_ISSUES = new Metric.Builder(UNASSIGNED_ISSUES_KEY, "Unassigned issues", Metric.ValueType.INT)
- .setDescription("Active unassigned issues")
+ public static final Metric FALSE_POSITIVE_ISSUES = new Metric.Builder(FALSE_POSITIVE_ISSUES_KEY, "False-positive issues", Metric.ValueType.INT)
+ .setDescription("False-positive issues")
.setDirection(Metric.DIRECTION_WORST)
.setDomain(DOMAIN_ISSUES)
.setBestValue(0.0)
.setOptimizedBestValue(true)
.create();
-
// --------------------------------------------------------------------------------------------------------------------
//
// DESIGN
public static final String ABSTRACTNESS_KEY = "abstractness";
public static final Metric ABSTRACTNESS = new Metric.Builder(ABSTRACTNESS_KEY, "Abstractness", Metric.ValueType.PERCENT)
- .setDescription("Abstractness")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .create();
+ .setDescription("Abstractness")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .create();
public static final String INSTABILITY_KEY = "instability";
public static final Metric INSTABILITY = new Metric.Builder(INSTABILITY_KEY, "Instability", Metric.ValueType.PERCENT)
- .setDescription("Instability")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .create();
+ .setDescription("Instability")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .create();
public static final String DISTANCE_KEY = "distance";
public static final Metric DISTANCE = new Metric.Builder(DISTANCE_KEY, "Distance", Metric.ValueType.FLOAT)
- .setDescription("Distance")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .create();
+ .setDescription("Distance")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .create();
public static final String DEPTH_IN_TREE_KEY = "dit";
public static final Metric DEPTH_IN_TREE = new Metric.Builder(DEPTH_IN_TREE_KEY, "Depth in Tree", Metric.ValueType.INT)
- .setDescription("Depth in Inheritance Tree")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .create();
+ .setDescription("Depth in Inheritance Tree")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .create();
public static final String NUMBER_OF_CHILDREN_KEY = "noc";
public static final Metric NUMBER_OF_CHILDREN = new Metric.Builder(NUMBER_OF_CHILDREN_KEY, "Number of Children", Metric.ValueType.INT)
- .setDescription("Number of Children")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .create();
+ .setDescription("Number of Children")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .create();
public static final String RFC_KEY = "rfc";
public static final Metric RFC = new Metric.Builder(RFC_KEY, "RFC", Metric.ValueType.INT)
- .setDescription("Response for Class")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setFormula(new WeightedMeanAggregationFormula(CoreMetrics.FILES, false))
- .create();
+ .setDescription("Response for Class")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setFormula(new WeightedMeanAggregationFormula(CoreMetrics.FILES, false))
+ .create();
public static final String RFC_DISTRIBUTION_KEY = "rfc_distribution";
public static final Metric RFC_DISTRIBUTION = new Metric.Builder(RFC_DISTRIBUTION_KEY, "Class distribution /RFC", Metric.ValueType.DISTRIB)
- .setDescription("Class distribution /RFC")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(true)
- .setDomain(DOMAIN_DESIGN)
- .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
- .create();
+ .setDescription("Class distribution /RFC")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DESIGN)
+ .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
+ .create();
public static final String LCOM4_KEY = "lcom4";
public static final Metric LCOM4 = new Metric.Builder(LCOM4_KEY, "LCOM4", Metric.ValueType.FLOAT)
- .setDescription("Lack of Cohesion of Methods")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DESIGN)
- .setBestValue(1.0)
- .setFormula(new WeightedMeanAggregationFormula(CoreMetrics.FILES, false))
- .create();
+ .setDescription("Lack of Cohesion of Methods")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DESIGN)
+ .setBestValue(1.0)
+ .setFormula(new WeightedMeanAggregationFormula(CoreMetrics.FILES, false))
+ .create();
public static final String LCOM4_BLOCKS_KEY = "lcom4_blocks";
public static final Metric LCOM4_BLOCKS = new Metric.Builder(LCOM4_BLOCKS_KEY, "LCOM4 blocks", Metric.ValueType.DATA)
- .setDescription("LCOM4 blocks")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("LCOM4 blocks")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String LCOM4_DISTRIBUTION_KEY = "lcom4_distribution";
public static final Metric LCOM4_DISTRIBUTION = new Metric.Builder(LCOM4_DISTRIBUTION_KEY, "Class distribution /LCOM4", Metric.ValueType.DISTRIB)
- .setDescription("Class distribution /LCOM4")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(true)
- .setDomain(DOMAIN_DESIGN)
- .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
- .create();
+ .setDescription("Class distribution /LCOM4")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DESIGN)
+ .setFormula(new SumChildDistributionFormula().setMinimumScopeToPersist(Scopes.DIRECTORY))
+ .create();
public static final String SUSPECT_LCOM4_DENSITY_KEY = "suspect_lcom4_density";
public static final Metric SUSPECT_LCOM4_DENSITY = new Metric.Builder(SUSPECT_LCOM4_DENSITY_KEY, "Suspect LCOM4 density", Metric.ValueType.PERCENT)
- .setDescription("Density of classes having LCOM4>1")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DESIGN)
- .create();
+ .setDescription("Density of classes having LCOM4>1")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DESIGN)
+ .create();
public static final String AFFERENT_COUPLINGS_KEY = "ca";
public static final Metric AFFERENT_COUPLINGS = new Metric.Builder(AFFERENT_COUPLINGS_KEY, "Afferent couplings", Metric.ValueType.INT)
- .setDescription("Afferent couplings")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .create();
+ .setDescription("Afferent couplings")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .create();
public static final String EFFERENT_COUPLINGS_KEY = "ce";
public static final Metric EFFERENT_COUPLINGS = new Metric.Builder(EFFERENT_COUPLINGS_KEY, "Efferent couplings", Metric.ValueType.INT)
- .setDescription("Efferent couplings")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .create();
+ .setDescription("Efferent couplings")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .create();
public static final String DEPENDENCY_MATRIX_KEY = "dsm";
public static final Metric DEPENDENCY_MATRIX = new Metric.Builder(DEPENDENCY_MATRIX_KEY, "Dependency Matrix", Metric.ValueType.DATA)
- .setDescription("Dependency Matrix")
- .setDirection(Metric.DIRECTION_NONE)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Dependency Matrix")
+ .setDirection(Metric.DIRECTION_NONE)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String PACKAGE_CYCLES_KEY = "package_cycles";
public static final Metric PACKAGE_CYCLES = new Metric.Builder(PACKAGE_CYCLES_KEY, "Package cycles", Metric.ValueType.INT)
- .setDescription("Package cycles")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DESIGN)
- .setBestValue(0.0)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("Package cycles")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DESIGN)
+ .setBestValue(0.0)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String PACKAGE_TANGLE_INDEX_KEY = "package_tangle_index";
public static final Metric PACKAGE_TANGLE_INDEX = new Metric.Builder(PACKAGE_TANGLE_INDEX_KEY, "Package tangle index", Metric.ValueType.PERCENT)
- .setDescription("Package tangle index")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setBestValue(0.0)
- .setDomain(DOMAIN_DESIGN)
- .create();
+ .setDescription("Package tangle index")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setBestValue(0.0)
+ .setDomain(DOMAIN_DESIGN)
+ .create();
public static final String PACKAGE_TANGLES_KEY = "package_tangles";
public static final Metric PACKAGE_TANGLES = new Metric.Builder(PACKAGE_TANGLES_KEY, "File dependencies to cut", Metric.ValueType.INT)
- .setDescription("File dependencies to cut")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setFormula(new SumChildValuesFormula(false))
- .create();
+ .setDescription("File dependencies to cut")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setFormula(new SumChildValuesFormula(false))
+ .create();
public static final String PACKAGE_FEEDBACK_EDGES_KEY = "package_feedback_edges";
public static final Metric PACKAGE_FEEDBACK_EDGES = new Metric.Builder(PACKAGE_FEEDBACK_EDGES_KEY, "Package dependencies to cut", Metric.ValueType.INT)
- .setDescription("Package dependencies to cut")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setFormula(new SumChildValuesFormula(false))
- .setBestValue(0.0)
- .create();
+ .setDescription("Package dependencies to cut")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setFormula(new SumChildValuesFormula(false))
+ .setBestValue(0.0)
+ .create();
public static final String PACKAGE_EDGES_WEIGHT_KEY = "package_edges_weight";
public static final Metric PACKAGE_EDGES_WEIGHT = new Metric.Builder(PACKAGE_EDGES_WEIGHT_KEY, "Package edges weight", Metric.ValueType.INT)
- .setDescription("Package edges weight")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setFormula(new SumChildValuesFormula(false))
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Package edges weight")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setFormula(new SumChildValuesFormula(false))
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String FILE_CYCLES_KEY = "file_cycles";
public static final Metric FILE_CYCLES = new Metric.Builder(FILE_CYCLES_KEY, "File cycles", Metric.ValueType.INT)
- .setDescription("File cycles")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .setBestValue(0.0)
- .create();
+ .setDescription("File cycles")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .setBestValue(0.0)
+ .create();
public static final String FILE_TANGLE_INDEX_KEY = "file_tangle_index";
public static final Metric FILE_TANGLE_INDEX = new Metric.Builder(FILE_TANGLE_INDEX_KEY, "File tangle index", Metric.ValueType.PERCENT)
- .setDescription("File tangle index")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .setBestValue(0.0)
- .create();
+ .setDescription("File tangle index")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .setBestValue(0.0)
+ .create();
public static final String FILE_TANGLES_KEY = "file_tangles";
public static final Metric FILE_TANGLES = new Metric.Builder(FILE_TANGLES_KEY, "File tangles", Metric.ValueType.INT)
- .setDescription("Files tangles")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("Files tangles")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .create();
public static final String FILE_FEEDBACK_EDGES_KEY = "file_feedback_edges";
public static final Metric FILE_FEEDBACK_EDGES = new Metric.Builder(FILE_FEEDBACK_EDGES_KEY, "Suspect file dependencies", Metric.ValueType.INT)
- .setDescription("Suspect file dependencies")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .setBestValue(0.0)
- .create();
+ .setDescription("Suspect file dependencies")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .setBestValue(0.0)
+ .create();
public static final String FILE_EDGES_WEIGHT_KEY = "file_edges_weight";
public static final Metric FILE_EDGES_WEIGHT = new Metric.Builder(FILE_EDGES_WEIGHT_KEY, "File edges weight", Metric.ValueType.INT)
- .setDescription("File edges weight")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(false)
- .setDomain(DOMAIN_DESIGN)
- .setHidden(true)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("File edges weight")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(false)
+ .setDomain(DOMAIN_DESIGN)
+ .setHidden(true)
+ .setDeleteHistoricalData(true)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
* @since 2.7
*/
public static final Metric SCM_AUTHORS_BY_LINE = new Metric.Builder(SCM_AUTHORS_BY_LINE_KEY, "Authors by line", Metric.ValueType.DATA)
- .setDomain(DOMAIN_SCM)
- .create();
+ .setDomain(DOMAIN_SCM)
+ .create();
/**
* @since 2.7
* @since 2.7
*/
public static final Metric SCM_REVISIONS_BY_LINE = new Metric.Builder(SCM_REVISIONS_BY_LINE_KEY, "Revisions by line", Metric.ValueType.DATA)
- .setDomain(DOMAIN_SCM)
- .create();
+ .setDomain(DOMAIN_SCM)
+ .create();
/**
* @since 2.7
* @since 2.7
*/
public static final Metric SCM_LAST_COMMIT_DATETIMES_BY_LINE = new Metric.Builder(SCM_LAST_COMMIT_DATETIMES_BY_LINE_KEY, "Last commit dates by line", Metric.ValueType.DATA)
- .setDomain(DOMAIN_SCM)
- .create();
+ .setDomain(DOMAIN_SCM)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final String UNREVIEWED_VIOLATIONS_KEY = "unreviewed_violations";
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final Metric UNREVIEWED_VIOLATIONS = new Metric.Builder(UNREVIEWED_VIOLATIONS_KEY, "Unreviewed violations", Metric.ValueType.INT)
- .setDescription("Violations that have not been reviewed yet")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_REVIEWS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Violations that have not been reviewed yet")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_REVIEWS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final String NEW_UNREVIEWED_VIOLATIONS_KEY = "new_unreviewed_violations";
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final Metric NEW_UNREVIEWED_VIOLATIONS = new Metric.Builder(NEW_UNREVIEWED_VIOLATIONS_KEY, "New unreviewed violations", Metric.ValueType.INT)
- .setDescription("New violations that have not been reviewed yet")
- .setDirection(Metric.DIRECTION_WORST)
- .setQualitative(true)
- .setDomain(DOMAIN_REVIEWS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .setDeleteHistoricalData(true)
- .create();
+ .setDescription("New violations that have not been reviewed yet")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setQualitative(true)
+ .setDomain(DOMAIN_REVIEWS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .setDeleteHistoricalData(true)
+ .create();
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is replaced by {@link #FALSE_POSITIVE_ISSUES_KEY}.
*/
+ @Deprecated
public static final String FALSE_POSITIVE_REVIEWS_KEY = "false_positive_reviews";
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is replaced by {@link #FALSE_POSITIVE_ISSUES}.
*/
+ @Deprecated
public static final Metric FALSE_POSITIVE_REVIEWS = new Metric.Builder(FALSE_POSITIVE_REVIEWS_KEY, "False-positive reviews", Metric.ValueType.INT)
- .setDescription("Active false-positive reviews")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_REVIEWS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Active false-positive reviews")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_REVIEWS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final String ACTIVE_REVIEWS_KEY = "active_reviews";
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final Metric ACTIVE_REVIEWS = new Metric.Builder(ACTIVE_REVIEWS_KEY, "Active reviews", Metric.ValueType.INT)
- .setDescription("Active open and reopened reviews")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_REVIEWS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Active open and reopened reviews")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_REVIEWS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final String UNASSIGNED_REVIEWS_KEY = "unassigned_reviews";
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final Metric UNASSIGNED_REVIEWS = new Metric.Builder(UNASSIGNED_REVIEWS_KEY, "Unassigned reviews", Metric.ValueType.INT)
- .setDescription("Active unassigned reviews")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_REVIEWS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Active unassigned reviews")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_REVIEWS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final String UNPLANNED_REVIEWS_KEY = "unplanned_reviews";
/**
* @since 2.14
+ * @deprecated in 3.6. This measure is not fed anymore since introduction of issues.
*/
+ @Deprecated
public static final Metric UNPLANNED_REVIEWS = new Metric.Builder(UNPLANNED_REVIEWS_KEY, "Unplanned reviews", Metric.ValueType.INT)
- .setDescription("Active unplanned reviews")
- .setDirection(Metric.DIRECTION_WORST)
- .setDomain(DOMAIN_REVIEWS)
- .setBestValue(0.0)
- .setOptimizedBestValue(true)
- .create();
+ .setDescription("Active unplanned reviews")
+ .setDirection(Metric.DIRECTION_WORST)
+ .setDomain(DOMAIN_REVIEWS)
+ .setBestValue(0.0)
+ .setOptimizedBestValue(true)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
*/
@Beta
public static final Metric NCLOC_DATA = new Metric.Builder(NCLOC_DATA_KEY, "ncloc_data", Metric.ValueType.DATA)
- .setHidden(true)
- .setDomain(DOMAIN_SIZE)
- .create();
+ .setHidden(true)
+ .setDomain(DOMAIN_SIZE)
+ .create();
/**
* @since 2.14
*/
@Beta
public static final Metric COMMENT_LINES_DATA = new Metric.Builder(COMMENT_LINES_DATA_KEY, "comment_lines_data", Metric.ValueType.DATA)
- .setHidden(true)
- .setDomain(DOMAIN_DOCUMENTATION)
- .create();
+ .setHidden(true)
+ .setDomain(DOMAIN_DOCUMENTATION)
+ .create();
// --------------------------------------------------------------------------------------------------------------------
//
public static final String ALERT_STATUS_KEY = "alert_status";
public static final Metric ALERT_STATUS = new Metric.Builder(ALERT_STATUS_KEY, "Alert", Metric.ValueType.LEVEL)
- .setDescription("Alert")
- .setDirection(Metric.DIRECTION_BETTER)
- .setQualitative(true)
- .setDomain(DOMAIN_GENERAL)
- .create();
+ .setDescription("Alert")
+ .setDirection(Metric.DIRECTION_BETTER)
+ .setQualitative(true)
+ .setDomain(DOMAIN_GENERAL)
+ .create();
public static final String PROFILE_KEY = "profile";
public static final Metric PROFILE = new Metric.Builder(PROFILE_KEY, "Profile", Metric.ValueType.DATA)
- .setDescription("Selected quality profile")
- .setDomain(DOMAIN_GENERAL)
- .create();
+ .setDescription("Selected quality profile")
+ .setDomain(DOMAIN_GENERAL)
+ .create();
/**
* @since 2.9
* @since 2.9
*/
public static final Metric PROFILE_VERSION = new Metric.Builder(PROFILE_VERSION_KEY, "Profile version", Metric.ValueType.INT)
- .setDescription("Selected quality profile version")
- .setQualitative(false)
- .setDomain(DOMAIN_GENERAL)
- .setHidden(true)
- .create();
+ .setDescription("Selected quality profile version")
+ .setQualitative(false)
+ .setDomain(DOMAIN_GENERAL)
+ .setHidden(true)
+ .create();
private static final List<Metric> METRICS;
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.api.database.model;
-
-import org.apache.commons.lang.StringUtils;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.Matchers.greaterThan;
-import static org.hamcrest.Matchers.startsWith;
-import static org.junit.Assert.assertThat;
-import org.junit.Test;
-
-import java.io.UnsupportedEncodingException;
-
-public class RuleFailureModelTest {
-
- @Test
- public void trimAndAbbreviateMessage() {
- final RuleFailureModel violation = new RuleFailureModel();
- violation.setMessage(" " + StringUtils.repeat("a", RuleFailureModel.MESSAGE_COLUMN_SIZE * 2));
- assertThat(violation.getMessage().length(), is(RuleFailureModel.MESSAGE_COLUMN_SIZE));
- assertThat(violation.getMessage(), startsWith("aaaaa"));
- }
-
- /**
- * this is a strange behavior with default Oracle settings...
- * <p/>
- * See SONAR-1073 :
- * Oracle uses as default the setting NLS_LENGTH_SEMANTICS=BYTE. In this case the character columns are created as
- * VARCHAR2(500) instead of VARCHAR2(500 CHAR). So the columns are created with a limitation of 500 single byte characters.
- * In UTF-8 some special characters need up to 6 single byte characters.
- * The problem is that Hibernate checks that the message does not exceed 500 Unicode characters.
- */
- @Test
- public void abbreviateMessageFromSizeInCharacters() throws UnsupportedEncodingException {
- assertThat("\u20AC".length(), is(1));
- // but EURO symbol is encoded on three bytes
- assertThat("\u20AC".getBytes("UTF-8").length, is(3));
-
- final RuleFailureModel violation = new RuleFailureModel();
- violation.setMessage(StringUtils.repeat("€", RuleFailureModel.MESSAGE_COLUMN_SIZE));
-
- assertThat(violation.getMessage().length(), is(RuleFailureModel.MESSAGE_COLUMN_SIZE));
-
- // THIS IS THE BUG ON ORACLE !!!!!!!!
- assertThat(violation.getMessage().getBytes("UTF-8").length, greaterThan(RuleFailureModel.MESSAGE_COLUMN_SIZE));
- }
-}
import org.sonar.core.timemachine.Periods;
import org.sonar.core.user.DefaultUserFinder;
import org.sonar.core.user.HibernateUserFinder;
-import org.sonar.core.workflow.ReviewDatabaseStore;
import org.sonar.core.workflow.WorkflowEngine;
import org.sonar.jpa.dao.MeasuresDao;
import org.sonar.jpa.dao.ProfilesDao;
private void startServiceComponents() {
servicesContainer = coreContainer.createChild();
servicesContainer.addSingleton(DefaultWorkflow.class);
- servicesContainer.addSingleton(ReviewDatabaseStore.class);
servicesContainer.addSingleton(WorkflowEngine.class);
servicesContainer.addSingleton(HttpDownloader.class);
servicesContainer.addSingleton(UriReader.class);
*/
public final class DefaultPages {
- private static final View[] PAGES = {new SourceTab(), new CoverageTab(), new ViolationsTab(), new IssuesTab(), new DuplicationsTab()};
+ private static final View[] PAGES = {new SourceTab(), new CoverageTab(), new IssuesTab(), new DuplicationsTab()};
private DefaultPages() {
}
@NavigationSection(NavigationSection.RESOURCE_TAB)
@DefaultTab(
- metrics = {CoreMetrics.VIOLATIONS_DENSITY_KEY, CoreMetrics.WEIGHTED_VIOLATIONS_KEY, CoreMetrics.VIOLATIONS_KEY, CoreMetrics.BLOCKER_VIOLATIONS_KEY,
- CoreMetrics.CRITICAL_VIOLATIONS_KEY, CoreMetrics.MAJOR_VIOLATIONS_KEY, CoreMetrics.MINOR_VIOLATIONS_KEY, CoreMetrics.INFO_VIOLATIONS_KEY,
- CoreMetrics.NEW_VIOLATIONS_KEY, CoreMetrics.NEW_BLOCKER_VIOLATIONS_KEY, CoreMetrics.NEW_CRITICAL_VIOLATIONS_KEY, CoreMetrics.NEW_MAJOR_VIOLATIONS_KEY,
- CoreMetrics.NEW_MINOR_VIOLATIONS_KEY, CoreMetrics.NEW_INFO_VIOLATIONS_KEY, CoreMetrics.ACTIVE_REVIEWS_KEY, CoreMetrics.UNASSIGNED_REVIEWS_KEY,
- CoreMetrics.UNPLANNED_REVIEWS_KEY, CoreMetrics.FALSE_POSITIVE_REVIEWS_KEY, CoreMetrics.UNREVIEWED_VIOLATIONS_KEY, CoreMetrics.NEW_UNREVIEWED_VIOLATIONS_KEY})
- @ResourceQualifier(
- value = {Qualifiers.VIEW, Qualifiers.SUBVIEW, Qualifiers.PROJECT, Qualifiers.MODULE, Qualifiers.PACKAGE, Qualifiers.DIRECTORY, Qualifiers.FILE, Qualifiers.CLASS,
- Qualifiers.UNIT_TEST_FILE})
- @UserRole(UserRole.CODEVIEWER)
- private static final class ViolationsTab implements RubyRailsPage {
- public String getTemplate() {
- // not used, hardcoded in BrowseController
- return "browse/index";
- }
-
- public String getId() {
- return "violations";
- }
-
- public String getTitle() {
- return "Violations";
- }
- }
-
- @NavigationSection(NavigationSection.RESOURCE_TAB)
- @DefaultTab(
- metrics = {CoreMetrics.ISSUES_DENSITY_KEY, CoreMetrics.WEIGHTED_ISSUES_KEY, CoreMetrics.ISSUES_KEY, CoreMetrics.BLOCKER_ISSUES_KEY,
- CoreMetrics.CRITICAL_ISSUES_KEY, CoreMetrics.MAJOR_ISSUES_KEY, CoreMetrics.MINOR_ISSUES_KEY, CoreMetrics.INFO_ISSUES_KEY,
- CoreMetrics.NEW_ISSUES_KEY, CoreMetrics.NEW_BLOCKER_ISSUES_KEY, CoreMetrics.NEW_CRITICAL_ISSUES_KEY, CoreMetrics.NEW_MAJOR_ISSUES_KEY,
- CoreMetrics.NEW_MINOR_ISSUES_KEY, CoreMetrics.NEW_INFO_ISSUES_KEY,
- CoreMetrics.UNASSIGNED_ISSUES_KEY, CoreMetrics.FALSE_POSITIVE_ISSUES_KEY
- // TODO
-// CoreMetrics.UNPLANNED_REVIEWS_KEY
+ metrics = {CoreMetrics.VIOLATIONS_DENSITY_KEY, CoreMetrics.WEIGHTED_VIOLATIONS_KEY, CoreMetrics.VIOLATIONS_KEY, CoreMetrics.BLOCKER_VIOLATIONS_KEY,
+ CoreMetrics.CRITICAL_VIOLATIONS_KEY, CoreMetrics.MAJOR_VIOLATIONS_KEY, CoreMetrics.MINOR_VIOLATIONS_KEY, CoreMetrics.INFO_VIOLATIONS_KEY,
+ CoreMetrics.NEW_VIOLATIONS_KEY, CoreMetrics.NEW_BLOCKER_VIOLATIONS_KEY, CoreMetrics.NEW_CRITICAL_VIOLATIONS_KEY, CoreMetrics.NEW_MAJOR_VIOLATIONS_KEY,
+ CoreMetrics.NEW_MINOR_VIOLATIONS_KEY, CoreMetrics.NEW_INFO_VIOLATIONS_KEY,
+ CoreMetrics.FALSE_POSITIVE_ISSUES_KEY
})
@ResourceQualifier(
value = {Qualifiers.VIEW, Qualifiers.SUBVIEW, Qualifiers.PROJECT, Qualifiers.MODULE, Qualifiers.PACKAGE, Qualifiers.DIRECTORY, Qualifiers.FILE, Qualifiers.CLASS,
require "json"
-# Google Wire Protocol controller helper
+# Google Wire Protocol controller helper.
+# Used by the MotionChart plugin.
class Api::GwpResourcesController < Api::ResourceRestController
before_filter :parse_gwp_params
+++ /dev/null
-#
-# Sonar, entreprise quality control tool.
-# Copyright (C) 2008-2013 SonarSource
-# mailto:contact AT sonarsource DOT com
-#
-# SonarQube is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 3 of the License, or (at your option) any later version.
-#
-# SonarQube is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-
-require 'json'
-
-class Api::ReviewsController < Api::ApiController
-
- verify :method => :put, :only => [:add_comment, :reassign, :resolve, :reopen]
- verify :method => :post, :only => [:create]
-
- #
- # --- Search reviews ---
- # Since 2.8
- #
- # GET /api/reviews
- # Optional parameters :
- # - 'statuses'
- # - 'resolutions' (since 2.9)
- # - 'severities'
- # - 'projects'
- # - 'resources'
- # - 'authors'
- # - 'assignees'
- #
- def index
- reviews=select_authorized(:user, Review.search(params.merge({'limit' => 500})), :project)
-
- render_reviews(reviews, params[:output] == 'HTML')
- end
-
- # Review of an existing violation or create a new violation.
- #
- # Since 2.9
- # POST /api/reviews
- #
- # ==== Requirements
- #
- # * If the violation must be created on a given line of a file, then source code must be available. It
- # means that it's not compatible with the property sonar.importSources=false.
- #
- # * Requires the USER role on the related project
- #
- # ==== Parameters
- #
- # To review an existing violation :
- # * 'violation_id' : the violation on which the review should be created
- #
- # To create a violation :
- # * 'rule_name' : the name of the rule in the repository "manual". If it does not exist then the rule is created.
- # * 'resource' : id or key of the resource to review
- # * 'line' : optional line. It starts from 1. If 0 then no specific line. Default value is 0.
- # * 'severity' : BLOCKER, CRITICAL, MAJOR, MINOR or INFO. Default value is MAJOR.
- # * 'cost' : optional numeric cost
- #
- # Other parameters :
- # * 'status' : the initial status (can be 'OPEN' or 'RESOLVED')
- # * 'comment' : the text of the comment
- # * 'resolution' (optional) : if status 'RESOLVED', then resolution must be provided (can be 'FIXED' or 'FALSE-POSITIVE')
- # * 'assignee' (optional) : login used to create a review directly assigned
- #
- # ==== Examples
- #
- # * Create a manual violation : POST /api/reviews?resource=MyFile&line=18&status=OPEN&rule_name=Performance%20Issue
- # * Review an existing violation : POST /api/reviews?violation_id=1&status=OPEN&assignee=admin&comment=Please%20fix%20this
- # * Flag an existing violation as false-positive : POST /api/reviews/?violation_id=2&status=RESOLVED&resolution=FALSE-POSITIVE&comment=No%20violation%20here
- # * Resolve an existing violation : POST /api/reviews/?violation_id=3&status=RESOLVED&resolution=FIXED&assignee=admin&comment=This%20violation%20was%20fixed%20by%20me
- #
- def create
- # Validate parameters
- convert_markdown=(params[:output]=='HTML')
- assignee = find_user(params[:assignee])
- status = params[:status]
- resolution = params[:resolution]
- comment = params[:comment] || request.raw_post
- bad_request("Missing parameter 'status'") if status.blank?
- bad_request("Missing parameter 'comment'") if comment.blank?
- review = nil
-
- Review.transaction do
- if params[:violation_id].present?
- # Review an existing violation
- violation = RuleFailure.find(params[:violation_id], :include => :rule)
- access_denied unless has_rights_to_modify?(violation.resource)
- bad_request("Violation is already reviewed") if violation.review
- sanitize_violation(violation)
- violation.create_review!(:assignee => assignee, :user => current_user, :manual_violation => false)
-
- else
- # Manually create a violation and review it
- bad_request("Missing parameter 'rule_name'") if params[:rule_name].blank?
- bad_request("Missing parameter 'resource'") if params[:resource].blank?
- resource = Project.by_key(params[:resource])
- access_denied unless resource && has_rights_to_modify?(resource)
- bad_request("Resource does not exist") unless resource.last_snapshot
-
- rule = Rule.find_or_create_manual_rule(params[:rule_name], has_role?(:admin))
- access_denied unless rule
- violation = rule.create_violation!(resource, params)
- violation.create_review!(:assignee => assignee, :user => current_user, :manual_violation => true)
- end
-
- # Set review status
- review = violation.review
- if status == Review::STATUS_OPEN
- review.create_comment(:user => current_user, :text => comment)
- elsif status == Review::STATUS_RESOLVED
- if resolution == Review::RESOLUTION_FALSE_POSITIVE
- review.set_false_positive(true, current_user, :text => comment)
- elsif resolution == Review::RESOLUTION_FIXED
- review.create_comment(:user => current_user, :text => comment)
- review.resolve(current_user)
- else
- bad_request("Incorrect resolution")
- end
- else
- bad_request("Incorrect status")
- end
- end
-
- # 5- And finally send back the review
- render_reviews([review], convert_markdown)
- end
-
- #
- # --- Add comment ---
- # Since 2.9
- #
- # PUT /api/reviews/add_comment
- # Required parameters:
- # - 'id' : the review id
- # - 'comment' : the text of the comment
- #
- # Example :
- # - PUT "/api/reviews/add_comment/1?comment=New%20Comment!"
- #
- def add_comment
- begin
- review = get_review(params[:id])
- review.transaction do
- comment = params[:comment] || request.raw_post
- if review.closed?
- raise "Closed review can not be commented."
- end
- raise "Comment must be provided." unless comment && !comment.blank?
- review.create_comment(:user => current_user, :text => comment)
- end
- render_reviews([review], params[:output] == 'HTML')
- rescue ApiException => e
- render_error(e.msg, e.code)
- rescue Exception => e
- render_error(e.message, 400)
- end
- end
-
- #
- # --- Reassign ---
- # Since 2.9
- #
- # PUT /api/reviews/reassign
- # Required parameters:
- # - 'id' : the review id
- # - 'assignee' : new assignee
- #
- # Example :
- # - PUT "/api/reviews/reassign/1?assignee=fabrice"
- # - PUT "/api/reviews/reassign/1?assignee="
- #
- def reassign
- begin
- review = get_review(params[:id])
- review.transaction do
- assignee = params[:assignee]
- if !review.open? && !review.reopened?
- raise "Only open review can be reassigned."
- end
- if assignee.blank?
- user = nil
- else
- user = find_user(assignee)
- raise "Assignee not found." unless user
- end
- review.reassign(current_user, user)
- end
- render_reviews([review], params[:output] == 'HTML')
- rescue ApiException => e
- render_error(e.msg, e.code)
- rescue Exception => e
- render_error(e.message, 400)
- end
- end
-
- #
- # --- Resolve ---
- # Since 2.9
- #
- # PUT /api/reviews/resolve
- # Required parameters:
- # - 'id' : the review id
- # - 'resolution' : can be 'FIXED' or 'FALSE-POSITIVE'
- # - 'comment' : the text of the comment
- #
- # Example :
- # - PUT "/api/reviews/resolve/1?resolution=FALSE-POSITIVE&comment=No%20violation%20here"
- # - PUT "/api/reviews/resolve/1?resolution=FIXED"
- # - PUT "/api/reviews/resolve/1?resolution=FIXED&comment=This%20violation%20was%20fixed%20by%20me"
- #
- def resolve
- begin
- review = get_review(params[:id])
- review.transaction do
- resolution = params[:resolution]
- comment = params[:comment] || request.raw_post
- if !review.open? && !review.reopened?
- raise "Only open review can be resolved."
- end
- if resolution == Review::RESOLUTION_FALSE_POSITIVE
- raise "Comment must be provided." unless comment && !comment.blank?
- review.set_false_positive(true, current_user, :text => comment)
- elsif resolution == Review::RESOLUTION_FIXED
- review.create_comment(:user => current_user, :text => comment) unless comment.blank?
- review.resolve(current_user)
- else
- raise "Incorrect resolution."
- end
- end
- render_reviews([review], params[:output] == 'HTML')
- rescue ApiException => e
- render_error(e.msg, e.code)
- rescue Exception => e
- render_error(e.message, 400)
- end
- end
-
- #
- # --- Reopen ---
- # Since 2.9
- #
- # PUT /api/reviews/reopen
- # Required parameters:
- # - 'id' : the review id
- # - 'comment' : the text of the comment
- #
- # Example :
- # - PUT "/api/reviews/reopen/1"
- # - PUT "/api/reviews/reopen/1?comment=Not%20fixed"
- #
- def reopen
- begin
- review = get_review(params[:id])
- review.transaction do
- comment = params[:comment] || request.raw_post
- if !review.resolved?
- raise "Only resolved review can be reopened."
- end
- if review.resolution == Review::RESOLUTION_FALSE_POSITIVE
- raise "Comment must be provided." unless comment && !comment.blank?
- review.set_false_positive(false, current_user, :text => comment)
- else
- review.reopen(current_user)
- review.create_comment(:user => current_user, :text => comment) unless comment.blank?
- end
- end
- render_reviews([review], params[:output] == 'HTML')
- rescue ApiException => e
- render_error(e.msg, e.code)
- rescue Exception => e
- render_error(e.message, 400)
- end
- end
-
-
- private
-
- def get_review(id)
- raise "No 'id' parameter has been provided." unless id
- review = Review.find(id, :include => ['project'])
- raise ApiException.new(401, 'Unauthorized') unless has_rights_to_modify?(review.project)
- review
- end
-
- def render_reviews(reviews, convert_markdown)
- respond_to do |format|
- format.json { render :json => jsonp(Review.reviews_to_json(reviews, convert_markdown)) }
- format.xml { render :xml => Review.reviews_to_xml(reviews, convert_markdown) }
- format.text { render :text => text_not_supported }
- end
- end
-
- def find_user(login)
- unless login.blank?
- users = User.find(:all, :conditions => ["login = ?", login])
- users[0] if users.size > 0
- end
- end
-
- def has_rights_to_modify?(object)
- current_user && has_role?(:user, object)
- end
-
- def sanitize_violation(violation)
- # the field RULE_FAILURES.PERMANENT_ID is not set when upgrading to version 2.8.
- # It must be manually set when using a violation created before v2.8.
- if violation.permanent_id.nil?
- violation.permanent_id=violation.id
- violation.save
- end
- end
-
-end
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
-require 'json'
+class Api::ViolationsController < Api::ApiController
-class Api::ViolationsController < Api::ResourceRestController
+ def index
+ conditions={}
- def rest_call
- snapshot = @resource.last_snapshot
-
- conditions=[]
- values={}
if params['scopes']
- conditions << 'snapshots.scope in (:scopes)'
- values[:scopes]=params['scopes'].split(',')
+ rest_error('The parameter "scopes" is not supported since version 3.6.')
end
+
if params['qualifiers']
- conditions << 'snapshots.qualifier in (:qualifiers)'
- values[:qualifiers]=params['qualifiers'].split(',')
+ rest_error('The parameter "qualifiers" is not supported since version 3.6.')
end
+ resource = params[:resource]
depth=(params['depth'] ? params['depth'].to_i : 0)
if depth==0
- conditions << 'snapshots.id=:sid'
- values[:sid]=snapshot.id
-
+ conditions[:components] = resource
elsif depth>0
- # all the resource tree
- conditions << 'snapshots.root_snapshot_id=:root_sid'
- values[:root_sid] = (snapshot.root_snapshot_id || snapshot.id)
-
- conditions << 'snapshots.path LIKE :path'
- values[:path]="#{snapshot.path}#{snapshot.id}.%"
-
- conditions << 'snapshots.depth=:depth'
- values[:depth] = snapshot.depth + depth
-
+ rest_error('The parameter "depth" is not supported since version 3.6.')
else
# negative : all the resource tree
- conditions << '(snapshots.id=:sid OR (snapshots.root_snapshot_id=:root_sid AND snapshots.path LIKE :path))'
- values[:sid] = snapshot.id
- values[:root_sid] = (snapshot.root_snapshot_id || snapshot.id)
- values[:path]="#{snapshot.path}#{snapshot.id}.%"
+ conditions[:componentRoots] = resource
end
if params[:rules]
- rule_ids=params[:rules].split(',').map do |key_or_id|
- Rule.to_i(key_or_id)
- end.compact
- conditions << 'rule_failures.rule_id IN (:rule_ids)'
- values[:rule_ids] = rule_ids
+ conditions[:rules] = params[:rules].split(',')
end
+
if params[:priorities]
- conditions << 'rule_failures.failure_level IN (:priorities)'
- values[:priorities]=params[:priorities].split(',').map do |p|
- Sonar::RulePriority.id(p)
- end.compact
+ conditions[:severities] = params[:priorities].split(',')
end
- if params[:switched_off] == "true"
- conditions << 'rule_failures.switched_off=:switched_off'
- values[:switched_off] = true
- else
- conditions << '(rule_failures.switched_off IS NULL OR rule_failures.switched_off=:switched_off)'
- values[:switched_off] = false
+ if params[:switched_off] == 'true'
+ conditions[:resolutions]='FALSE-POSITIVE'
end
- limit = (params[:limit] ? [params[:limit].to_i,5000].min : 5000)
- violations = RuleFailure.all(
- :conditions => [ conditions.join(' AND '), values],
- :include => [:snapshot, {:snapshot => :project}, :rule, :review],
- :order => 'rule_failures.failure_level DESC',
- :limit => limit)
- rest_render(violations)
- end
+ limit = (params[:limit] ? [params[:limit].to_i,5000].min : 5000)
+ conditions[:pageSize]=limit
- def rest_to_json(rule_failures)
- include_review=(params['include_review']=='true')
- convert_markdown=(params[:output]=='HTML')
- JSON(rule_failures.collect{|rule_failure| rule_failure.to_json(include_review, convert_markdown)})
- end
+ results = Api.issues.find(conditions)
- def rest_to_xml(rule_failures)
- include_review=(params['include_review']=='true')
- convert_markdown=(params[:output]=='HTML')
- xml = Builder::XmlMarkup.new(:indent => 0)
- xml.instruct!
- xml.violations do
- rule_failures.each do |rule_failure|
- rule_failure.to_xml(xml, include_review, convert_markdown)
+ array = results.issues.map do |issue|
+ hash={:id => issue.key}
+ hash[:message] = issue.message if issue.message
+ hash[:line] = issue.line.to_i if issue.line
+ hash[:priority] = issue.severity if issue.severity
+ hash[:createdAt] = Api::Utils.format_datetime(issue.creationDate) if issue.creationDate
+ hash[:switchedOff]=true if issue.resolution=='FALSE-POSITIVE'
+ rule = results.rule(issue)
+ if rule
+ hash[:rule] = {:key => rule.ruleKey, :name => Internal.rules.ruleL10nName(rule)}
+ end
+ resource = results.component(issue)
+ if resource
+ hash[:resource] = {:key => resource.key, :name => resource.name, :qualifier => resource.qualifier}
end
+ hash
end
- end
+ respond_to do |format|
+ format.json { render :json => jsonp(array) }
+ format.xml { render :xml => array.to_xml(:skip_types => true, :root => 'violations') }
+ end
+ end
end
\ No newline at end of file
@display_viewers=display_metric_viewers?(@highlighted_resource||@resource, @highlighted_metric.key)
end
- def violations
- @rule=Rule.by_key_or_id(params[:rule])
-
- # variation measures
- if params[:period].present? && params[:period].to_i>0
- @period=params[:period].to_i
- metric_prefix = 'new_'
- else
- @period=nil
- metric_prefix = ''
- end
-
- @severity = params[:severity] || params[:priority]
- @rule_severity = params[:rule_sev] || @severity
-
- if @rule && @rule_severity.blank?
- # workaround for SONAR-3255 : guess the severity
- @rule_severity=guess_rule_severity(@snapshot, @rule, metric_prefix)
- end
-
-
- if @rule_severity.present?
- # Filter resources by severity
- @metric = Metric::by_key("#{metric_prefix}#{@rule_severity.downcase}_violations")
- else
- @metric = Metric::by_key("#{metric_prefix}violations")
- end
-
- # selected resources
- if params[:rids]
- @selected_rids= params[:rids]
- elsif params[:resource]
- highlighted_resource=Project.by_key(params[:resource])
- @selected_rids=(highlighted_resource ? [highlighted_resource.id] : [])
- else
- @selected_rids=[]
- end
- @selected_rids=@selected_rids.map { |r| r.to_i }
-
-
- # options for Drilldown
- options={:exclude_zero_value => true, :period => @period}
- if @rule
- params[:rule]=@rule.key # workaround for SONAR-1767 : the javascript hash named "rp" in the HTML source must contain the rule key, but not the rule id
- options[:rule_id]=@rule.id
- end
-
- # load data
- @drilldown = Drilldown.new(@resource, @metric, @selected_rids, options)
-
- @highlighted_resource=@drilldown.highlighted_resource
- if @highlighted_resource.nil? && @drilldown.columns.empty?
- @highlighted_resource=@resource
- end
-
-
- #
- # Initialize filter by rule
- #
- if @severity.present?
- # Filter on severity -> filter rule measures by the selected metric
- @rule_measures = @snapshot.rule_measures(@metric)
- else
- # No filter -> loads all the rules
- metrics=[
- Metric.by_key("#{metric_prefix}blocker_violations"),
- Metric.by_key("#{metric_prefix}critical_violations"),
- Metric.by_key("#{metric_prefix}major_violations"),
- Metric.by_key("#{metric_prefix}minor_violations"),
- Metric.by_key("#{metric_prefix}info_violations")
- ]
- @rule_measures = @snapshot.rule_measures(metrics)
- end
-
- @display_viewers=display_violation_viewers?(@drilldown.highlighted_snapshot || @snapshot)
- end
-
def issues
@rule=Rule.by_key_or_id(params[:rule])
if @rule_severity.present?
# Filter resources by severity
- @metric = Metric::by_key("#{metric_prefix}#{@rule_severity.downcase}_issues")
+ @metric = Metric::by_key("#{metric_prefix}#{@rule_severity.downcase}_violations")
else
- @metric = Metric::by_key("#{metric_prefix}issues")
+ @metric = Metric::by_key("#{metric_prefix}violations")
end
# selected resources
else
# No filter -> loads all the rules
metrics=[
- Metric.by_key("#{metric_prefix}blocker_issues"),
- Metric.by_key("#{metric_prefix}critical_issues"),
- Metric.by_key("#{metric_prefix}major_issues"),
- Metric.by_key("#{metric_prefix}minor_issues"),
- Metric.by_key("#{metric_prefix}info_issues")
+ Metric.by_key("#{metric_prefix}blocker_violations"),
+ Metric.by_key("#{metric_prefix}critical_violations"),
+ Metric.by_key("#{metric_prefix}major_violations"),
+ Metric.by_key("#{metric_prefix}minor_violations"),
+ Metric.by_key("#{metric_prefix}info_violations")
]
@rule_measures = @snapshot.rule_measures(metrics)
end
def guess_rule_severity_for_issues_metric(snapshot, rule, metric_prefix)
Severity::KEYS.each do |severity|
- if snapshot.rule_measure(Metric.by_key("#{metric_prefix}#{severity.downcase}_issues"), rule)
+ if snapshot.rule_measure(Metric.by_key("#{metric_prefix}#{severity.downcase}_violations"), rule)
return severity
end
end
+++ /dev/null
-#
-# Sonar, entreprise quality control tool.
-# Copyright (C) 2008-2013 SonarSource
-# mailto:contact AT sonarsource DOT com
-#
-# SonarQube is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 3 of the License, or (at your option) any later version.
-#
-# SonarQube is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-
-class ProjectReviewsController < ApplicationController
-
- SECTION=Navigation::SECTION_RESOURCE
-
- verify :method => :post,
- :only => [:assign, :flag_as_false_positive, :save_comment, :delete_comment, :change_status,
- :link_to_action_plan, :unlink_from_action_plan],
- :redirect_to => {:action => :error_not_post}
- helper SourceHelper, UsersHelper
-
- # lists all the reviews of a project, filtered using the same parameters as for the review WS API
- def index
- @project=Project.by_key(params[:id])
- @project=Project.by_key(params[:projects]) unless @project
-
- if @project
- access_denied unless has_role?(:user, @project)
-
- # 'id' is the id of the project, so it should be removed from the search params
- found_reviews = Review.search(params.reject { |k, v| k=='id' })
- @reviews = select_authorized(:user, found_reviews, :project)
- if found_reviews.size != @reviews.size
- @security_exclusions = true
- end
- else
- render :text => "<b>Listing reviews without a project reference is not possible</b>. Go to review search service instead."
- end
- end
-
-
- # Used for the permalink, e.g. http://localhost:9000/project_reviews/view/1
- def view
- @review = Review.find(params[:id], :include => ['project'])
- @resource = @review.project
- if has_role?(:user, @review.project)
- render 'project_reviews/_view', :locals => {:review => @review}
- else
- render :text => "<b>Cannot access this review</b> : access denied."
- end
- end
-
-
- #
- #
- # ACTIONS FROM REVIEW SERVICE PAGE
- #
- #
-
- def show
- @review = Review.find(params[:id], :include => ['project'])
- @resource = @review.project
- if has_role?(:user, @resource)
- render :partial => 'project_reviews/view'
- else
- render :text => "access denied"
- end
- end
-
- # GET
- def assign_form
- @review = Review.find(params[:id])
- render :partial => "assign_form"
- end
-
- # POST
- def assign
- @review = Review.find(params[:id], :include => ['project'])
- @resource = @review.project
- unless has_rights_to_modify?(@resource)
- render :text => "<b>Cannot edit the review</b> : access denied."
- return
- end
-
- assignee = nil
- if params[:me]=='true'
- assignee = current_user
-
- elsif params[:assignee_login].present?
- assignee = findUserByLogin(params[:assignee_login])
- end
-
- @review.reassign(current_user, assignee, params)
- render :partial => 'project_reviews/view'
- end
-
- # GET
- def comment_form
- @review = Review.find(params[:id])
- if !params[:comment_id].blank? && @review
- @comment = @review.comments.find(params[:comment_id])
- end
- render :partial => 'project_reviews/comment_form'
- end
-
- # POST
- def save_comment
- @review = Review.find(params[:id], :include => ['project'])
- @resource = @review.project
- unless has_rights_to_modify?(@resource)
- render :text => "<b>Cannot create the comment</b> : access denied."
- return
- end
-
- unless params[:text].blank?
- if params[:comment_id]
- @review.edit_comment(current_user, params[:comment_id].to_i, params[:text])
- else
- @review.create_comment(:user => current_user, :text => params[:text])
- end
- end
-
- render :partial => "project_reviews/view"
- end
-
- # GET
- def false_positive_form
- @review = Review.find(params[:id])
- render :partial => 'project_reviews/false_positive_form'
- end
-
- # POST
- def flag_as_false_positive
- @review = Review.find(params[:id], :include => ['project'])
- @resource = @review.project
- unless has_rights_to_modify?(@resource)
- render :text => "<b>Cannot create the comment</b> : access denied."
- return
- end
-
- @review.set_false_positive(params[:false_positive]=='true', current_user, params)
- render :partial => "project_reviews/view"
- end
-
- # POST
- def delete_comment
- @review = Review.find(params[:id], :include => ['project'])
- @resource = @review.project
- unless has_rights_to_modify?(@resource)
- render :text => "<b>Cannot delete the comment</b> : access denied."
- return
- end
-
- if @review
- @review.delete_comment(current_user, params[:comment_id].to_i)
- end
- render :partial => "project_reviews/view"
- end
-
- def change_status_form
- @review = Review.find(params[:id])
- render :partial => 'project_reviews/change_status_form'
- end
-
- # POST
- def change_status
- @review = Review.find(params[:id], :include => ['project'])
- @resource = @review.project
- unless has_rights_to_modify?(@resource)
- render :text => "<b>Cannot change the status</b> : access denied."
- return
- end
-
- if @review.resolved?
- @review.reopen(current_user, params)
- else
- # for the moment, if a review is not open, it can only be "RESOLVED"
- @review.resolve(current_user, params)
- end
-
- render :partial => "project_reviews/view"
- end
-
- # GET
- def change_severity_form
- render :partial => 'project_reviews/change_severity_form'
- end
-
- # POST
- def change_severity
- @review=Review.find(params[:id], :include => 'project')
- @resource = @review.project
- unless has_rights_to_modify?(@resource)
- render :text => "<b>Cannot change severity</b> : access denied."
- return
- end
-
- @review.set_severity(params[:severity], current_user, params)
- render :partial => "project_reviews/review"
- end
-
- # GET
- def action_plan_form
- @review = Review.find(params[:id])
- @action_plans = ActionPlan.open_by_project_id(@review.project_id)
- render :partial => 'project_reviews/action_plan_form'
- end
-
- # POST
- def link_to_action_plan
- @review = Review.find(params[:id])
- @resource = @review.project
- unless has_rights_to_modify?(@resource)
- render :text => "<b>Cannot link to action plan</b> : access denied."
- return
- end
-
- action_plan = params[:action_plan_id].to_i==-1 ? nil : ActionPlan.find(params[:action_plan_id])
- @review.link_to_action_plan(action_plan, current_user, params)
-
- render :partial => "project_reviews/review"
- end
-
- # POST
- def unlink_from_action_plan
- @review = Review.find(params[:id])
- @resource = @review.project
- unless has_rights_to_modify?(@resource)
- render :text => "<b>Cannot link to action plan</b> : access denied."
- return
- end
-
- @review.link_to_action_plan(nil, current_user, params)
-
- render :partial => "project_reviews/review"
- end
-
- # GET
- def screen
- @review = Review.find(params[:id])
- bad_request('Unknown violation') unless @review
-
- command = params[:command]
- bad_request('Missing command') if command.blank?
-
- @screen = java_facade.getReviewScreen(command)
- bad_request('No associated screen') unless @screen
-
- render :partial => "project_reviews/screens/#{@screen.getKey()}"
- end
-
- # POST
- def execute
- bad_request('Missing review id') unless params[:id]
- @review = Review.find(params[:id], :include => ['project'])
-
- access_denied unless has_rights_to_modify?(@review.resource)
-
- bad_request('Missing command') if params[:command].blank?
-
- error_message = nil
- begin
- RuleFailure.execute_command(params[:command], @review.violation, current_user, params)
- rescue Exception => e
- error_message=Api::Utils.exception_message(e, :backtrace => false)
- end
-
- ActiveRecord::Base.uncached() do
- @review.clean_violation_cache
- @review.reload
-
- # TODO remove this ugly workaround to bypass ActiveRecord cache....
- @review.violation.review=@review
- end
- render :partial => "project_reviews/review", :locals => {:error_message => error_message}
- end
-
-
- #
- #
- # ACTIONS FROM THE REVIEW WIDGETS
- #
- #
-
- # GET
- def widget_reviews_list
- @snapshot = Snapshot.find(params[:snapshot_id])
- unless @snapshot && has_role?(:user, @snapshot)
- render :text => "<b>Cannot access the reviews of this project</b>: access denied."
- return
- end
-
- @dashboard_configuration=Api::DashboardConfiguration.new(nil, :period_index => params[:period], :snapshot => @snapshot)
- render :partial => 'project/widgets/reviews/reviews_list'
- end
-
-
- ## -------------- PRIVATE -------------- ##
- private
-
- def findUserByLogin(login)
- User.find(:first, :conditions => ["login = ?", login])
- end
-
- def has_rights_to_modify?(object)
- current_user && has_role?(:user, object)
- end
-
- def error_not_post
- render :text => "Create actions must use POST method."
- end
-
-end
helper :dashboard
helper SourceHelper, UsersHelper
- verify :method => :post, :only => [:create_violation]
-
def index
if request.xhr?
@resource = Project.by_key(params[:id])
load_extensions()
if @extension
- if @extension.getId()=='violations'
- render_violations()
- render_partial_index()
- elsif @extension.getId()=='issues'
+ if @extension.getId()=='issues'
render_issues()
- render :partial => 'index_issues'
+ render_partial_index()
elsif (@extension.getId()=='coverage')
render_coverage()
render_partial_index()
:group_index => params[:group_index], :external => (resource.root_id != original_resource.root_id)}
end
- # Ajax request to display a form to create a review anywhere in source code
- def show_create_violation_form
- @line = params[:line].to_i
- @rules = Rule.manual_rules
- @html_id="#{params[:resource]}_#{@line}"
- render :partial => 'resource/create_violation_form'
- end
-
- def create_violation
- resource = Project.by_key(params[:resource])
- access_denied unless resource && current_user
-
- rule_id_or_name = params[:rule]
- if rule_id_or_name.blank?
- access_denied if params[:new_rule].present? && !has_role?(:admin)
- rule_id_or_name = params[:new_rule]
- end
- bad_request(message('code_viewer.create_violation.missing_rule')) if rule_id_or_name.blank?
- bad_request(message('code_viewer.create_violation.missing_message')) if params[:message].blank?
- bad_request(message('code_viewer.create_violation.missing_severity')) if params[:severity].blank?
-
- assignee=nil
- if params[:assignee_login].present?
- assignee = User.first(:conditions => ["login = ?", params[:assignee_login]])
- bad_request(message('code_viewer.create_violation.bad_assignee')) unless assignee
- end
- violation = nil
- Review.transaction do
- rule = Rule.find_or_create_manual_rule(rule_id_or_name, true)
- violation = rule.create_violation!(resource, params)
- violation.create_review!(
- :assignee => assignee,
- :user => current_user,
- :status => Review::STATUS_OPEN,
- :manual_violation => true)
- end
-
- render :partial => 'resource/violation', :locals => {:violation => violation}
- end
-
private
def render_partial_index
@duplication_group_warning = message('duplications.dups_found_on_deleted_resource') if dups_found_on_deleted_resource
end
-
- def render_violations
- load_sources()
- @display_violations=true
- @global_violations=[]
- @expandable=(@lines!=nil)
- @filtered=!@expanded
- rule_param=params[:rule]
-
- options={:snapshot_id => @snapshot.id}
-
- if rule_param.blank? && params[:metric]
- metric = Metric.by_id(params[:metric])
- if metric && (metric.name=='active_reviews' || metric.name=='unassigned_reviews' || metric.name=='unplanned_reviews' || metric.name=='false_positive_reviews'|| metric.name=='unreviewed_violations' || metric.name=='new_unreviewed_violations')
- rule_param = metric.name.gsub(/new_/, '')
-
- # hack to select the correct option in the rule filter select-box
- params[:rule] = rule_param
- end
- end
-
- if !rule_param.blank? && rule_param!='all'
- if rule_param=='false_positive_reviews'
- options[:switched_off]=true
-
- elsif rule_param=='active_reviews'
- options[:review_statuses]=[Review::STATUS_OPEN, Review::STATUS_REOPENED, nil]
-
- elsif rule_param=='unassigned_reviews'
- options[:review_statuses]=[Review::STATUS_OPEN, Review::STATUS_REOPENED, nil]
- options[:review_assignee_id]=nil
-
- elsif rule_param=='unplanned_reviews'
- options[:review_statuses]=[Review::STATUS_OPEN, Review::STATUS_REOPENED, nil]
- options[:planned]=false
-
- elsif rule_param=='unreviewed_violations'
- options[:review_statuses]=[nil]
-
- elsif Sonar::RulePriority.id(rule_param)
- options[:severity]=rule_param
-
- else
- options[:rule_id]=rule_param
- end
- end
-
-
- if @period && @period != 0
- date=@snapshot.period_datetime(@period)
- if date
- options[:created_after]=date.advance(:minutes => 1)
- end
- end
-
- violations = RuleFailure.search(options)
- violations.each do |violation|
- # sorted by severity => from blocker to info
- if @lines && violation.line && violation.line>0 && violation.line<=@lines.size
- @lines[violation.line-1].add_violation(violation)
- else
- @global_violations<<violation
- end
- end
-
- if !@expanded && @lines
- filter_lines { |line| line.violations? }
- end
-
- @review_screens_by_vid=nil
- if current_user && has_role?(:user, @resource)
- @review_screens_by_vid = RuleFailure.available_java_screens_for_violations(violations, @resource, current_user)
- end
- end
-
def render_issues
load_sources()
@display_issues = true
filter_lines { |line| line.issues? }
end
- # TODO
- #@review_screens_by_vid=nil
- #if current_user && has_role?(:user, @resource)
- # @review_screens_by_vid = RuleFailure.available_java_screens_for_violations(violations, @resource, current_user)
- #end
end
def render_source
+++ /dev/null
-#
-# Sonar, entreprise quality control tool.
-# Copyright (C) 2008-2013 SonarSource
-# mailto:contact AT sonarsource DOT com
-#
-# SonarQube is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 3 of the License, or (at your option) any later version.
-#
-# SonarQube is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-
-class ReviewsController < ApplicationController
-
- verify :method => :post,
- :only => [:violation_assign, :violation_flag_as_false_positive, :violation_change_severity,
- :violation_save_comment, :violation_delete_comment, :violation_change_status,
- :violation_link_to_action_plan, :violation_unlink_from_action_plan, :execute],
- :redirect_to => {:action => :error_not_post}
- helper SourceHelper, UsersHelper
-
- def index
- init_params()
- search_reviews()
- end
-
- # Used for the "OLD" permalink "http://localhost:9000/reviews/view/1"
- # => Since Sonar 2.13, permalinks are "http://localhost:9000/project_reviews/view/1" and are displayed in the context of the project
- def view
- redirect_to :controller => 'project_reviews', :action => 'view', :id => params[:id]
- end
-
- # GET
- def screen
- @violation = RuleFailure.find params[:id]
- bad_request('Unknown violation') unless @violation
-
- command = params[:command]
- bad_request('Missing command') if command.blank?
-
- @screen = java_facade.getReviewScreen(command)
- bad_request('No associated screen') unless @screen
-
- render :partial => "reviews/screens/#{@screen.getKey()}"
- end
-
- # POST
- def execute
- bad_request('Missing violation id') unless params[:id]
- violation = RuleFailure.find(:first, :include => [:rule, {:snapshot => :project}, {:review => :action_plans}], :conditions => {:id => params[:id].to_i})
- bad_request('Unknown violation') unless violation
- access_denied unless has_rights_to_modify? violation.snapshot
-
- bad_request('Missing command') if params[:command].blank?
-
- sanitize_violation(violation)
- unless violation.review
- violation.create_review!(:user_id => current_user.id)
- end
-
- # TODO remove parameters 'id' and 'command' from params
- error_message = nil
- begin
- RuleFailure.execute_command(params[:command], violation, current_user, params)
- rescue Exception => e
- error_message=Api::Utils.exception_message(e, :backtrace => false)
- end
-
- # reload data required for display
- violation.reload
- screens = violation.available_java_screens(current_user)
-
- render :partial => 'resource/violation', :locals => {:violation => violation, :review_screens => screens, :error_message => error_message}
- end
-
- #
- #
- # ACTIONS FROM VIOLATIONS TAB OF RESOURCE VIEWER
- #
- #
-
- # GET
- def display_violation
- violation = RuleFailure.find(params[:id])
- screens = violation.available_java_screens(current_user)
- render :partial => "resource/violation", :locals => {:violation => violation, :review_screens => screens}
- end
-
- # GET
- def violation_assign_form
- @violation = RuleFailure.find(params[:id], :include => 'review')
- render :partial => "violation_assign_form"
- end
-
- # POST
- def violation_assign
- violation = RuleFailure.find(params[:id], :include => 'snapshot')
- unless has_rights_to_modify?(violation.snapshot)
- render :text => "<b>Cannot edit the review</b> : access denied."
- return
- end
- sanitize_violation(violation)
-
- violation.build_review(:user_id => current_user.id)
- assignee=nil
- if params[:me]=='true'
- assignee = current_user
-
- elsif params[:assignee_login].present?
- assignee = findUserByLogin(params[:assignee_login])
- end
- violation.review.reassign(current_user, assignee, params)
- violation.save
-
- display_violation
- end
-
- # GET
- def violation_change_severity_form
- render :partial => 'reviews/violation_change_severity_form'
- end
-
- # POST
- def violation_change_severity
- violation=RuleFailure.find(params[:id], :include => 'snapshot')
- unless has_rights_to_modify?(violation.snapshot)
- render :text => "<b>Cannot change severity</b> : access denied."
- return
- end
- sanitize_violation(violation)
-
- if violation.review.nil?
- violation.build_review(:user_id => current_user.id)
- end
- violation.review.set_severity(params[:severity], current_user, params)
- # refresh the violation that has been modified
- violation.reload
-
- display_violation
- end
-
- # GET
- def violation_false_positive_form
- @violation = RuleFailure.find(params[:id])
- render :partial => 'reviews/violation_false_positive_form'
- end
-
- # POST
- def violation_flag_as_false_positive
- violation=RuleFailure.find(params[:id], :include => 'snapshot')
- unless has_rights_to_modify?(violation.snapshot)
- render :text => "<b>Cannot switch on the violation</b> : access denied."
- return
- end
- sanitize_violation(violation)
-
- if violation.review.nil?
- violation.build_review(:user_id => current_user.id)
- end
- violation.review.set_false_positive(params[:false_positive]=='true', current_user, params)
-
- # refresh the violation that has been modified when setting the review to false positive
- violation.reload
-
- display_violation
- end
-
-
- # GET
- def violation_comment_form
- @violation = RuleFailure.find params[:id]
- if !params[:comment_id].blank? && @violation.review
- @comment = @violation.review.comments.find(params[:comment_id])
- end
- render :partial => 'reviews/violation_comment_form'
- end
-
- # POST
- def violation_save_comment
- violation = RuleFailure.find(params[:id], :include => 'snapshot')
- unless has_rights_to_modify?(violation.snapshot)
- render :text => "<b>Cannot create the comment</b> : access denied."
- return
- end
- sanitize_violation(violation)
-
- unless violation.review
- assignee = findUserByLogin(params[:assignee_login]) unless params[:assignee_login].blank?
- violation.create_review!(
- :assignee => assignee,
- :user => current_user)
- end
-
- unless params[:text].blank?
- if params[:comment_id]
- violation.review.edit_comment(current_user, params[:comment_id].to_i, params[:text])
- else
- violation.review.create_comment(:user => current_user, :text => params[:text])
- end
- end
-
- display_violation
- end
-
- # POST
- def violation_delete_comment
- violation = RuleFailure.find(params[:id], :include => 'snapshot')
- unless has_rights_to_modify?(violation.snapshot)
- render :text => "<b>Cannot delete the comment</b> : access denied."
- return
- end
- sanitize_violation(violation)
- if violation.review
- violation.review.delete_comment(current_user, params[:comment_id].to_i)
- end
- display_violation
- end
-
- # GET
- def violation_change_status_form
- @violation = RuleFailure.find(params[:id], :include => 'review')
- render :partial => 'reviews/violation_change_status_form'
- end
-
- # POST
- def violation_change_status
- violation = RuleFailure.find(params[:id], :include => 'snapshot')
- unless has_rights_to_modify?(violation.snapshot)
- render :text => "<b>Cannot delete the comment</b> : access denied."
- return
- end
- sanitize_violation(violation)
-
- if violation.review.nil?
- violation.build_review(:user_id => current_user.id)
- end
-
- if violation.review.resolved?
- violation.review.reopen(current_user, params)
- else
- # for the moment, if a review is not open, it can only be "RESOLVED"
- violation.review.resolve(current_user, params)
- end
-
- display_violation
- end
-
- # GET
- def violation_action_plan_form
- @violation = RuleFailure.find(params[:id], :include => ['review', 'snapshot'])
- @action_plans = ActionPlan.open_by_project_id(@violation.snapshot.root_project_id)
- render :partial => 'reviews/violation_action_plan_form'
- end
-
- # POST
- def violation_link_to_action_plan
- violation = RuleFailure.find(params[:id], :include => 'snapshot')
- unless has_rights_to_modify?(violation.snapshot)
- render :text => "<b>Cannot link to action plan</b> : access denied."
- return
- end
- sanitize_violation(violation)
-
- if violation.review.nil?
- violation.build_review(:user_id => current_user.id)
- end
- action_plan = params[:action_plan_id].to_i==-1 ? nil : ActionPlan.find(params[:action_plan_id])
- violation.review.link_to_action_plan(action_plan, current_user, params)
-
- display_violation
- end
-
- # POST
- def violation_unlink_from_action_plan
- violation = RuleFailure.find(params[:id], :include => 'snapshot')
- unless has_rights_to_modify?(violation.snapshot)
- render :text => "<b>Cannot link to action plan</b> : access denied."
- return
- end
- violation.review.link_to_action_plan(nil, current_user, params)
-
- display_violation
- end
-
-
- ## -------------- PRIVATE -------------- ##
- private
-
- def findUserByLogin(login)
- User.find(:first, :conditions => ["login = ?", login])
- end
-
- def init_params
- default_user = (current_user ? current_user.login : '')
- @assignee_login = params[:assignee_login] || default_user
- @author_login = params[:author_login] || ''
- @severities = filter_any(params[:severities]) || ['']
- @statuses = filter_any(params[:statuses]) || [Review::STATUS_OPEN, Review::STATUS_REOPENED]
- @projects = filter_any(params[:projects]) || ['']
- @false_positives = params[:false_positives] || 'without'
- @id = params[:review_id] || ''
- @sort = params[:sort]
- @asc = params[:asc] == "true"
- @from = Time.parse(params[:from]) if params[:from]
- @to = Time.parse(params[:to]) if params[:to]
- end
-
- def filter_any(array)
- if array && array.size>1 && array.include?("")
- array=[""]
- end
- array
- end
-
- def search_reviews
- options = {}
- unless @statuses == ['']
- options['statuses']=@statuses.join(',')
- end
- unless @projects == ['']
- options['projects']=@projects.join(',')
- end
- unless @severities == ['']
- options['severities']=@severities.join(',')
- end
- if @author_login
- options['authors']=@author_login
- end
- if @assignee_login
- options['assignees']=@assignee_login unless @assignee_login.blank?
- end
- if @false_positives
- options['false_positives']=@false_positives
- end
- if @from
- options['from']=@from
- end
- if @to
- options['to']=@to
- end
- unless @id == ''
- if Api::Utils.is_integer? @id
- options['ids'] = @id
- else
- options['ids'] = '-1'
- end
- end
- options['sort'] = @sort unless @sort.blank?
- options['asc'] = @asc
- options['limit']=500
-
- found_reviews = Review.search(options)
- @reviews = select_authorized(:user, found_reviews, :project)
- if found_reviews.size != @reviews.size
- @security_exclusions = true
- end
- end
-
- def has_rights_to_modify?(object)
- current_user && has_role?(:user, object)
- end
-
- def error_not_post
- render :text => "Create actions must use POST method."
- end
-
- def sanitize_violation(violation)
- # the field RULE_FAILURES.PERMANENT_ID is not set when upgrading to version 2.8.
- # It must be manually set when using a violation created before v2.8.
- if violation.permanent_id.nil?
- violation.permanent_id=violation.id
- violation.save
- end
- end
-end
html
end
- #
- # Used on the reviews listing page (http://localhost:9000/project_reviews)
- # Prints a label for the given parameter that is used to filter the review list.
- # The label has:
- # * a name (=the param name) with a tooltip (=the param value)
- # * a 'x' action to remove this filter
- #
- # === Optional parameters
- # * title: to overwrite the tooltip of the parameter
- #
- def review_filter_tag(param_name, params, options={})
- html = "<span class=\"review-filter\" title=\""
- html += options[:title] ? options[:title] : params[param_name]
- html += "\">"
- html += message('reviews.filtered_by.' + param_name)
- html += "<a href=\""
- html += url_for params.reject { |key, value| key==param_name }
- html += "\" title=\""
- html += message('reviews.remove_this_filter')
- html += "\">X</a></span>"
- end
-
-
def select2_tag(name, ws_url, options={})
width=options[:width]||'250px'
html_id=options[:html_id]||name
+++ /dev/null
- #
- # Sonar, entreprise quality control tool.
- # Copyright (C) 2008-2013 SonarSource
- # mailto:contact AT sonarsource DOT com
- #
- # SonarQube is free software; you can redistribute it and/or
- # modify it under the terms of the GNU Lesser General Public
- # License as published by the Free Software Foundation; either
- # version 3 of the License, or (at your option) any later version.
- #
- # SonarQube is distributed in the hope that it will be useful,
- # but WITHOUT ANY WARRANTY; without even the implied warranty of
- # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- # Lesser General Public License for more details.
- #
- # You should have received a copy of the GNU Lesser General Public License
- # along with this program; if not, write to the Free Software Foundation,
- # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- #
-module DrilldownHelper
-
-end
\ No newline at end of file
+++ /dev/null
-#
-# Sonar, entreprise quality control tool.
-# Copyright (C) 2008-2013 SonarSource
-# mailto:contact AT sonarsource DOT com
-#
-# SonarQube is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 3 of the License, or (at your option) any later version.
-#
-# SonarQube is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-module ReviewsHelper
-
- def projects_for_select
- projects=Project.find(:all, :select => 'id,name,long_name,scope,qualifier,root_id', :conditions => ['enabled=? AND scope=? AND qualifier IN (?)', true, 'PRJ', ['TRK', 'VW', 'SVW']], :order => 'name ASC')
- select_authorized(:user, projects)
- end
-
-end
@id=id
end
- def add_violation(violation)
- @violations||=[]
- @violations<<violation
- @visible=true
- end
-
def add_issue(issue)
@issues||=[]
@issues<<issue
@visible=true
end
- def violations?
- @violations && @violations.size>0
- end
-
def issues?
@issues && @issues.size>0
end
- def violation_severity
- if @violations && @violations.size>0
- @violations[0].failure_level
- else
- nil
- end
- end
-
def issue_severity
if @issues && @issues.size>0
@issues[0].severity
+++ /dev/null
-#
-# Sonar, entreprise quality control tool.
-# Copyright (C) 2008-2013 SonarSource
-# mailto:contact AT sonarsource DOT com
-#
-# SonarQube is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 3 of the License, or (at your option) any later version.
-#
-# SonarQube is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-
-class ActionPlan < ActiveRecord::Base
- belongs_to :project
- has_and_belongs_to_many :reviews
-
- validates_length_of :name, :within => 1..200
- validates_length_of :description, :maximum => 1000, :allow_blank => true, :allow_nil => true
- validates_presence_of :user_login, :message => "can't be empty"
- validates_presence_of :status, :message => "can't be empty"
- validates_presence_of :project, :message => "can't be empty"
- validate :unique_name_on_same_project
-
- STATUS_OPEN = 'OPEN'
- STATUS_CLOSED = 'CLOSED'
-
- def self.open_by_project_id(project_id)
- ActionPlan.find :all, :conditions => ['status=? AND project_id=?', STATUS_OPEN, project_id], :order => :name
- end
-
- def self.find_by_key(key)
- ActionPlan.first :conditions => ['kee=?', key]
- end
-
- def key
- kee
- end
-
- def user
- @user ||=
- begin
- user_login ? User.find(:first, :conditions => ['login=?', user_login]) : nil
- end
- end
-
- def closed?
- status == STATUS_CLOSED
- end
-
- def open?
- status == STATUS_OPEN
- end
-
- def progress
- total_reviews = reviews.size
- open_reviews = reviews.select { |r| r.open? || r.reopened? }.size
- {:total => total_reviews, :open => open_reviews, :resolved => total_reviews-open_reviews}
- end
-
- def has_open_reviews?
- open_reviews.size > 0
- end
-
- def open_reviews
- reviews.select { |r| r.open? || r.reopened? }
- end
-
- def over_due?
- deadline ? status==STATUS_OPEN && deadline.past? : false
- end
-
- # since 3.6
- def self.to_hash(java_action_plan)
- hash = {:key => java_action_plan.key(), :name => java_action_plan.name(), :status => java_action_plan.status()}
- hash[:desc] = java_action_plan.description() if java_action_plan.description() && !java_action_plan.description().blank?
- hash[:userLogin] = java_action_plan.userLogin() if java_action_plan.userLogin()
- hash[:deadLine] = Api::Utils.format_datetime(java_action_plan.deadLine()) if java_action_plan.deadLine()
- hash[:createdAt] = Api::Utils.format_datetime(java_action_plan.createdAt()) if java_action_plan.createdAt()
- hash[:updatedAt] = Api::Utils.format_datetime(java_action_plan.updatedAt()) if java_action_plan.updatedAt()
- hash
- end
-
- private
-
- def unique_name_on_same_project
- action_plan = ActionPlan.find(:first, :conditions => ['project_id=? AND name=?', project_id, name])
- if action_plan && ((id && action_plan.id!=id) || !id)
- errors.add(:base, Api::Utils.message('action_plans.same_name_in_same_project'))
- end
- end
-
-end
+++ /dev/null
-#
-# Sonar, entreprise quality control tool.
-# Copyright (C) 2008-2013 SonarSource
-# mailto:contact AT sonarsource DOT com
-#
-# SonarQube is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 3 of the License, or (at your option) any later version.
-#
-# SonarQube is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-class Review < ActiveRecord::Base
- belongs_to :user
- belongs_to :assignee, :class_name => "User", :foreign_key => "assignee_id"
- belongs_to :resource, :class_name => "Project", :foreign_key => "resource_id"
- belongs_to :project, :class_name => "Project", :foreign_key => "project_id"
- belongs_to :rule
- has_many :review_comments, :order => "created_at", :dependent => :destroy
- alias_attribute :comments, :review_comments
- has_and_belongs_to_many :action_plans
-
- validates_presence_of :status, :message => "can't be empty"
- validates_inclusion_of :severity, :in => Severity::KEYS
-
- before_save :assign_project
-
- STATUS_OPEN = 'OPEN'
- STATUS_RESOLVED = 'RESOLVED'
- STATUS_REOPENED = 'REOPENED'
- STATUS_CLOSED = 'CLOSED'
- # "IDLE" is a non-persisted status of an non-existing review = when a violation does have a review yet
- # It is currently used by rule_failure.rb (#to_java_workflow_review) to pass a list of reviews to the
- # review workflow, even for violations which don't have yet a review.
- STATUS_IDLE = 'IDLE'
-
- RESOLUTION_FALSE_POSITIVE = 'FALSE-POSITIVE'
- RESOLUTION_FIXED = 'FIXED'
-
- def on_project?
- resource_id==project_id
- end
-
- def rule
- @rule ||=
- begin
- rule_failure ? rule_failure.rule : nil
- end
- end
-
- def violation
- rule_failure
- end
-
- def rule_failure
- @rule_failure ||=
- begin
- # We need to manually run this DB request as the real relation Reviews-RuleFailures is 1:n but we want only 1 violation
- # (more than 1 violation can have the same "permanent_id" when several analyses are run in a small time frame)
- RuleFailure.find(:first, :conditions => {:permanent_id => rule_failure_permanent_id}, :order => 'id desc')
- end
- end
-
- def clean_violation_cache
- @rule_failure=nil
- end
-
- #
- #
- # REVIEW CORE METHODS
- #
- #
-
- # params of 'comment_values' are mandatory:
- # - :user
- # - :text
- def create_comment(comment_values={})
- comment = comments.create!(comment_values)
- touch
- notification_manager.notifyChanged(id.to_i, comment.user.login.to_java, to_java_map, to_java_map("comment" => comment.text))
- end
-
- def edit_comment(current_user, comment_id, comment_text)
- comment=comments.find(comment_id)
- if comment
- old_comment_text=comment.text
- comment.text=comment_text
- comment.save!
- touch
- notification_manager.notifyChanged(id.to_i, current_user.login.to_java, to_java_map("comment" => old_comment_text), to_java_map("comment" => comment.text))
- end
- end
-
- # TODO Godin: seems that this method not used anymore
- def edit_last_comment(current_user, comment_text)
- comment=comments.last
- old_comment_text=comment.text
- comment.text=comment_text
- comment.save!
- touch
- notification_manager.notifyChanged(id.to_i, current_user.login.to_java, to_java_map("comment" => old_comment_text), to_java_map("comment" => comment.text))
- end
-
- def delete_comment(current_user, comment_id)
- comment=comments.find(comment_id)
- comments.pop
- if comment
- old_comment_text=comment.text
- comment.delete
- touch
- notification_manager.notifyChanged(id.to_i, current_user.login.to_java, to_java_map("comment" => old_comment_text), to_java_map)
- end
- end
-
- def notification_manager
- Java::OrgSonarServerUi::JRubyFacade.getInstance().getReviewsNotificationManager()
- end
-
- def to_java_map(options = {})
- java.util.HashMap.new(
- {
- "project" => project.long_name.to_java,
- "projectId" => project.id.to_s.to_java,
- "resource" => resource.long_name.to_java,
- "title" => title.to_java,
- "creator" => user == nil ? nil : user.login.to_java,
- "assignee" => assignee == nil ? nil : assignee.login.to_java,
- "status" => status.to_java,
- "resolution" => resolution.to_java,
- "severity" => severity.to_java
- }.merge(options))
- end
-
- def reassign(current_user, assignee, options={})
- if options[:text].present?
- comments.create!(:user => current_user, :text => options[:text])
- end
- old = self.to_java_map
- self.assignee = assignee
- self.save!
- notification_manager.notifyChanged(id.to_i, current_user.login.to_java, old, to_java_map)
- end
-
- def reopen(current_user, options={})
- old = self.to_java_map
- if options[:text].present?
- comments.create!(:user => current_user, :text => options[:text])
- end
- self.status = STATUS_REOPENED
- self.resolution = nil
- self.save!
- notification_manager.notifyChanged(id.to_i, current_user.login.to_java, old, to_java_map)
- end
-
- def resolve(current_user, options={})
- old = self.to_java_map
- if options[:text].present?
- comments.create!(:user => current_user, :text => options[:text])
- end
- self.status = STATUS_RESOLVED
- self.resolution = RESOLUTION_FIXED
- self.save!
- notification_manager.notifyChanged(id.to_i, current_user.login.to_java, old, to_java_map)
- end
-
- # Parameters:
- # - :text
- def set_false_positive(is_false_positive, user, options={})
- if violation.nil?
- bad_request('This review does not relate to a violation')
- end
- violation.switched_off=is_false_positive
- violation.save!
- if options[:text].present?
- comments.create!(:user => user, :text => options[:text])
- end
- old = self.to_java_map
- self.assignee = nil
- self.status = is_false_positive ? STATUS_RESOLVED : STATUS_REOPENED
- self.resolution = is_false_positive ? RESOLUTION_FALSE_POSITIVE : nil
- self.save!
- notification_manager.notifyChanged(id.to_i, user.login.to_java, old, to_java_map("comment" => options[:text]))
- end
-
- def false_positive
- resolution == RESOLUTION_FALSE_POSITIVE
- end
-
- def can_change_false_positive_flag?
- (status == STATUS_RESOLVED && resolution == RESOLUTION_FALSE_POSITIVE) || status == STATUS_OPEN || status == STATUS_REOPENED
- end
-
- def set_severity(new_severity, user, options={})
- if options[:text].present?
- comments.create!(:user => user, :text => options[:text])
- end
- old = self.to_java_map
- self.severity=new_severity
- self.manual_severity=(new_severity!=violation.severity)
- self.save!
- notification_manager.notifyChanged(id.to_i, user.login.to_java, old, to_java_map("comment" => options[:text]))
- end
-
- def link_to_action_plan(action_plan, user, options={})
- if options[:text].present?
- comments.create!(:user => user, :text => options[:text])
- end
- old = self.to_java_map
- self.action_plans.clear
- if action_plan
- self.action_plans << action_plan
- end
- self.save!
- notification_manager.notifyChanged(id.to_i, user.login.to_java, old, to_java_map("action_plans" => action_plan ? action_plan.name : ''))
- end
-
- def resolved?
- status == STATUS_RESOLVED
- end
-
- def closed?
- status == STATUS_CLOSED
- end
-
- def reopened?
- status == STATUS_REOPENED
- end
-
- def open?
- status == STATUS_OPEN
- end
-
- def active?
- status == STATUS_OPEN || status == STATUS_REOPENED
- end
-
- def linked_to? (action_plan)
- action_plans.include? action_plan
- end
-
- def planned?
- action_plans.size!=0
- end
-
- def assigned?
- assignee_id != nil
- end
-
- # used as long as we currently allow to link a review to only 1 action plan.
- def action_plan
- action_plans[0]
- end
-
- #
- #
- # SEARCH METHODS
- #
- #
-
- def self.search(options={})
- conditions=[]
- values={}
- no_need_for_db_request = false
-
- if options['id'].present?
- conditions << 'id=:id'
- values[:id]=options['id'].to_i
- elsif options['ids'].present?
- ids=options['ids'].split(',')
- conditions << 'id in (:ids)'
- values[:ids]=ids.map { |id| id.to_i }
- else
-
- # --- 'review_type' is deprecated since 2.9 ---
- # Following code just for backward compatibility
- review_type = options['review_type']
- if review_type
- if review_type == RESOLUTION_FALSE_POSITIVE
- conditions << "resolution='#{RESOLUTION_FALSE_POSITIVE}'"
- else
- conditions << "(resolution<>'#{RESOLUTION_FALSE_POSITIVE}' OR resolution IS NULL)"
- end
- end
- # --- End of code for backward compatibility code ---
-
- # --- For UI
- false_positives = options['false_positives']
- if false_positives == "only"
- conditions << "resolution='#{RESOLUTION_FALSE_POSITIVE}'"
- elsif false_positives == "without"
- conditions << "(resolution<>'#{RESOLUTION_FALSE_POSITIVE}' OR resolution IS NULL)"
- end
- # --- End
-
- # --- For web-service
- resolutions = options['resolutions'].split(',') if options['resolutions']
- if resolutions && resolutions.size>0 && !resolutions[0].blank?
- conditions << 'resolution in (:resolutions)'
- values[:resolutions] = resolutions
- end
- # --- End
-
-
- projects=options['projects'].split(',') if options['projects']
- if projects && projects.size>0 && !projects[0].blank?
- conditions << 'project_id in (:projects)'
- projectIds = []
- projects.each do |project|
- foundProject = Project.by_key(project)
- projectIds << foundProject.id if foundProject
- end
- values[:projects]=projectIds
- end
-
- resources=options['resources'].split(',') if options['resources']
- if resources && resources.size>0 && !resources[0].blank?
- conditions << 'resource_id in (:resources)'
- resourceIds = []
- resources.each do |resource|
- foundResource = Project.by_key(resource)
- resourceIds << foundResource.id if foundResource
- end
- values[:resources]=resourceIds
- end
-
- statuses=options['statuses'].split(',') if options['statuses']
- if statuses && statuses.size>0 && !statuses[0].blank?
- conditions << 'status in (:statuses)'
- values[:statuses]=statuses
- end
-
- severities=options['severities'].split(',') if options['severities']
- if severities && severities.size>0 && !severities[0].blank?
- conditions << 'severity in (:severities)'
- values[:severities]=severities
- end
-
- authors=options['authors'].split(',') if options['authors']
- if authors && authors.size>0 && !authors[0].blank?
- conditions << 'user_id in (:authors)'
- values[:authors]=User.logins_to_ids(authors)
- end
-
- assignees=options['assignees'].split(',') if options['assignees']
- if assignees
- if assignees.size == 0
- # Unassigned reviews
- conditions << 'assignee_id IS NULL'
- else
- # Assigned reviews
- conditions << 'assignee_id in (:assignees)'
- values[:assignees]=User.logins_to_ids(assignees)
- end
- end
-
- action_plan_id = options['action_plan_id']
- if action_plan_id
- action_plan = ActionPlan.find action_plan_id.to_i, :include => 'reviews'
- if action_plan && action_plan.reviews.size>0
- conditions << 'id in (:ids)'
- values[:ids]=action_plan.reviews.map { |r| r.id }
- else
- # no action plan or action plan is empty => no need to look into the database
- no_need_for_db_request = true
- end
- elsif options['unplanned']
- conditions << 'id not in (:ids)'
- values[:ids]=find_by_sql('SELECT DISTINCT review_id as id from action_plans_reviews')
- end
-
- from=options['from']
- if from
- conditions << 'created_at >= :from'
- values[:from] = from
- end
-
- to=options['to']
- if from
- conditions << 'created_at <= :to'
- values[:to] = to
- end
- end
-
- sort_field=(options['sort'].blank? ? 'updated_at' : options['sort'])
- asc=(options['asc'] ? 'ASC' : 'DESC')
- sort_sql="reviews.#{sort_field} #{asc}"
- sort_sql += ', reviews.updated_at DESC' unless sort_field=='updated_at'
-
- found_reviews = []
- found_reviews = Review.find(:all, :include => ['review_comments', 'project', 'assignee', 'resource', 'user'], :conditions => [conditions.join(' AND '), values], :order => sort_sql, :limit => options['limit']) unless no_need_for_db_request
- found_reviews
- end
-
-
-#
-#
-# XML AND JSON UTILITY METHODS
-#
-#
-
- def self.reviews_to_xml(reviews, convert_markdown=false)
- xml = Builder::XmlMarkup.new(:indent => 0)
- xml.instruct!
- xml.reviews do
- reviews.each do |review|
- review.to_xml(xml, convert_markdown)
- end
- end
- end
-
- def to_xml(xml, convert_markdown=false)
- xml.review do
- xml.id(id.to_i)
- xml.createdAt(Api::Utils.format_datetime(created_at))
- xml.updatedAt(Api::Utils.format_datetime(updated_at))
- xml.author(user.login) if user
- xml.assignee(assignee.login) if assignee
- xml.title(title)
- xml.status(status)
- xml.resolution(resolution) if resolution
- xml.severity(severity)
- xml.resource(resource.kee) if resource
- xml.line(resource_line) if resource_line && resource_line>0
- xml.violationId(rule_failure_permanent_id) if rule_failure_permanent_id
- xml.comments do
- review_comments.each do |comment|
- xml.comment do
- xml.id(comment.id.to_i)
- xml.author(comment.user.login) if comment.user
- xml.updatedAt(Api::Utils.format_datetime(comment.updated_at))
- if convert_markdown
- xml.text(comment.html_text)
- else
- xml.text(comment.plain_text)
- end
- end
- end
- end
- end
- end
-
- def self.reviews_to_json(reviews, convert_markdown=false)
- JSON(reviews.collect { |review| review.to_json(convert_markdown) })
- end
-
- def to_json(convert_markdown=false)
- json = {}
- json['id'] = id.to_i
- json['createdAt'] = Api::Utils.format_datetime(created_at)
- json['updatedAt'] = Api::Utils.format_datetime(updated_at)
- json['author'] = user.login if user
- json['assignee'] = assignee.login if assignee
- json['title'] = title if title
- json['status'] = status
- json['resolution'] = resolution if resolution
- json['severity'] = severity
- json['resource'] = resource.kee if resource
- json['line'] = resource_line if resource_line && resource_line>0
- json['violationId'] = rule_failure_permanent_id if rule_failure_permanent_id
- comments = []
- review_comments.each do |comment|
- comment_map = {
- 'id' => comment.id.to_i,
- 'updatedAt' => Api::Utils.format_datetime(comment.updated_at),
- 'text' => convert_markdown ? comment.html_text : comment.plain_text
- }
- comment_map['author'] = comment.user.login if comment.user
- comments << comment_map
- end
- json['comments'] = comments
- json
- end
-
-#
-#
-# PRIVATE METHODS
-#
-#
- private
-
- def assign_project
- if self.project.nil? && self.resource
- self.project=self.resource.root_project
- end
- end
-
-
-end
+++ /dev/null
-#
-# Sonar, entreprise quality control tool.
-# Copyright (C) 2008-2013 SonarSource
-# mailto:contact AT sonarsource DOT com
-#
-# SonarQube is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 3 of the License, or (at your option) any later version.
-#
-# SonarQube is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# along with this program; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-class ReviewComment < ActiveRecord::Base
- belongs_to :user
- belongs_to :review
- validates_presence_of :user => "can't be empty"
- validate :comment_should_not_be_blank
-
- alias_attribute :text, :review_text
-
- def html_text
- Api::Utils.markdown_to_html(review_text)
- end
-
- def plain_text
- Api::Utils.convert_string_to_unix_newlines(review_text)
- end
-
- def excerpt
- text = plain_text.gsub("\n", " ")
- if text.size > 101
- text[0..100] + " ..."
- else
- text
- end
- end
-
- private
-
- def comment_should_not_be_blank
- errors.add("Comment", " cannot be blank") if review_text.blank?
- end
-
-end
validates_presence_of :plugin_rule_key, :if => 'name.present?'
has_many :rules_parameters, :inverse_of => :rule
- has_many :rule_failures, :inverse_of => :rule
has_many :active_rules, :inverse_of => :rule
belongs_to :parent, :class_name => 'Rule', :foreign_key => 'parent_id'
has_one :rule_note, :inverse_of => :rule
rule
end
- def create_violation!(resource, options={})
- line = options['line']
- checksum = nil
- level = Sonar::RulePriority.id(options['severity']||Severity::MAJOR)
- RuleFailure.create!(
- :snapshot => resource.last_snapshot,
- :rule => self,
- :failure_level => level,
- :message => options['message'],
- :cost => (options['cost'] ? options['cost'].to_f : nil),
- :switched_off => false,
- :line => line,
- :checksum => checksum)
- end
-
def self.to_hash(java_rule)
l10n_name = Internal.rules.ruleL10nName(java_rule)
l10n_desc = Internal.rules.ruleL10nDescription(java_rule)
+++ /dev/null
-#
-# Sonar, entreprise quality control tool.
-# Copyright (C) 2008-2013 SonarSource
-# mailto:contact AT sonarsource DOT com
-#
-# SonarQube is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 3 of the License, or (at your option) any later version.
-#
-# SonarQube is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public License
-# License along with {library}; if not, write to the Free Software
-# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
-#
-
-class RuleFailure < ActiveRecord::Base
-
- belongs_to :rule
- belongs_to :snapshot
- has_one :review, :primary_key => 'permanent_id', :foreign_key => 'rule_failure_permanent_id', :order => 'created_at'
- after_save :update_permanent_id
- validates_presence_of :rule, :snapshot
-
- # first line of message
- def title
- @title||=
- begin
- if message.blank?
- rule.name
- else
- parts=Api::Utils.split_newlines(message)
- parts.size==0 ? rule.name : parts[0]
- end
- end
- end
-
- def plain_message
- @plain_message ||=
- begin
- Api::Utils.convert_string_to_unix_newlines(message)
- end
- end
-
- def html_message
- @html_message ||=
- begin
- message ? Api::Utils.split_newlines(ERB::Util.html_escape(message)).join('<br/>') : ''
- end
- end
-
- def severity
- Sonar::RulePriority.to_s(failure_level)
- end
-
- def resource
- snapshot.resource
- end
-
- def to_json(include_review=false, convert_markdown=false)
- json = {}
- json['id'] = id
- json['message'] = plain_message if plain_message
- json['line'] = line if line && line>=1
- json['priority'] = severity
- json['switchedOff']=true if switched_off?
- if created_at
- json['createdAt'] = Api::Utils.format_datetime(created_at)
- end
- json['rule'] = {
- :key => rule.key,
- :name => rule.name
- }
- json['resource'] = {
- :key => resource.key,
- :name => resource.name,
- :scope => resource.scope,
- :qualifier => resource.qualifier,
- :language => resource.language
- }
- json['review'] = review.to_json(convert_markdown) if include_review && review
- json
- end
-
- def to_xml(xml=Builder::XmlMarkup.new(:indent => 0), include_review=false, convert_markdown=false)
- xml.violation do
- xml.id(id)
- xml.message(plain_message) if plain_message
- xml.line(line) if line && line>=1
- xml.priority(severity)
- xml.switchedOff(true) if switched_off?
- if created_at
- xml.createdAt(Api::Utils.format_datetime(created_at))
- end
- xml.rule do
- xml.key(rule.key)
- xml.name(rule.name)
- end
- xml.resource do
- xml.key(resource.key)
- xml.name(resource.name)
- xml.scope(resource.scope)
- xml.qualifier(resource.qualifier)
- xml.language(resource.language)
- end
- review.to_xml(xml, convert_markdown) if include_review && review
- end
- end
-
- def build_review(options={})
- if self.review.nil?
- self.review=Review.new(
- {
- :status => Review::STATUS_OPEN,
- :severity => severity,
- :resource_line => line,
- :resource => resource,
- :title => title,
- :rule => rule,
- :manual_violation => false,
- :manual_severity => false
- }.merge(options))
- end
- end
-
- def create_review!(options={})
- build_review(options)
- self.review.save!
- end
-
- # Options :
- # - snapshot_id (integer)
- # - resource_id (integer)
- # - ancestor_resource_id (integer)
- # - ancestor_snapshot (Snapshot)
- # - created_after (datetime)
- # - switched_off (boolean)
- # - review_statuses (array of strings, can include nil)
- # - review_assignee_id (integer, nil means no assignee)
- # - severity
- # - rule_id
- # - planned (boolean)
- #
- # WARNING: association 'snapshot' is not loaded
- #
- def self.search(options={})
- conditions=[]
- values=[]
- includes=[:rule, {:review => :action_plans}]
-
- if options.has_key? :snapshot_id
- conditions << 'rule_failures.snapshot_id = ?'
- values << options[:snapshot_id].to_i
- end
-
- if options.has_key? :resource_id
- conditions << 'rule_failures.snapshot_id in (select id from snapshots where islast=? and status=? and project_id=?)'
- values << true
- values << 'P'
- values << options[:resource_id].to_i
- end
-
- if options.has_key? :ancestor_resource_id
- ancestor = Snapshot.find(:first, :select => 'id,path', :conditions => {:islast => true, :status => 'P', :project_id => options[:ancestor_resource_id].to_i})
- options[:ancestor_snapshot]=ancestor
- end
-
- if options.has_key? :ancestor_snapshot
- ancestor_snapshot=options[:ancestor_snapshot]
- if ancestor_snapshot
- conditions << 'rule_failures.snapshot_id in (select id from snapshots where islast=? and status=? and (id=? or (root_snapshot_id=? and path like ?)))'
- values << true
- values << 'P'
- values << ancestor_snapshot.id
- values << ancestor_snapshot.id
- values << "#{ancestor_snapshot.path}#{ancestor_snapshot.id}.%"
- else
- return []
- end
- end
-
- if options.has_key? :rule_id
- conditions << 'rule_failures.rule_id=?'
- values << options[:rule_id].to_i
- end
-
- if options.has_key? :created_after
- conditions << 'rule_failures.created_at>?'
- values << options[:created_after]
- end
-
- if options[:switched_off]
- conditions << 'rule_failures.switched_off=?'
- values << true
- else
- conditions << '(rule_failures.switched_off is null or rule_failures.switched_off = ?)'
- values << false
- end
-
- if options.has_key? :review_statuses
- statuses = options[:review_statuses]
- unless statuses.empty?
- if statuses.include? nil
- if statuses.size==1
- # only nil : unreviewed violations
- conditions << 'not exists(select id from reviews where rule_failure_permanent_id=rule_failures.permanent_id)'
- else
- conditions << '(reviews.status in (?) or not exists(select id from reviews where rule_failure_permanent_id=rule_failures.permanent_id))'
- values << options[:review_statuses].compact
- end
- else
- conditions << 'reviews.status in (?)'
- values << options[:review_statuses]
- end
- end
- end
-
- if options.has_key? :review_assignee_id
- review_assignee_id = options[:review_assignee_id]
- if review_assignee_id
- conditions << 'reviews.assignee_id=?'
- values << review_assignee_id.to_i
- else
- conditions << '(reviews.assignee_id is null or not exists(select id from reviews where rule_failure_permanent_id=rule_failures.permanent_id))'
- end
- end
-
- if options.has_key? :severity
- conditions << 'failure_level=?'
- values << Sonar::RulePriority.id(options[:severity])
- end
-
- result = find(:all, :include => includes, :conditions => [conditions.join(' and ')] + values, :order => 'rule_failures.failure_level DESC')
-
- if options.has_key? :planned
- # this condition can not be implemented with SQL
- if options[:planned]
- result = result.select { |violation| violation.review && violation.review.planned? }
- else
- result = result.reject { |violation| violation.review && violation.review.planned? }
- end
- end
-
- result
- end
-
-
- #
- # Constraint : all the violations are in the same project
- #
- def self.available_java_screens_for_violations(violations, resource, user)
- reviews = violations.map { |violation| to_java_workflow_review(violation) }
- context = to_java_workflow_context(resource, user)
- Java::OrgSonarServerUi::JRubyFacade.getInstance().listAvailableReviewsScreens(reviews, context)
- end
-
- def available_java_screens(user)
- if user
- review = RuleFailure.to_java_workflow_review(self)
- context = RuleFailure.to_java_workflow_context(snapshot.root_snapshot.project, user)
- Java::OrgSonarServerUi::JRubyFacade.getInstance().listAvailableReviewScreens(review, context)
- else
- []
- end
- end
-
- def self.execute_command(command_key, violation, user, parameters)
- review = to_java_workflow_review(violation)
- context = to_java_workflow_context(violation.resource, user)
- Java::OrgSonarServerUi::JRubyFacade.getInstance().executeReviewCommand(command_key, review, context, parameters)
- end
-
- def self.to_java_workflow_review(violation)
- java_review=Java::OrgSonarApiWorkflowInternal::DefaultReview.new
- java_review.setViolationId(violation.id)
- java_review.setSeverity(violation.severity.to_s)
- java_review.setRuleKey(violation.rule.plugin_rule_key)
- java_review.setRuleRepositoryKey(violation.rule.repository_key)
- java_review.setRuleName(violation.rule.name(false)) # rule name is not localized
- java_review.setSwitchedOff(violation.switched_off||false)
- java_review.setMessage(violation.message)
- java_review.setLine(violation.line)
-
- review = violation.review
- if review
- java_review.setReviewId(review.id)
- java_review.setStatus(review.status)
- java_review.setResolution(review.resolution)
- java_review.setManual(review.manual_violation)
- java_review.setPropertiesAsString(review.data)
- else
- java_review.setStatus(Review::STATUS_IDLE)
- end
- java_review
- end
-
- def self.to_java_workflow_context(resource, user)
- java_context = Java::OrgSonarApiWorkflowInternal::DefaultWorkflowContext.new
- java_context.setUserId(user.id)
- java_context.setUserLogin(user.login)
- java_context.setUserName(user.name)
- java_context.setUserEmail(user.email)
- java_context.setIsAdmin(user.has_role?(:admin))
- java_context.setProjectId(resource.root_project.id)
- java_context
- end
-
- private
- def update_permanent_id
- if self.permanent_id.nil? && self.id
- self.permanent_id = self.id
- save!
- end
- end
-
-end
has_many :events, :dependent => :destroy, :order => 'event_date DESC'
has_one :source, :class_name => 'SnapshotSource', :dependent => :destroy
- has_many :violations, :class_name => 'RuleFailure'
STATUS_UNPROCESSED = 'U'
STATUS_PROCESSED = 'P'
<tr class="<%= css -%> <%= 'selected' if selected -%>">
<td><%= image_tag "priority/#{severity}.png" %></td>
<td>
- <%= link_to message("severity.#{severity}"), {:controller => :drilldown, :action => :violations, :id => @resource.id, :severity => (selected ? nil : severity), :period => @period} %>
+ <%= link_to message("severity.#{severity}"), {:controller => :drilldown, :action => :issues, :id => @resource.id, :severity => (selected ? nil : severity), :period => @period} %>
</td>
<td style="padding-left: 10px;" align="right" nowrap>
<%= @period ? format_variation(measure, :index => @period, :style => 'light') : format_measure(measure) -%>
+++ /dev/null
-<% selected=(severity==@severity) %>
-<tr class="<%= css -%> <%= 'selected' if selected -%>">
- <td><%= image_tag "priority/#{severity}.png" %></td>
- <td>
- <%= link_to message("severity.#{severity}"), {:controller => :drilldown, :action => :issues, :id => @resource.id, :severity => (selected ? nil : severity), :period => @period} %>
- </td>
- <td style="padding-left: 10px;" align="right" nowrap>
- <%= @period ? format_variation(measure, :index => @period, :style => 'light') : format_measure(measure) -%>
- </td>
- <td align="left">
- <% value = measure_or_variation_value(measure) %>
- <%= barchart(:width => 60, :percent => (value ? (100 * value / max).to_i : 0), :color => (@period_index ? '#cc0000' : '#777')) if max>0 %>
- </td>
-</tr>
\ No newline at end of file
value_column = (@period ? "variation_value_#{@period}" : 'value')
max = 0
if @period
- blocker_issues=@snapshot.measure('new_blocker_issues')
- critical_issues=@snapshot.measure('new_critical_issues')
- major_issues=@snapshot.measure('new_major_issues')
- minor_issues=@snapshot.measure('new_minor_issues')
- info_issues=@snapshot.measure('new_info_issues')
+ blocker_issues=@snapshot.measure('new_blocker_violations')
+ critical_issues=@snapshot.measure('new_critical_violations')
+ major_issues=@snapshot.measure('new_major_violations')
+ minor_issues=@snapshot.measure('new_minor_violations')
+ info_issues=@snapshot.measure('new_info_violations')
else
- blocker_issues=@snapshot.measure('blocker_issues')
- critical_issues=@snapshot.measure('critical_issues')
- major_issues=@snapshot.measure('major_issues')
- minor_issues=@snapshot.measure('minor_issues')
- info_issues=@snapshot.measure('info_issues')
+ blocker_issues=@snapshot.measure('blocker_violations')
+ critical_issues=@snapshot.measure('critical_violations')
+ major_issues=@snapshot.measure('major_violations')
+ minor_issues=@snapshot.measure('minor_violations')
+ info_issues=@snapshot.measure('info_violations')
end
[blocker_issues, critical_issues, major_issues, minor_issues, info_issues].each do |m|
%>
<h3><%= message('issues_drilldown.col.severity') -%></h3>
<table class="spacedicon" style="border: 1px solid #ccc;">
- <%= render :partial => 'severity_issues', :locals => {:css => 'even', :severity => 'BLOCKER', :max => max, :measure => blocker_issues} %>
- <%= render :partial => 'severity_issues', :locals => {:css => 'odd', :severity => 'CRITICAL', :max => max, :measure => critical_issues} %>
- <%= render :partial => 'severity_issues', :locals => {:css => 'even', :severity => 'MAJOR', :max => max, :measure => major_issues} %>
- <%= render :partial => 'severity_issues', :locals => {:css => 'odd', :severity => 'MINOR', :max => max, :measure => minor_issues} %>
- <%= render :partial => 'severity_issues', :locals => {:css => 'even', :severity => 'INFO', :max => max, :measure => info_issues} %>
+ <%= render :partial => 'severity', :locals => {:css => 'even', :severity => 'BLOCKER', :max => max, :measure => blocker_issues} %>
+ <%= render :partial => 'severity', :locals => {:css => 'odd', :severity => 'CRITICAL', :max => max, :measure => critical_issues} %>
+ <%= render :partial => 'severity', :locals => {:css => 'even', :severity => 'MAJOR', :max => max, :measure => major_issues} %>
+ <%= render :partial => 'severity', :locals => {:css => 'odd', :severity => 'MINOR', :max => max, :measure => minor_issues} %>
+ <%= render :partial => 'severity', :locals => {:css => 'even', :severity => 'INFO', :max => max, :measure => info_issues} %>
</table>
</td>
<td align="left" style="white-space: normal;" valign="top">
+++ /dev/null
-<%= render :partial => 'header' -%>
-
-<div class="line-block">
- <div id="snapshot_title" class="page_title">
- <h4>
- <%
- profile_measure=@snapshot.measure(Metric::PROFILE)
- %>
- <% if profile_measure %>Profile <%= link_to profile_measure.data, :controller => '/rules_configuration', :action => 'index', :id => profile_measure.value.to_i %>
- <% end %>
- <% if @snapshot.project_snapshot.periods? %>
- <form method="GET" action="<%= url_for :only_path=>true, :overwrite_params => {:period => nil} -%>" style="display: inline" class="spacer-left">
- <%= dropdown_tag "period", period_select_option_tags(@snapshot, 'small'), {
- :width => '200px',
- }, {:id => 'select-comparison', :onchange => 'submit()'} -%>
- </form>
- <% end %>
- </h4>
- </div>
-</div>
-
-<table class="width100 spacer-bottom" cellpadding="0" cellspacing="0" id="columns">
- <tr>
- <td align="left" width="1%" nowrap class="spacer-right" valign="top">
-
- <%
- value_column = (@period ? "variation_value_#{@period}" : 'value')
- max = 0
- if @period
- blocker_violations=@snapshot.measure('new_blocker_violations')
- critical_violations=@snapshot.measure('new_critical_violations')
- major_violations=@snapshot.measure('new_major_violations')
- minor_violations=@snapshot.measure('new_minor_violations')
- info_violations=@snapshot.measure('new_info_violations')
- else
- blocker_violations=@snapshot.measure('blocker_violations')
- critical_violations=@snapshot.measure('critical_violations')
- major_violations=@snapshot.measure('major_violations')
- minor_violations=@snapshot.measure('minor_violations')
- info_violations=@snapshot.measure('info_violations')
- end
-
- [blocker_violations, critical_violations, major_violations, minor_violations, info_violations].each do |m|
- value = measure_or_variation_value(m)
- max = value if value && value>max
- end
- %>
- <h3><%= message('violations_drilldown.col.severity') -%></h3>
- <table class="spacedicon" style="border: 1px solid #ccc;">
- <%= render :partial => 'severity', :locals => {:css => 'even', :severity => 'BLOCKER', :max => max, :measure => blocker_violations} %>
- <%= render :partial => 'severity', :locals => {:css => 'odd', :severity => 'CRITICAL', :max => max, :measure => critical_violations} %>
- <%= render :partial => 'severity', :locals => {:css => 'even', :severity => 'MAJOR', :max => max, :measure => major_violations} %>
- <%= render :partial => 'severity', :locals => {:css => 'odd', :severity => 'MINOR', :max => max, :measure => minor_violations} %>
- <%= render :partial => 'severity', :locals => {:css => 'even', :severity => 'INFO', :max => max, :measure => info_violations} %>
- </table>
- </td>
- <td align="left" style="white-space: normal;" valign="top">
- <h3><%= message('violations_drilldown.col.rule') -%></h3>
-
- <div class="scrollable">
- <table class="spacedicon" width="100%" id="col_rules">
- <%
- max=0
- rule_index=0
- already_selected=false
- @rule_measures.each do |m|
- value = m.send(value_column) if m
- max=value if value && value>max
- end
- @rule_measures.sort do |x, y|
- val=y.rule_priority<=>x.rule_priority
- if val==0
- x_value=x.send(value_column)
- y_value=y.send(value_column)
- y_value <=> x_value
- else
- val
- end
- end.each do |rule_measure|
- value = rule_measure.send(value_column)
- next if value.nil? || value==0
- rule=rule_measure.rule
- clazz = cycle('even', 'odd', :name => 'rules')
- selected = !already_selected && @rule && @rule.id==rule_measure.rule_id && (@rule_severity.nil? || @rule_severity==rule_measure.severity)
- already_selected = true if selected
- clazz = clazz + ' selected' if selected
- rule_index+=1
- %>
- <tr class="<%= clazz -%>">
- <td width="1%" nowrap>
- <a id="<%= "rule#{rule_index}" -%>" title="<%= message('violations_drilldown.click_for_more_on_x', :params => [rule.plugin_name, rule.plugin_rule_key]) -%>" onclick="window.open(this.href,'rule','height=800,width=900,scrollbars=1,resizable=1');return false;" href="<%= url_for :controller => 'rules', :action => 'show', :id => rule.key, :layout => 'false' -%>"><img src="<%= ApplicationController.root_context -%>/images/priority/<%= rule_measure.rule_priority -%>.png"/></a>
- </td>
- <td>
- <%= link_to(rule.name, {:controller => :drilldown, :action => :violations, :id => @resource.id, :rule => (selected ? nil : rule.key), :rule_sev => (selected ? nil : rule_measure.severity), :sid => nil, :severity => @severity, :period => @period, :rids => (selected ? nil : @selected_rids)}, :title => "#{rule.plugin_name}: #{rule.plugin_rule_key}") -%>
- </td>
- <td class="right" nowrap="nowrap">
- <span><%= @period ? format_variation(rule_measure, :period => @period, :style => 'light') : rule_measure.formatted_value -%></span>
- </td>
- <td class="left last">
- <%= barchart(:width => 70, :percent => (100 * value / max).to_i, :color => (@period ? '#cc0000' : '#777')) if max>0 %>
- </td>
- </tr>
- <% end %>
-
- <% if rule_index==0 %>
- <tr class="even">
- <td><%= message('violations_drilldown.no_violations') -%></td>
- </tr>
- <% end %>
- </table>
- </div>
- </td>
- </tr>
-</table>
-<%
- paths=[]
- rids=[]
- first_column=true
- @drilldown.columns.each_with_index do |column, index|
-%>
- <% if first_column %>
- <table class="spacer-bottom" style="width: 100%">
- <tr>
- <% end %>
- <td class="<%= 'spacer-left' unless first_column -%>" nowrap>
- <div class="scrollable" id="col_<%= index -%>">
- <table class="spaced">
- <%
- column.measures.each_with_index do |measure, row_index|
- resource=column.resource(measure)
- clazz = cycle('even', 'odd', :name => "col_#{index}")
- selected = column.selected_snapshot && column.selected_snapshot.project_id==resource.id
- if selected
- clazz += ' selected'
- paths << [h(resource.name), @selected_rids-[resource.id]]
- end
- %>
- <tr class="<%= clazz -%>" id="row_<%= index -%>_<%= row_index -%>">
- <td nowrap>
- <% if resource.source_code? %>
- <a href="<%= url_for :controller => 'resource', :action => 'index', :id => resource.key, :period => params[:period], :metric => @metric ? @metric.id : nil, :rule => @rule ? @rule.id : @severity, :display_title => 'true' -%>"
- onclick="window.open(this.href,'resource-<%= resource.key.parameterize -%>','height=800,width=900,scrollbars=1,resizable=1');return false;"
- id="popup-<%= resource.key.parameterize -%>"
- target="_blank"><%= image_tag 'new-window-16.gif', :alt => message('new_window') -%></a>
- <% else %>
- <%= link_to(image_tag('zoom.png'), {:id => resource.id}, {:class => 'nolink'}) %>
- <% end %>
- <%= qualifier_icon(resource) -%>
- <% if resource.source_code? %>
- <a href="#" onclick="$j('#col_<%= index -%> tr').removeClass('selected'); $j('#row_<%= index -%>_<%= row_index -%>').addClass('selected'); d(<%= resource.id -%>);"
- alt="<%= h resource.name(true) -%>" title="<%= h resource.name(true) -%>"><%= h resource.name(false) %></a>
- <% else %>
- <%= link_to(h(resource.name), {:only_path => true, :overwrite_params => {:rids => (selected ? rids-[resource.id] : rids+[resource.id])}}) -%>
- <% end %>
- </td>
- <td class="right" nowrap>
- <%= @period ? format_variation(measure, :period => @period, :style => 'light') : measure.formatted_value -%>
- </td>
- </tr>
- <% end %>
- </table>
- </div>
- </td>
- <% if column.switch? || index==@drilldown.columns.size-1 %>
- </tr>
- </table>
- <% end
- first_column = column.switch?
- rids<<column.selected_snapshot.project_id if column.selected_snapshot
- end
- %>
-
-<script>
- $$('#col_rules tr.selected').each(function (item) {
- item.scrollIntoView(true);
- });
- <% for i in 0...@drilldown.columns.size do %>
- $$('#col_<%= i -%> tr.selected').each(function (item) {
- item.scrollIntoView(true);
- });
- <% end %>
-</script>
-
-<div id="accordion-panel"/>
-
-<%= render :partial => 'footer' -%>
\ No newline at end of file
<%
displayed_resource = @resource || @project
- display_only_root = @review || @issue
+ display_only_root = @issue
%>
<% if @breadcrumbs %>
end
end
- # ======== Path for review ========
- if @review
- %>
- <li>
- <%= link_to message('review') + ' #' + @review.id.to_s -%>
- </li>
- <%
- end
-
# ======== Path for issue ========
if @issue
%>
<li>
<a href="<%= ApplicationController.root_context -%>/measures"><%= message('layout.measures') -%></a>
</li>
- <li>
- <a href="<%= ApplicationController.root_context -%>/reviews/index"><%= message('reviews.page') -%></a>
- </li>
<li>
<a href="<%= ApplicationController.root_context -%>/issues/index"><%= message('issues.page') -%></a>
</li>
<li class="<%= 'active' if request.request_uri.include?('/components/index') -%>">
<a href="<%= ApplicationController.root_context -%>/components/index/<%= @project.id -%>"><%= message('components.page') -%></a>
</li>
- <li class="<%= 'active' if request.request_uri.include?('/drilldown/violations') -%>">
- <a href="<%= ApplicationController.root_context -%>/drilldown/violations/<%= @project.id -%><%= "?"+period_param if period_param -%>"><%= message('violations_drilldown.page') -%></a>
- </li>
<li class="<%= 'active' if request.request_uri.include?('/drilldown/issues') -%>">
<a href="<%= ApplicationController.root_context -%>/drilldown/issues/<%= @project.id -%><%= "?"+period_param if period_param -%>"><%= message('issues_drilldown.page') -%></a>
</li>
+++ /dev/null
-<% if @action_plans.empty? %>
-
- <span class="error"><%= message('reviews.an_action_plan_must_be_created_first') -%></span>
-
- <%= link_to_remote message('reviews.hide_this_message'), :url => {:action => 'show', :id => params[:id]}, :update => 'review' -%>
-
-<% else %>
-
-<form method="POST">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
-
- <%= message('reviews.action_plan_label') -%>:
- <select name="action_plan_id" id="selectActionPlan">
- <% @action_plans.each do |plan| %>
- <option value="<%= plan.id -%>" <%= 'selected' if @review.linked_to?(plan) -%>><%= h(plan.name) -%></option>
- <% end %>
- </select>
-
- <textarea id="actionText" rows="4" name="text" style="width: 100%"></textarea>
- <%= submit_to_remote "submit_btn", message('reviews.action_plan_submit'), :url => {:action => 'link_to_action_plan'}, :html => {:id => "submit_btn"}, :update => 'review' -%>
-
-
- <% if @review.planned? %>
-
- <%= submit_to_remote "submit_btn", message('reviews.unlink_action_plan_submit'), :url => {:action => 'unlink_from_action_plan'}, :html => {:id => "submit_btn"}, :update => 'review' -%>
- <% end %>
-
- <%= link_to_remote message('cancel'), :url => {:action => 'show', :id => params[:id]}, :update => 'review' -%>
-</form>
-
-<% end %>
+++ /dev/null
-<%
- assignee_check_script = "if ($('autocompleteText-assignee_login').value != '' && $('assignee_login').value == '') { alert($('autocompleteText-assignee_login').value + '" + message('reviews.user_does_not_exist') + "'); return false;}"
-%>
-
-<form method="post"
- onsubmit="<%= assignee_check_script -%> new Ajax.Updater('review', '<%= url_for :action => 'assign' -%>', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">
- <%= hidden_field_tag :id, params[:id] -%>
-
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="actionText" rows="4" name="text" style="width: 100%"></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
-
- <%= user_autocomplete_field "assignee_login", "" -%>
- <%= submit_to_remote "submit_btn", message('reviews.assign_submit'),
- :url => {:action => 'assign'},
- :update => "review",
- :before => assignee_check_script -%>
-
- <%= image_tag 'sep12.png' -%>
-
- <%= button_to_remote message('reviews.assign_to_me_submit'),
- {
- :url => {:action => 'assign', :id => params[:id], :me => true},
- :update => "review"
- },
- :disabled => (@review.assignee_id==current_user.id) -%>
-
-
- <%= link_to_remote message('cancel'),
- :url => {:action => 'show', :id => params[:id]},
- :update => "review" %>
- <script>
- $('autocompleteText-assignee_login').focus();
- </script>
-</form>
\ No newline at end of file
+++ /dev/null
-<form method="POST">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
-
- <%= message('reviews.new_severity_label') -%>
- <select name="severity" class="withIcons" id="selectSeverity">
- <% Severity::KEYS.each do |severity| %>
- <option class="sev_<%= severity -%>" value="<%= severity -%>" <%= 'selected' if severity==Severity::MAJOR -%>><%= message("severity.#{severity}") -%></option>
- <% end %>
- </select>
-
- <textarea id="actionText" rows="4" name="text" style="width: 100%"></textarea>
- <%= submit_to_remote "submit_btn", message('reviews.change_severity_submit'), :url => {:action => 'change_severity'}, :html => {:id => "submit_btn"}, :update => 'review' -%>
-
- <%= link_to_remote message('cancel'), :url => {:action => 'show', :id => params[:id]}, :update => 'review' -%>
-</form>
+++ /dev/null
-<form method="POST">
- <input type="hidden" name="id" value="<%= @review.id -%>"/>
-
- <textarea id="actionText" rows="4" name="text" style="width: 100%"></textarea>
- <%= submit_to_remote "submit_btn",
- message(@review.resolved? ? 'reviews.reopen_submit' : 'reviews.resolved_submit'),
- :url => {:action => 'change_status'},
- :html => {:id => "submit_btn"},
- :update => 'review' -%>
-
- <%= link_to_remote message('cancel'), :url => {:action => 'show', :id => params[:id]}, :update => 'review' -%>
-</form>
+++ /dev/null
-<%
- button=(@comment ? message('reviews.update_comment_submit') : message('reviews.comment_submit'))
-%>
-<form method="POST" action="save_comment">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
- <% if @comment %>
- <input type="hidden" name="comment_id" value="<%= @comment.id -%>"/>
- <% end %>
-
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="commentText" rows="4" name="text" style="width: 100%" onkeyup="if (this.value=='') $('submit_btn').disabled='true'; else $('submit_btn').disabled='';"><%= @comment.text if @comment -%></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
-
- <%= submit_to_remote "submit_btn", button, :url => {:action => 'save_comment'}, :html => {:id => "submit_btn", :disabled => "true"}, :update => 'review' -%>
-
- <%= link_to_remote message('cancel'), :url => {:action => 'show', :id => params[:id]}, :update => 'review' -%>
-</form>
+++ /dev/null
-<%
- if @review.violation.switched_off?
- title = message('reviews.why_not_false_positive')
- button = message('reviews.unflag_as_false_positive')
- else
- title = message('reviews.why_false_positive')
- button = message('reviews.flag_as_false_positive')
- end
-%>
-<form method="POST">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
- <input type="hidden" name="false_positive" value="<%= @review.violation.switched_off? ? 'false' : 'true' -%>"/>
-
- <h3><%= title -%></h3>
- <textarea id="actionText" rows="4" name="text" style="width: 100%"></textarea>
- <%= submit_to_remote "submit_btn", button, :url => {:action => 'flag_as_false_positive'}, :html => {:id => "submit_btn"}, :update => 'review' -%>
-
- <%= link_to_remote message('cancel'), :url => {:action => 'show', :id => params[:id]}, :update => 'review' -%>
-</form>
+++ /dev/null
-<div id="rev_<%= @review.id -%>">
- <div class="reviewTitle">
- <h2><%= message('reviews.review_number', :params => h(@review.id.to_s)) -%> - <%= h(@review.title) -%></h2>
- </div>
-
- <% if defined?(error_message) && error_message %>
- <div id="review_error" class="error"><%= h error_message -%> <a href="#" onclick="$('review_error').hide(); return false;"><%= message('reviews.hide_this_message') -%></a></div>
- <% end %>
-
- <%
- if current_user && !@review.closed? && @review.rule_failure
- violation_switched_off = @review.rule_failure.switched_off?
- %>
- <div class="marginbottom10" id="actionButtons">
- <% unless @review.resolved? %>
- <%= button_to_remote message('reviews.assign'),
- :url => {:controller => "project_reviews", :action => "assign_form", :id => @review.id},
- :update => "actionForm",
- :complete => "$('actionButtons').remove();$('actionForm').show();" -%>
-
- <% end %>
-
- <%
- if !violation_switched_off
- %>
- <%= button_to_remote (@review.resolved? ? message('reviews.reopen') : message('reviews.resolved')),
- :url => {:controller => "project_reviews", :action => "change_status_form", :id => @review.id},
- :update => "actionForm",
- :complete => "$('actionButtons').remove();$('actionForm').show();$('actionText').focus();" -%>
-
-
- <% end %>
- <% if @review.can_change_false_positive_flag? %>
- <%= button_to_remote (violation_switched_off ? message('reviews.unflag_as_false_positive') : message('reviews.flag_as_false_positive')),
- :url => {:controller => "project_reviews", :action => "false_positive_form", :id => @review.id, :false_positive => !violation_switched_off},
- :update => "actionForm",
- :complete => "$('actionButtons').remove();$('actionForm').show();$('actionText').focus();" -%>
- <% end %>
-
- <% unless @review.resolved? %>
- <%= button_to_remote message('reviews.change_severity'),
- :url => {:controller => "project_reviews", :action => "change_severity_form", :id => @review.id},
- :update => "actionForm",
- :complete => "$('actionButtons').remove();$('actionForm').show();$('selectSeverity').focus();" -%>
-
- <%= button_to_remote message('reviews.link_to_action_plan'),
- :url => {:controller => "project_reviews", :action => "action_plan_form", :id => @review.id},
- :update => "actionForm",
- :complete => "$('actionButtons').remove();$('actionForm').show();$('selectSeverity').focus();" -%>
- <%
- end
- %>
- <%
- if @review.violation
- screens = @review.violation.available_java_screens(current_user)
- screens.each do |screen|
- %>
- <%= button_to_remote message("reviews.command.#{screen.getCommandKey()}.button"),
- :url => {:controller => "project_reviews", :action => "screen", :id => @review.id, :command => screen.getCommandKey()},
- :update => "actionForm",
- :complete => "$('actionButtons').remove();$('actionForm').show();$('actionText').focus();" -%>
- <%
- end
- end
- %>
- </div>
- <% end %>
-
- <div class="discussionComment" id="actionForm" style="border: 1px solid #DDD;display:none"></div>
-
- <table class="reviewDetails marginbottom10">
- <tr>
- <td class="key">
- <%= message('status') -%>:
- </td>
- <td class="val">
- <%= image_tag "status/#{@review.status}.png" -%> <span class="reviewStatus<%= @review.status -%>"><%= message("reviews.status.#{@review.status}") -%></span>
- <% if @review.resolution.present? %>
- (<span class="reviewResolution<%= @review.resolution -%>"><%= message("reviews.resolution.#{@review.resolution}") -%></span>)
- <% end %>
- </td>
- <td class="key">
- <%= message('severity') -%>:
- </td>
- <td class="val">
- <%= image_tag "priority/#{@review.severity}.png" -%> <%= message("severity.#{@review.severity}") -%>
- </td>
- </tr>
- <tr>
- <td class="key">
- <%= message('assignee') -%>:
- </td>
- <td class="val">
- <%= @review.assignee ? h(@review.assignee.name) : '-' -%>
- </td>
- <td class="key">
- <%= message('author') -%>:
- </td>
- <td class="val">
- <%= @review.user ? h(@review.user.name) : '-' -%>
- </td>
- </tr>
- <tr>
- <td class="key">
- <%= message('created') -%>:
- </td>
- <td class="val">
- <%= l(@review.created_at) -%>
- </td>
- <td class="key">
- <%= message('updated') -%>:
- </td>
- <td class="val">
- <%= l(@review.updated_at) -%>
- </td>
- </tr>
- <% if @review.planned? %>
- <tr>
- <td class="key">
- <%= message('reviews.planned_for_label') -%>:
- </td>
- <td class="val" colspan="3">
- <%= h(@review.action_plan.name) -%>
- </td>
- </tr>
- <% end %>
- <% if @review.rule %>
- <tr>
- <td class="key">
- <%= message('rule') -%>:
- </td>
- <td class="val" colspan="3">
- <a onclick="window.open(this.href,'rule','height=800,width=900,scrollbars=1,resizable=1');return false;" href="<%= url_for :controller => 'rules', :action => 'show', :id => @review.rule.key, :layout => 'false' -%>"><%= h(@review.rule.name) -%></a>
- </td>
- </tr>
- <% end %>
- <tr>
- <td class="key">
- <%= message('file') -%>:
- </td>
- <td class="val" colspan="3">
- <%= qualifier_icon(@review.resource) -%>
- <% if !@review.on_project? %> <%= @review.project.long_name -%> <%= image_tag 'sep12.png' -%>
- <% end %>
- <% if @review.rule_failure && @review.rule_failure.snapshot %>
- <%= link_to_resource(@review.resource, @review.resource.long_name, {:tab => :violations, :rule => @review.false_positive ? "false_positive_reviews" : ""}) %>
- <% else %>
- <%= @review.resource.long_name -%>
- <% end %>
- </td>
- </tr>
- </table>
-
- <% if @review.rule_failure && @review.resource_line && @review.rule_failure.snapshot && has_role?(:codeviewer, @review.project) %>
- <div class="marginbottom10">
- <%= snapshot_html_source(@review.rule_failure.snapshot, {:line_range => (@review.resource_line-5)..(@review.resource_line+5), :highlighted_lines => [@review.resource_line]}) -%>
- </div>
- <% end %>
-
- <% if @review.rule_failure || !@review.comments.empty? %>
- <div class="discussion marginbottom10">
- <% if @review.rule_failure %>
- <div class="discussionComment first">
- <%= h(@review.rule_failure.message) -%>
- </div>
- <% end %>
- <%
- @review.comments.each_with_index do |comment, comment_index|
- is_last_comment=(comment_index==@review.comments.size-1)
- %>
- <div class="discussionComment">
- <h4>
- <%= image_tag("reviews/comment.png") -%> <b><%= comment.user.name -%></b> (<%= distance_of_time_in_words_to_now(comment.created_at) -%>)
- <% if is_last_comment && current_user && !@review.closed? %>
- <span class="actions" id="editActions">
-
- <%= image_tag("sep12.png") -%>
-
- <%
- if current_user.id == comment.user_id
- %>
- <%= link_to_remote message('edit'),
- :url => {:controller => "project_reviews", :action => "comment_form", :comment_id => comment.id, :id => @review.id},
- :update => "lastComment",
- :complete => "$('commentAction').remove();$('editActions').hide();$('commentText').focus();",
- :html => {:class => 'link-action'} -%>
-
- <%= link_to_remote message('delete'),
- :url => {:controller => "project_reviews", :action => "delete_comment", :comment_id => comment.id, :id => @review.id},
- :update => "review",
- :confirm => message('reviews.do_you_want_to_delete_comment'),
- :html => {:class => 'link-action'} -%>
- <%
- end
- %>
- </span>
- <% end %>
- </h4>
- <% if is_last_comment %>
- <div id="lastComment">
- <%= comment.html_text -%>
- </div>
- <% else %>
- <%= comment.html_text -%>
- <% end %>
- </div>
- <% end %>
- </div>
- <% end %>
-
- <% if current_user && !@review.closed? %>
- <%= button_to_remote message('reviews.comment'),
- {
- :url => {:controller => "project_reviews", :action => "comment_form", :id => @review.id},
- :update => "commentForm",
- :complete => "$('commentAction').remove();$('commentForm').show();$('commentText').focus();"
- },
- :id => 'commentAction' -%>
-
- <div class="discussionComment" id="commentForm" style="border: 1px solid #DDD;display:none"></div>
- <% end %>
-</div>
\ No newline at end of file
+++ /dev/null
-<div id="review">
- <%
- # hack in case 'error_message' is nil (this should disappear when refactoring the '_view' and '_review' partials)
- error_message = error_message
- %>
- <%= render :partial => 'project_reviews/review', :locals => {:workflow => @review, :error_message => error_message} -%>
-</div>
+++ /dev/null
-<% content_for :script do %>
- <script>
-
- function launchSearch(columnName) {
- var urlParts = document.URL.split('?');
-
- var url = urlParts.shift() + '?';
-
- if (urlParts[0]) {
- urlParts[0].split('&').forEach( function(s) {
- if (s != '' & s.indexOf('asc=') == -1 && s.indexOf('sort=') == -1 ) {
- url += '&' + s;
- }
- });
-
- if (url.indexOf('?') > 0) {
- url += '&sort=' + columnName;
- } else {
- url += '?sort=' + columnName;
- }
-
- if (document.URL.indexOf('&asc=true') == -1) {
- url += '&asc=true';
- }
- }
-
- window.location = url;
- }
- </script>
-<% end %>
-
-<div style="font-size: 85%; margin-bottom: 10px">
-» <a href="#" onclick="javascript:history.back(-1);return false;"><%= message('back') -%></a>
-</div>
-
-<div id="reviews-search">
- <h1><%= message('reviews') -%></h1>
-
- <input type="hidden" name="asc" id="asc" value="<%= params[:asc] ? params[:asc] : 'true' -%>"/>
-
- <div class="review-filters">
- <%= message('reviews.filtered_by') -%>:
- <% if params[:statuses] %>
- <%= review_filter_tag 'statuses', params -%>
- <% end %>
- <% if params[:resolutions] %>
- <%= review_filter_tag 'resolutions', params -%>
- <% end %>
- <% if params[:severities] %>
- <%= review_filter_tag 'severities', params -%>
- <% end %>
- <% if params[:authors] %>
- <%= review_filter_tag 'authors', params -%>
- <% end %>
- <% if params[:assignees] %>
- <%= review_filter_tag 'assignees', params, {:title => params[:assignees].size()==0 ? message('none') : params[:assignees]} -%>
- <% end %>
- <% if params[:action_plan_id] %>
- <%= review_filter_tag 'action_plan_id', params, {:title => ActionPlan.find(params[:action_plan_id]).name} -%>
- <% end %>
- <% if params[:unplanned] %>
- <%= review_filter_tag 'unplanned', params -%>
- <% end %>
- <% if params[:from] %>
- <%= review_filter_tag 'from', params, {:title => l(DateTime.parse(params[:from]))} -%>
- <% end %>
- <% if params[:to] %>
- <%= review_filter_tag 'to', params, {:title => l(DateTime.parse(params[:to]))} -%>
- <% end %>
- </div>
-
- <%= render :partial => "reviews/list" -%>
-
-</div>
\ No newline at end of file
+++ /dev/null
-<form method="POST">
- <input type="hidden" name="id" value="<%= @review.id -%>"/>
- <input type="hidden" name="command" value="<%= @screen.getCommandKey() -%>"/>
-
- <textarea id="actionText" rows="4" name="text" style="width: 100%"></textarea>
- <%= submit_to_remote "submit_btn",
- message("reviews.command.#{@screen.getCommandKey()}.submit"),
- :url => {:action => 'execute'},
- :html => {:id => "submit_btn"},
- :before => "$('loading').show();",
- :update => 'review' -%>
-
- <%= link_to_remote message('cancel'), :url => {:action => 'show', :id => @review.id}, :update => 'review' -%>
-
- <span id="loading" style="display: none;"><%= image_tag 'loading.gif' -%></span>
-</form>
<% if @period && measure('new_issues') %>
<table>
<tr>
- <td><span class="big"><%= format_variation('new_issues', :default => 0, :period => @period, :style => 'none') -%></span> <%= message('new_issues').downcase -%></td>
+ <td><span class="big"><%= format_variation('new_violations', :default => 0, :period => @period, :style => 'none') -%></span> <%= message('new_issues').downcase -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/BLOCKER.png' -%></td>
<td class="name"><%= message('blocker') -%>:</td>
- <td class="value"><%= format_variation('new_blocker_issues', :default => 0, :period => @period, :style => 'none') -%></td>
+ <td class="value"><%= format_variation('new_blocker_violations', :default => 0, :period => @period, :style => 'none') -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/CRITICAL.png' -%></td>
<td class="name"><%= message('critical') -%>:</td>
- <td class="value"><%= format_variation('new_critical_issues', :default => 0, :period => @period, :style => 'none') -%></td>
+ <td class="value"><%= format_variation('new_critical_violations', :default => 0, :period => @period, :style => 'none') -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/MAJOR.png' -%></td>
<td class="name"><%= message('major') -%>:</td>
- <td class="value"><%= format_variation('new_major_issues', :default => 0, :period => @period, :style => 'none') -%></td>
+ <td class="value"><%= format_variation('new_major_violations', :default => 0, :period => @period, :style => 'none') -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/MINOR.png' -%></td>
<td class="name"><%= message('minor') -%>:</td>
- <td class="value"><%= format_variation('new_minor_issues', :default => 0, :period => @period, :style => 'none') -%></td>
+ <td class="value"><%= format_variation('new_minor_violations', :default => 0, :period => @period, :style => 'none') -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/INFO.png' -%></td>
<td class="name"><%= message('info') -%>:</td>
- <td class="value"><%= format_variation('new_info_issues', :default => 0, :period => @period, :style => 'none') -%></td>
+ <td class="value"><%= format_variation('new_info_violations', :default => 0, :period => @period, :style => 'none') -%></td>
</tr>
</table>
<% else %>
<table class="sourceHeader">
<tr>
- <td nowrap><span class="big"><%= format_measure('issues', :default => 0) -%></span> <%= message('issues').downcase -%></td>
+ <td nowrap><span class="big"><%= format_measure('violations', :default => 0) -%></span> <%= message('issues').downcase -%></td>
<td class="sep"> </td>
<td nowrap><%= image_tag 'priority/BLOCKER.png' -%></td>
<td class="name"><%= message('blocker') -%>:</td>
- <td class="value"><%= format_measure('blocker_issues', :default => 0) -%></td>
+ <td class="value"><%= format_measure('blocker_violations', :default => 0) -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/CRITICAL.png' -%></td>
<td class="name"><%= message('critical') -%>:</td>
- <td class="value"><%= format_measure('critical_issues', :default => 0) -%></td>
+ <td class="value"><%= format_measure('critical_violations', :default => 0) -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/MAJOR.png' -%></td>
<td class="name"><%= message('major') -%>:</td>
- <td class="value"><%= format_measure('major_issues', :default => 0) -%></td>
+ <td class="value"><%= format_measure('major_violations', :default => 0) -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/MINOR.png' -%></td>
<td class="name"><%= message('minor') -%>:</td>
- <td class="value"><%= format_measure('minor_issues', :default => 0) -%></td>
+ <td class="value"><%= format_measure('minor_violations', :default => 0) -%></td>
<td class="sep"> </td>
<td><%= image_tag 'priority/INFO.png' -%></td>
<td class="name"><%= message('info') -%>:</td>
- <td class="value"><%= format_measure('info_issues', :default => 0) -%></td>
+ <td class="value"><%= format_measure('info_violations', :default => 0) -%></td>
</tr>
</table>
<% end %>
+++ /dev/null
-<div class="violations_header tab_header">
- <% if @period && measure('new_violations') %>
- <table>
- <tr>
- <td><span class="big"><%= format_variation('new_violations', :default => 0, :period => @period, :style => 'none') -%></span> <%= message('new_violations').downcase -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/BLOCKER.png' -%></td>
- <td class="name"><%= message('blocker') -%>:</td>
- <td class="value"><%= format_variation('new_blocker_violations', :default => 0, :period => @period, :style => 'none') -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/CRITICAL.png' -%></td>
- <td class="name"><%= message('critical') -%>:</td>
- <td class="value"><%= format_variation('new_critical_violations', :default => 0, :period => @period, :style => 'none') -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/MAJOR.png' -%></td>
- <td class="name"><%= message('major') -%>:</td>
- <td class="value"><%= format_variation('new_major_violations', :default => 0, :period => @period, :style => 'none') -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/MINOR.png' -%></td>
- <td class="name"><%= message('minor') -%>:</td>
- <td class="value"><%= format_variation('new_minor_violations', :default => 0, :period => @period, :style => 'none') -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/INFO.png' -%></td>
- <td class="name"><%= message('info') -%>:</td>
- <td class="value"><%= format_variation('new_info_violations', :default => 0, :period => @period, :style => 'none') -%></td>
- </tr>
- </table>
-
- <% else %>
- <table class="sourceHeader">
- <tr>
- <td nowrap><span class="big"><%= format_measure('violations', :default => 0) -%></span> <%= message('violations').downcase -%></td>
-
- <td class="sep"> </td>
- <td nowrap><%= image_tag 'priority/BLOCKER.png' -%></td>
- <td class="name"><%= message('blocker') -%>:</td>
- <td class="value"><%= format_measure('blocker_violations', :default => 0) -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/CRITICAL.png' -%></td>
- <td class="name"><%= message('critical') -%>:</td>
- <td class="value"><%= format_measure('critical_violations', :default => 0) -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/MAJOR.png' -%></td>
- <td class="name"><%= message('major') -%>:</td>
- <td class="value"><%= format_measure('major_violations', :default => 0) -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/MINOR.png' -%></td>
- <td class="name"><%= message('minor') -%>:</td>
- <td class="value"><%= format_measure('minor_violations', :default => 0) -%></td>
-
- <td class="sep"> </td>
- <td><%= image_tag 'priority/INFO.png' -%></td>
- <td class="name"><%= message('info') -%>:</td>
- <td class="value"><%= format_measure('info_violations', :default => 0) -%></td>
- </tr>
- </table>
- <% end %>
-
- <%= render :partial => 'options' -%>
-
-</div>
-
-<div>
+<% accordionId = rand(10000) %>
+<div id="accordion<%= accordionId -%>">
<div class="accordion-item-header">
<%= render :partial => 'tabs' -%>
</div>
<div class="accordion-item-body">
<%= render :partial => "resource/header_#{@extension.getId()}" -%>
- <% if @display_violations && @global_violations && @global_violations.size>0 -%>
- <table class="global_violations" cellpadding="0" cellspacing="0" border="0">
- <% @global_violations.each do |violation| %>
- <tr>
- <td>
- <%= render :partial => 'violation', :locals => {:violation => violation, \
- :review_screens => @review_screens_by_vid ? @review_screens_by_vid.get(violation.id) : []} -%>
- </td>
- </tr>
+ <% if @display_issues && @global_issues && @global_issues.size>0 -%>
+ <div class="code-global-issues">
+ <% @global_issues.each do |issue| %>
+ <%= render :partial => 'issue/issue', :locals => {:issue => issue} -%></td>
<% end %>
- </table>
+ </div>
<% end %>
<% if @lines && @lines.size>0 %>
-
<%= render :partial => "shared/source_display", :locals => { :display_manual_violation_form => @display_manual_violation_form, \
:scm_available => @scm_available, \
:display_coverage => @display_coverage, \
:review_screens_by_vid => @review_screens_by_vid, \
:filtered => @filtered}
%>
-
<% end %>
<% if @duplication_groups %>
</div>
</div>
-
+<script>
+ $j('#accordion<%= accordionId -%> .open-modal').modal();
+</script>
+++ /dev/null
-<% accordionId = rand(10000) %>
-<div id="accordion<%= accordionId -%>">
- <div class="accordion-item-header">
- <%= render :partial => 'tabs' -%>
- </div>
- <div class="accordion-item-body">
- <%= render :partial => "resource/header_#{@extension.getId()}" -%>
-
- <% if @display_issues && @global_issues && @global_issues.size>0 -%>
- <div class="code-global-issues">
- <% @global_issues.each do |issue| %>
- <%= render :partial => 'issue/issue', :locals => {:issue => issue} -%></td>
- <% end %>
- </div>
- <% end %>
-
- <% if @lines && @lines.size>0 %>
- <%= render :partial => "shared/source_display", :locals => { :display_manual_violation_form => @display_manual_violation_form, \
- :scm_available => @scm_available, \
- :display_coverage => @display_coverage, \
- :lines => @lines, \
- :expanded => @expanded, \
- :display_violations => @display_violations, \
- :display_issues => @display_issues, \
- :resource => @resource, \
- :snapshot => @snapshot, \
- :review_screens_by_vid => @review_screens_by_vid, \
- :filtered => @filtered}
- %>
- <% end %>
-
- <% if @duplication_groups %>
- <%= render :partial => 'duplications' -%>
- <% end %>
-
- </div>
-</div>
-<script>
- $j('#accordion<%= accordionId -%> .open-modal').modal();
-</script>
-
<%
if @period
- blocker_issues = @snapshot.measure('new_blocker_issues')
- critical_issues = @snapshot.measure('new_critical_issues')
- major_issues = @snapshot.measure('new_major_issues')
- minor_issues = @snapshot.measure('new_minor_issues')
- info_issues = @snapshot.measure('new_info_issues')
+ blocker_issues = @snapshot.measure('new_blocker_violations')
+ critical_issues = @snapshot.measure('new_critical_violations')
+ major_issues = @snapshot.measure('new_major_violations')
+ minor_issues = @snapshot.measure('new_minor_violations')
+ info_issues = @snapshot.measure('new_info_violations')
metrics = [
- Metric.by_key("new_blocker_issues"),
- Metric.by_key("new_critical_issues"),
- Metric.by_key("new_major_issues"),
- Metric.by_key("new_minor_issues"),
- Metric.by_key("new_info_issues")
+ Metric.by_key('new_blocker_violations'),
+ Metric.by_key('new_critical_violations'),
+ Metric.by_key('new_major_violations'),
+ Metric.by_key('new_minor_violations'),
+ Metric.by_key('new_info_violations')
]
else
- blocker_issues = @snapshot.measure('blocker_issues')
- critical_issues = @snapshot.measure('critical_issues')
- major_issues = @snapshot.measure('major_issues')
- minor_issues = @snapshot.measure('minor_issues')
- info_issues = @snapshot.measure('info_issues')
+ blocker_issues = @snapshot.measure('blocker_violations')
+ critical_issues = @snapshot.measure('critical_violations')
+ major_issues = @snapshot.measure('major_violations')
+ minor_issues = @snapshot.measure('minor_violations')
+ info_issues = @snapshot.measure('info_violations')
metrics = [
- Metric.by_key("blocker_issues"),
- Metric.by_key("critical_issues"),
- Metric.by_key("major_issues"),
- Metric.by_key("minor_issues"),
- Metric.by_key("info_issues")
+ Metric.by_key('blocker_violations'),
+ Metric.by_key('critical_violations'),
+ Metric.by_key('major_violations'),
+ Metric.by_key('minor_violations'),
+ Metric.by_key('info_violations')
]
end
+++ /dev/null
-<div id="vId<%= violation.id -%>">
- <div class="violation">
- <div class="vtitle">
- <% if violation.review %>
- <div class="review_permalink">
- <span class="review_permalink"><%= link_to "Review #"+violation.review.id.to_s, :controller => "project_reviews", :action => "view", :id => violation.review.id -%></span>
- </div>
- <% end %>
-
- <% if violation.review && violation.review.manual_severity && violation.review.severity!=violation.severity %>
- <img src="<%= ApplicationController.root_context -%>/images/priority/<%= violation.review.severity -%>.png">
- <% else %>
- <img src="<%= ApplicationController.root_context -%>/images/priority/<%= violation.failure_level -%>.png">
- <% end %>
-
- <span class="rulename">
- <a onclick="window.open(this.href,'rule','height=800,width=900,scrollbars=1,resizable=1');return false;" href="<%= url_for :controller => 'rules', :action => 'show', :id => violation.rule.key, :layout => 'false' -%>"><%= h(violation.rule.name) -%></a>
- </span>
-
- <%= image_tag 'sep12.png' -%>
-
-
- <% if violation.created_at %>
- <span><%= distance_of_time_in_words_to_now(violation.created_at) -%></span>
-
- <% end %>
- <% if violation.switched_off? %>
- <%= image_tag 'sep12.png' -%>
-
- <span class="falsePositive"><%= message('false_positive') -%></span>
-
- <% end %>
- <% if violation.review && violation.review.resolved? %>
- <%= image_tag 'sep12.png' -%>
-
- <span class="reviewResolved"><%= message('reviews.status.RESOLVED') -%></span>
-
- <% end %>
- <% if violation.review && violation.review.assignee_id %>
- <%= image_tag 'sep12.png' -%>
-
- <%= message('assigned_to') -%> <%= h(violation.review.assignee.name) -%>
-
- <% end %>
- <% if violation.review && violation.review.planned? %>
- <%= image_tag 'sep12.png' -%>
-
- <%= message('reviews.planned_for_x', :params => h(violation.review.action_plan.name)) -%>
-
- <% end %>
-
- </div>
-
- <div class="discussionComment first">
- <div id="vMsg<%= violation.id -%>">
- <%= violation.html_message || ' ' -%>
- </div>
- </div>
-
- <%
- if violation.review
- violation.review.comments.each_with_index do |review_comment, comment_index|
- is_last_comment=(comment_index==violation.review.comments.size-1)
- %>
- <div class="discussionComment">
- <h4><%= image_tag("reviews/comment.png") -%> <b><%= review_comment.user.name -%></b>
- (<%= distance_of_time_in_words_to_now(review_comment.created_at) -%>)
- <% if is_last_comment && current_user %>
- <span class="actions" id="commentActions<%= violation.id -%>">
-
- <%
- if current_user.id == review_comment.user_id
- %>
- <%= image_tag 'sep12.png' -%>
-
- <%= link_to_remote message('reviews.edit'),
- :url => {:controller => "reviews", :action => "violation_comment_form", :comment_id => review_comment.id, :id => violation.id},
- :update => "lastComment" + violation.id.to_s,
- :complete => "$('vActions#{violation.id}').hide();$('commentActions#{violation.id}').hide();$('commentText#{violation.id}').focus();",
- :html => {:class => 'link-action'} -%>
-
- <%= link_to_remote message('reviews.delete'),
- :url => {:controller => "reviews", :action => "violation_delete_comment", :comment_id => review_comment.id, :id => violation.id},
- :update => "vId" + violation.id.to_s,
- :confirm => message('reviews.do_you_want_to_delete_comment'),
- :html => {:class => 'link-action'} -%>
- <%
- end
- %>
- </span>
- <% end %>
- </h4>
- <% if is_last_comment %>
- <div id="lastComment<%= violation.id -%>">
- <%= review_comment.html_text -%>
- </div>
- <% else %>
- <%= review_comment.html_text -%>
- <% end %>
- </div>
- <%
- end
- %>
- <div class="discussionComment" id="replyForm<%= violation.id -%>" style="display:none"></div>
- <%
- end
- %>
-
- <% if current_user %>
- <div class="vActions" id="vActions<%= violation.id -%>">
- <% if defined?(error_message) && error_message %>
- <div id="review_error_<%= violation.id -%>" class="error"><%= h error_message -%> <a href="#" onclick="$('review_error_<%= violation.id -%>').hide(); return false;"><%= message('reviews.hide_this_message') -%></a></div>
- <% end %>
-
- <%= link_to_function message('reviews.comment'), "sCF(#{violation.id})", :name => 'bComment', :class => 'link-action spacer-right' -%>
-
- <% unless violation.review && violation.review.resolved? %>
- <%= link_to_function message('reviews.assign'), "sAF(#{violation.id})", :name => 'bAssign', :class => 'link-action spacer-right' -%>
- <% end %>
-
- <% if violation.review.nil? || violation.review.can_change_false_positive_flag? %>
- <%= link_to_function message(violation.switched_off? ? 'reviews.unflag_as_false_positive' : 'reviews.flag_as_false_positive'),
- "sFPF(#{violation.id})", :name => 'bFalsePositive', :class => 'link-action spacer-right' -%>
- <% end %>
-
- <% unless violation.switched_off? && violation.review && violation.review.resolved? %>
- <div class="dropdown">
- <a href="#" class="link-action link-more" onclick="showDropdownMenu('more<%= violation.id -%>');return false;"><%= message('more_actions') -%></a>
- <ul style="display: none" class="dropdown-menu" id="more<%= violation.id -%>">
- <% if !violation.switched_off? %>
- <li><%= link_to_function (violation.review && violation.review.resolved? ? message('reviews.reopen') : message('reviews.resolved')),
- "sCStF(#{violation.id})", :name => (violation.review && violation.review.resolved? ? 'bReopen' : 'bResolved') -%></li>
- <% end %>
- <% unless violation.review && violation.review.resolved? %>
- <li><%= link_to_function message('reviews.change_severity'), "sCSF(#{violation.id})", :name => 'bChangeSeverity' -%></li>
- <li><%= link_to_function message('reviews.link_to_action_plan'), "sAPF(#{violation.id})", :name => 'bLinkActionPlan' -%></li>
- <% end %>
- <%
- if defined? review_screens
- review_screens.each do |screen|
- %>
- <li><%= link_to_function message("reviews.command.#{screen.getCommandKey()}.button"), "sS(#{violation.id}, '#{screen.getCommandKey()}')", :name => "bCommand#{screen.getCommandKey()}" -%></li>
- <%
- end
- end
- %>
- </ul>
- </div>
- <% end %>
- </div>
- <% end %>
- <div class="discussionComment" id="reviewForm<%= violation.id -%>" style="display:none"></div>
- </div>
-
-</div>
\ No newline at end of file
+++ /dev/null
- <%
- if @reviews && !@reviews.empty?
- %>
- <table id="reviews-list" class="data width100">
- <thead>
- <tr>
- <th width="1%" nowrap>
- <a href="#" onClick="launchSearch('status')"><%= message('status_abbreviated') -%></a>
- <%= image_tag(@asc ? "asc12.png" : "desc12.png") if @sort == 'status' -%>
- </th>
- <th width="1%" nowrap>
- <a href="#" onClick="launchSearch('id')"><%= message('identifier_abbreviated') -%></a>
- <%= image_tag(@asc ? "asc12.png" : "desc12.png") if @sort == 'id' -%>
- </th>
- <th width="1%" nowrap>
- <a href="#" onClick="launchSearch('severity')"><%= message('severity_abbreviated') -%></a>
- <%= image_tag(@asc ? "asc12.png" : "desc12.png") if @sort == 'severity' -%>
- </th>
- <th>
- <a href="#" onClick="launchSearch('title')"><%= message('title') -%></a>
- <%= image_tag(@asc ? "asc12.png" : "desc12.png") if @sort == 'title' -%>
- </th>
- <th width="1%"><%= message('project') -%></th>
- <th><%= message('assignee') -%></th>
- <th>
- <a href="#" onClick="launchSearch('updated_at')"><%= message('age') -%></a>
- <%= image_tag(@asc ? "asc12.png" : "desc12.png") if @sort == 'updated_at' -%>
- </th>
- </tr>
- </thead>
- <tfoot>
- <tr>
- <td colspan="6">
- <%= paginate(@reviews) -%>
- </td>
- </tr>
- </tfoot>
- <tbody>
- <%
- @reviews.each do |review|
- comment = review.comments.last
- %>
- <tr class="<%= cycle('even', 'odd') -%>">
- <td><img src="<%= ApplicationController.root_context -%>/images/status/<%= review.status -%>.png" title="<%= message(review.status.downcase).capitalize -%>"/></td>
- <td>
- <%= link_to h(review.id), :controller => "project_reviews", :action => "view", :id => review.id -%>
- </td>
- <td><img src="<%= ApplicationController.root_context -%>/images/priority/<%= review.severity -%>.png" title="<%= message(review.severity.downcase).capitalize -%>"/></td>
- <td>
- <%= link_to h(review.title), :controller => "project_reviews", :action => "view", :id => review.id -%>
- <% if comment %>
- <div class="comment-excerpt">
- <img src="<%= ApplicationController.root_context -%>/images/reviews/comment.png"/>
- <b><%= comment.user.name -%> :</b>
- <%= comment.excerpt -%>
- <% end %>
- </div>
- </td>
- <td>
- <span class="nowrap"><%= h review.project.name -%></span>
- <br/>
- <span class="note"><%= h(review.resource.name) if review.resource -%></span></td>
- <td><%= review.assignee ? h(review.assignee.name) : '-' -%></td>
- <td><%= distance_of_time_in_words_to_now(review.updated_at) -%></td>
- </tr>
- <%
- end
- %>
- </tbody>
- </table>
- <%
- elsif @reviews
- %>
- <p><%= message('no_results') -%></p>
- <%
- end
- %>
-
- <% if @security_exclusions %>
- <br/>
-
- <p class="notes"><%= message('results_not_display_due_to_security') -%></p>
- <% end %>
\ No newline at end of file
+++ /dev/null
-<% if @action_plans.empty? %>
-
- <span class="error"><%= message('reviews.an_action_plan_must_be_created_first') -%></span>
-
- <%= link_to_function message('reviews.hide_this_message'), "cancelViolationAction(#{params[:id]})" -%>
-
-<% else %>
-
-<form method="POST" action="violation_link_to_action_plan">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
-
- <%= message('reviews.action_plan_label') -%>:
- <select name="action_plan_id" id="selectActionPlan<%= params[:id] -%>">
- <% @action_plans.each do |plan| %>
- <option value="<%= plan.id -%>" <%= 'selected' if @violation.review && @violation.review.linked_to?(plan) -%>><%= h(plan.name) -%></option>
- <% end %>
- </select>
-
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="commentText<%= params[:id] -%>" rows="4" name="text" style="width: 100%"></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
-
- <%= submit_to_remote "submit_btn"+params[:id], message('reviews.action_plan_submit'), :url => {:action => 'violation_link_to_action_plan'}, :html => {:id => "submit_btn"+params[:id]}, :update => 'vId'+params[:id] -%>
-
- <% if @violation.review && @violation.review.planned? %>
-
- <%= submit_to_remote "submit_btn"+params[:id], message('reviews.unlink_action_plan_submit'), :url => {:action => 'violation_unlink_from_action_plan'}, :html => {:id => "submit_btn"+params[:id]}, :update => 'vId'+params[:id] -%>
- <% end %>
-
-
- <%= link_to_function message('cancel'), "cancelViolationAction(#{params[:id]})" -%>
-</form>
-
-<% end %>
\ No newline at end of file
+++ /dev/null
-<%
- assignee_check_script = "if ($('autocompleteText-assignee_login').value != '' && $('assignee_login').value == '') { alert($('autocompleteText-assignee_login').value + '" + message('reviews.user_does_not_exist') + "'); return false;}"
-%>
-
-<form method="post"
- onsubmit="<%= assignee_check_script -%> new Ajax.Updater('vId<%= params[:id] -%>', '<%= url_for :action => 'violation_assign' -%>', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">
- <%= hidden_field_tag :id, params[:id] -%>
-
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="commentText<%= params[:id] -%>" rows="4" name="text" style="width: 100%"></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
-
- <%= user_autocomplete_field "assignee_login", "" -%>
-
- <%= submit_to_remote "submit_btn", message('reviews.assign_submit'),
- :url => {:action => 'violation_assign'},
- :update => "vId" + params[:id],
- :before => assignee_check_script -%>
-
- <%= image_tag 'sep12.png' -%>
-
- <%= submit_to_remote "submit_me_btn", message('reviews.assign_to_me_submit'),
- :url => {:action => 'violation_assign', :id => params[:id], :me => true},
- :update => "vId" + params[:id],
- :html => {:disabled => (@violation.review && @violation.review.assignee_id==current_user.id)} -%>
-
- <%= link_to_function message('cancel'), "cancelViolationAction(#{params[:id]})" -%>
- <script>
- $('autocompleteText-assignee_login').focus()
- </script>
-</form>
\ No newline at end of file
+++ /dev/null
-<form method="POST" action="violation_change_severity">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
-
- <%= message('reviews.new_severity_label') -%>
- <select name="severity" class="withIcons" id="selectSeverity<%= params[:id] -%>">
- <% Severity::KEYS.each do |severity| %>
- <option class="sev_<%= severity -%>" value="<%= severity -%>" <%= 'selected' if severity==Severity::MAJOR -%>><%= message("severity.#{severity}") -%></option>
- <% end %>
- </select>
-
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="commentText<%= params[:id] -%>" rows="4" name="text" style="width: 100%"></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
- <input type="button" value="<%= h message('reviews.change_severity_submit') -%>" onclick="new Ajax.Updater('vId<%= params[:id] -%>', '<%= ApplicationController.root_context -%>/reviews/violation_change_severity', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this.form)});" name="submit_severity" id="submit_btn<%= params[:id] -%>">
-
- <%= link_to_function message('cancel'), "cancelViolationAction(#{params[:id]})" -%>
-</form>
+++ /dev/null
-<form method="POST"
- onsubmit="new Ajax.Updater('vId<%= params[:id] -%>', '<%= url_for :action => 'violation_change_status' -%>', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)});return false;">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
-
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="commentText<%= params[:id] -%>" rows="4" name="text" style="width: 100%"></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
-
- <div>
- <%= submit_to_remote "submit_btn"+params[:id],
- @violation.review && @violation.review.resolved? ? message('reviews.reopen_submit') : message('reviews.resolved_submit'),
- :url => {:action => 'violation_change_status'},
- :html => {:id => "submit_btn"+params[:id]},
- :update => 'vId'+params[:id] -%>
-
- <%= link_to_function message('cancel'), "cancelViolationAction(#{params[:id]})" -%>
- </div>
-</form>
+++ /dev/null
-<%
- button_label=(@comment ? message('reviews.update_comment_submit') : message('reviews.comment_submit'))
-%>
-<form method="POST"
- onsubmit="new Ajax.Updater('vId<%= params[:id] -%>', '<%= url_for :action => 'violation_save_comment' -%>', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)});return false;">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
- <% if @comment %>
- <input type="hidden" name="comment_id" value="<%= @comment.id -%>"/>
- <% end %>
-
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="commentText<%= params[:id] -%>"
- onkeyup="if (this.value=='') $('submit_btn<%= params[:id] -%>').disabled='true'; else $('submit_btn<%= params[:id] -%>').disabled='';"
- rows="4" name="text" style="width: 100%"><%= @comment.text if @comment -%></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
-
-
- <div>
- <%= submit_to_remote "submit_btn"+params[:id],
- button_label,
- :url => {:action => 'violation_save_comment'},
- :html => {:id => "submit_btn"+params[:id], :disabled => "true"},
- :before => "$('loading-#{params[:id]}').show();",
- :update => 'vId'+params[:id] -%>
-
- <%= link_to_function message('cancel'), "cancelViolationAction(#{params[:id]})" -%>
-
- <span id="loading-<%= params[:id] -%>" style="display: none;"><%= image_tag 'loading.gif' -%></span>
- </div>
-</form>
+++ /dev/null
-<%
- if @violation.switched_off?
- title = message('reviews.why_not_false_positive')
- button = message('reviews.unflag_as_false_positive_submit')
- else
- title = message('reviews.why_false_positive')
- button = message('reviews.flag_as_false_positive_submit')
- end
-%>
-<form method="POST" action="violation_flag_as_false_positive">
- <input type="hidden" name="id" value="<%= params[:id] -%>"/>
- <input type="hidden" name="false_positive" value="<%= @violation.switched_off? ? 'false' : 'true' -%>"/>
-
- <h3><%= title -%></h3>
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="commentText<%= params[:id] -%>" rows="4" name="text" style="width: 100%"></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
-
- <%= submit_to_remote "submit_btn"+params[:id], button, :url => {:action => 'violation_flag_as_false_positive'}, :html => {:id => "submit_btn"+params[:id]}, :update => 'vId'+params[:id] -%>
-
- <%= link_to_function message('cancel'), "cancelViolationAction(#{params[:id]})" -%>
-</form>
+++ /dev/null
-<% content_for :style do %>
- <style>
- #search-form select {
- width: 100%;
- box-sizing: border-box;
- -webkit-box-sizing: border-box;
- -moz-box-sizing: border-box;
- }
- </style>
-<% end %>
-<% content_for :script do %>
- <script>
-
- function reviewIdFieldModified(field) {
- if (field.value != '') {
- $('statuses').value = '';
- $('severities').value = '';
- $('projects').value = '';
- $('author_login').value = '';
- $('autocompleteText-author_login').value = '';
- $('assignee_login').value = '';
- $('autocompleteText-assignee_login').value = '';
- $('false_positives').value = 'with';
- }
- }
- function launchSearch(columnName) {
- $('sort').value = columnName;
- if ($('asc').value == "true") {
- $('asc').value = "false";
- } else {
- $('asc').value = "true";
- }
- document.forms[0].submit();
- }
-
- </script>
-<% end %>
-
-<div id="reviews-search">
- <div class="page-split-left">
- <form id="search-form" method="GET" action="<%= ApplicationController.root_context -%>/reviews/index">
- <ul class="sidebar gray-sidebar">
- <li>
- <%= message('identifier_abbreviated') -%>:
- <br/>
- <%= text_field_tag "review_id", @id, :size => 10, :onkeyup => "reviewIdFieldModified(this)" -%>
- </li>
- <li>
- <%= message('status') -%>:
- <br/>
- <select size="5" name="statuses[]" multiple="multiple" id="statuses" class="withIcons">
- <option <%= 'selected' if @statuses.include?('') -%> value=""><%= message('any') -%></option>
- <option value="<%= Review::STATUS_OPEN -%>" class="status_open" <%= 'selected' if @statuses.include?(Review::STATUS_OPEN) -%>><%= message('reviews.status.OPEN') -%></option>
- <option value="<%= Review::STATUS_REOPENED -%>" class="status_reopened" <%= 'selected' if @statuses.include?(Review::STATUS_REOPENED) -%>><%= message('reviews.status.REOPENED') -%></option>
- <option value="<%= Review::STATUS_RESOLVED -%>" class="status_resolved" <%= 'selected' if @statuses.include?(Review::STATUS_RESOLVED) -%>><%= message('reviews.status.RESOLVED') -%></option>
- <option value="<%= Review::STATUS_CLOSED -%>" class="status_closed" <%= 'selected' if @statuses.include?(Review::STATUS_CLOSED) -%>><%= message('reviews.status.CLOSED') -%></option>
- </select>
- </li>
- <li>
- <%= message('severity') -%>:
- <br/>
- <select size="6" name="severities[]" multiple="multiple" id="severities" class="withIcons">
- <option <%= 'selected' if @severities.include?('') -%> value=""><%= message('any') -%></option>
- <option value="<%= Severity::BLOCKER -%>" class="sev_BLOCKER" <%= 'selected' if @severities.include?(Severity::BLOCKER) -%>><%= message('blocker') -%></option>
- <option value="<%= Severity::CRITICAL -%>" class="sev_CRITICAL" <%= 'selected' if @severities.include?(Severity::CRITICAL) -%>><%= message('critical') -%></option>
- <option value="<%= Severity::MAJOR -%>" class="sev_MAJOR" <%= 'selected' if @severities.include?(Severity::MAJOR) -%>><%= message('major') -%></option>
- <option value="<%= Severity::MINOR -%>" class="sev_MINOR" <%= 'selected' if @severities.include?(Severity::MINOR) -%>><%= message('minor') -%></option>
- <option value="<%= Severity::INFO -%>" class="sev_INFO" <%= 'selected' if @severities.include?(Severity::INFO) -%>><%= message('info') -%></option>
- </select>
- </li>
- <li>
- <%= message('project') -%>:
- <br/>
- <select size="6" name="projects[]" multiple="multiple" id="projects">
- <option <%= 'selected' if @projects.include?('') -%> value=""><%= message('any') -%></option>
- <% projects_for_select.each do |project|
- name=project.name(true)
- %>
- <option value="<%= project.id -%>" title="<%= h(name) -%>" <%= 'selected' if @projects.include?(project.id.to_s) -%>><%= h(truncate(name, :length => 20)) -%></option>
- <% end %>
- </select>
- </li>
- <li>
- <%= message('created_by') -%>:
- <br/>
- <%= user_autocomplete_field "author_login", @author_login -%>
- </li>
- <li>
- <%= message('assigned_to') -%>:
- <br/>
- <%= user_autocomplete_field "assignee_login", @assignee_login -%>
- </li>
- <li>
- <select name="false_positives" id="false_positives" onchange="if(this.value=='only' || this.value=='with') {$('assignee_login').value = ''; $('autocompleteText-assignee_login').value = ''; $('statuses').value = '';};">
- <option <%= 'selected' if @false_positives=='without' -%> value="without"><%= message('reviews.without_false_positives') -%></option>
- <option <%= 'selected' if @false_positives=='only' -%> value="only"><%= message('reviews.only_false_positives') -%></option>
- </select>
- </li>
- <li>
- <input type="hidden" name="sort" id="sort" value="<%= @sort -%>"/>
- <input type="hidden" name="asc" id="asc" value="<%= @asc -%>"/>
- <br/>
- <%= submit_tag message('search_verb'), :id => 'submit_search' %>
- </li>
- </ul>
- </form>
- </div>
- <div class="page-split-right">
- <div id="content">
- <% if @false_positives=='only' %>
- <span class="falsePositive"><%= message('reviews.showing_false_positives_only') -%></span>
- <% end %>
- <%= render :partial => "list" -%>
- </div>
- </div>
-</div>
-
-<script>
- $j('#review_id').focus();
-</script>
\ No newline at end of file
+++ /dev/null
-<form method="POST"
- onsubmit="new Ajax.Updater('vId<%= params[:id] -%>', '<%= url_for :action => 'execute' -%>', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)});return false;">
- <input type="hidden" name="id" value="<%= @violation.id -%>"/>
- <input type="hidden" name="command" value="<%= @screen.getCommandKey() -%>"/>
-
- <table class="width100">
- <tr>
- <td style="vertical-align:top">
- <textarea id="commentText<%= @violation.id -%>" rows="4" name="text" style="width: 100%"></textarea>
- </td>
- <td class="sep"></td>
- <td style="vertical-align:top;width: 90px">
- <%= render :partial => 'markdown/tips' -%>
- </td>
- </tr>
- </table>
-
-
- <div>
- <%= submit_to_remote "submit_btn#{@violation.id}",
- message("reviews.command.#{@screen.getCommandKey()}.submit"),
- :url => {:action => 'execute'},
- :html => {:id => "submit_btn#{@violation.id}"},
- :before => "$('loading-#{@violation.id}').show();",
- :update => "vId#{@violation.id}" -%>
-
- <%= link_to_function message('cancel'), "cancelViolationAction(#{@violation.id})" -%>
-
- <span id="loading-<%= @violation.id -%>" style="display: none;"><%= image_tag 'loading.gif' -%></span>
- </div>
-</form>
elsif line.hits
status=(line.hits>0 ? '' : 'ko')
end
- elsif display_violations && line.violations?
- status="ko"
elsif display_issues && line.issues?
status="ko"
elsif line.has_focus
<tr class="row pos<%= index+1 -%>">
<% if display_manual_violation_form %>
- <%= render :partial => "shared/source_violation_form", :locals => { :resource_id => resource.id, \
+ <%= render :partial => "shared/source_issue_form", :locals => { :resource_id => resource.id, \
:index => index, \
:gray_colspan => gray_colspan, \
:white_colspan => white_colspan} %>
</tr>
- <% if display_violations && line.violations? %>
- <%= render :partial => "shared/source_violations", :locals => {:line => line, \
- :display_manual_violation_form => display_manual_violation_form, \
- :scm_available => scm_available, \
- :review_screens_by_vid => review_screens_by_vid} %>
- <% end %>
-
<% if display_issues && line.issues? %>
<%= render :partial => "shared/source_issues", :locals => { :line => line, \
:display_manual_violation_form => display_manual_violation_form, \
--- /dev/null
+<td class="plus"><a onclick="return openCIF(this,<%= resource_id -%>,<%= index + 1 -%>)"></a></td>
+++ /dev/null
-<td class="plus"><a onclick="return openCIF(this,<%= resource_id -%>,<%= index + 1 -%>)"></a></td>
+++ /dev/null
-<tr>
- <% if display_manual_violation_form %>
- <td class="gray"></td>
- <% end
- if scm_available %>
- <td class="scm"></td>
- <% end %>
- <td class="lid"></td>
- <td class="violations">
- <% line.violations.each_with_index do |violation, index| %>
- <%= render :partial => 'violation', :locals => {:violation => violation, :review_screens => review_screens_by_vid ? review_screens_by_vid.get(violation.id) : []} -%>
- <% if index < line.violations.size-1 %>
-
- <% end %>
- <% end %>
- </td>
-</tr>
api.resources :projects, :only => [:index, :destroy], :requirements => { :id => /.*/ }
api.resources :favourites, :only => [:index, :show, :create, :destroy], :requirements => { :id => /.*/ }
api.resources :manual_measures, :only => [:index, :create, :destroy], :requirements => { :id => /.*/ }
- api.resources :reviews, :only => [:index, :show, :create], :member => {
- :add_comment => :put,
- :reassign => :put,
- :resolve => :put,
- :reopen => :put
- }
end
map.connect 'api/metrics', :controller => 'api/metrics', :action => 'index', :conditions => { :method => :get }
map.connect 'api/server/:action', :controller => 'api/server'
map.connect 'api/resoures', :controller => 'api/resources', :action => 'index'
map.connect 'api/sources', :controller => 'api/sources', :action => 'index'
- map.connect 'api/violations', :controller => 'api/violations', :action => 'index'
map.resources 'rules', :path_prefix => 'api', :controller => 'api/rules'
map.resources 'properties', :path_prefix => 'api', :controller => 'api/properties', :requirements => { :id => /.*/ }
modules[gwtId]();
}
-// cancel action : hide form and refresh violation
-function cancelViolationAction(violation_id) {
- new Ajax.Updater(
- 'vId' + violation_id,
- baseUrl + '/reviews/display_violation/' + violation_id,
- {
- asynchronous:true,
- evalScripts:true
- });
- return false;
-}
-
-function hideMoreViolationActions(violation_id) {
- var popup = $('more' + violation_id);
- if (popup != null) {
- popup.hide();
- }
-}
-
-function sCF(violation_id) {
- hideMoreViolationActions(violation_id);
- new Ajax.Updater('reviewForm' + violation_id,
- baseUrl + '/reviews/violation_comment_form/' + violation_id,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('vActions' + violation_id).remove();
- $('reviewForm' + violation_id).show();
- $('commentText' + violation_id).focus();
- }
- });
- return false;
-}
-
-// show review screen
-function sS(violation_id, command_key) {
- hideMoreViolationActions(violation_id);
- new Ajax.Updater('reviewForm' + violation_id,
- baseUrl + '/reviews/screen/' + violation_id + '?command=' + command_key,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('vActions' + violation_id).remove();
- $('reviewForm' + violation_id).show();
- $('commentText' + violation_id).focus();
- }
- });
- return false;
-}
-
-// show the form to change severity
-function sCSF(violation_id) {
- hideMoreViolationActions(violation_id);
- new Ajax.Updater('reviewForm' + violation_id,
- baseUrl + '/reviews/violation_change_severity_form/' + violation_id,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('vActions' + violation_id).remove();
- $('reviewForm' + violation_id).show();
- $('selectSeverity' + violation_id).focus();
- }
- });
- return false;
-}
-
-// show the form to change status
-function sCStF(violation_id) {
- hideMoreViolationActions(violation_id);
- new Ajax.Updater('reviewForm' + violation_id,
- baseUrl + '/reviews/violation_change_status_form/' + violation_id,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('vActions' + violation_id).remove();
- $('reviewForm' + violation_id).show();
- $('commentText' + violation_id).focus();
- }
- });
- return false;
-}
-
-// show the form to flag as false-positive
-function sFPF(violation_id) {
- hideMoreViolationActions(violation_id);
- new Ajax.Updater('reviewForm' + violation_id,
- baseUrl + '/reviews/violation_false_positive_form/' + violation_id,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('vActions' + violation_id).remove();
- $('reviewForm' + violation_id).show();
- $('commentText' + violation_id).focus();
- }
- });
- return false;
-}
-
-// show the form to assign violation
-function sAF(violation_id) {
- hideMoreViolationActions(violation_id);
- new Ajax.Updater('reviewForm' + violation_id,
- baseUrl + '/reviews/violation_assign_form/' + violation_id,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('vActions' + violation_id).remove();
- $('reviewForm' + violation_id).show();
- $('assignee_login').focus();
- }
- });
- return false;
-}
-
-// show the form to link a review to an action plan
-function sAPF(violation_id) {
- hideMoreViolationActions(violation_id);
- new Ajax.Updater('reviewForm' + violation_id,
- baseUrl + '/reviews/violation_action_plan_form/' + violation_id,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('vActions' + violation_id).remove();
- $('reviewForm' + violation_id).show();
- $('action_plan').focus();
- }
- });
- return false;
-}
-
-// show the form to create violation
-function sVF(elt, resource, line, gray_colspan, white_colspan) {
- row = $j('#createViolationForm' + line);
- if (!row.length) {
- expandAccordionItem(elt);
- var element = $j(elt).closest('.pos' + line);
- $j.get(baseUrl + '/resource/show_create_violation_form?resource='+ resource + '&line='+ line + '&gray_colspan='+ gray_colspan + '&white_colspan='+ white_colspan, function (html) {
- element.after(html);
- }).error(function () {
- alert("Server error. Please contact your administrator.");
- });
- }
- return false;
-}
-
-// hide review form
-function hVF(elt, line) {
- var row = $j(elt).closest('#createViolationRow'+ line);
- if (row.length) {
- row.remove();
- }
- return false;
-}
-
-/*
- Functions used in issues code viewer
- */
-
-// show the form for transition
-function displayIssueTransitionForm(issueKey, transitionKey) {
- hideMoreIssueActions(issueKey);
- new Ajax.Updater('issue-form' + issueKey,
- baseUrl + '/issue/issue_transition_form?issue=' + issueKey + '&transition='+ transitionKey,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('issue-actions' + issueKey).remove();
- $('issue-form' + issueKey).show();
- $('issue-comment' + issueKey).focus();
- }
- });
- return false;
-}
-
-// show the form to assign issue
-function displayIssueAssignForm(issueKey) {
- hideMoreIssueActions(issueKey);
- new Ajax.Updater('issue-form' + issueKey,
- baseUrl + '/issue/issue_assign_form/?issue=' +issueKey,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('issue-actions' + issueKey).remove();
- $('issue-form' + issueKey).show();
- $('issue_assignee_login').focus();
- }
- });
- return false;
-}
-
-// show the form to change severity
-function displayIssueChangeSeverityForm(issueKey) {
- hideMoreIssueActions(issueKey);
- new Ajax.Updater('issue-form' + issueKey,
- baseUrl + '/issue/issue_change_severity_form/?issue=' + issueKey,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('issue-actions' + issueKey).remove();
- $('issue-form' + issueKey).show();
- $('issue-severity' + issueKey).focus();
- }
- });
- return false;
-}
-
-// show the form to link a issue to an action plan
-function displayIssuePlanForm(issueKey) {
- hideMoreIssueActions(issueKey);
- new Ajax.Updater('issue-form' + issueKey,
- baseUrl + '/issue/issue_plan_form/?issue=' + issueKey,
- {
- asynchronous:true,
- evalScripts:true,
- onComplete:function (request) {
- $('issue-actions' + issueKey).remove();
- $('issue-form' + issueKey).show();
- $('issue-plan').focus();
- }
- });
- return false;
-}
-
-// cancel action : hide form and refresh issue
-function cancelIssueAction(issueKey) {
- new Ajax.Updater(
- 'issue-key' + issueKey,
- baseUrl + '/issue/display_issue?issue=' + issueKey,
- {
- asynchronous:true,
- evalScripts:true
- });
- return false;
-}
-
-function hideMoreIssueActions(issueKey) {
- var popup = $('more' + issueKey);
- if (popup != null) {
- popup.hide();
- }
-}
-
/*
Functions used in tests viewer
*/
font-size: 12px;
}
-.sources2 td.reviewForm {
- width: 100%;
- padding: 10px;
-}
-
-
-
-
-
-
-
-
-
-
-
-
-
-div.vtitle {
- background-color: #E4ECF3;
- margin: 0;
- padding: 5px 10px;
- line-height: 16px;
- color: #777;
- border-bottom: 1px solid #DDDDDD;
-}
-
-div.vtitle img {
- vertical-align: text-bottom;
-}
-
-div.vActions {
- padding: 5px 10px;
- border-top: 1px solid #DDD;
- background-color: #EFEFEF;
- line-height: 16px;
-}
-
-span.falsePositive, span.reviewResolutionFALSE-POSITIVE {
- background-color: #FFF6BF;
- padding-left: 5px;
- padding-right: 5px;
-}
-
-span.reviewResolved, span.reviewStatusRESOLVED {
- background-color: #4B9FD5;
- color: #FFF;
- padding-left: 5px;
- padding-right: 5px;
-}
-
-span.reviewReopened, span.reviewStatusREOPENED {
- background-color: #FDC596;
- padding-left: 5px;
- padding-right: 5px;
-}
-
span.rulename, span.rulename a {
color: #444;
font-weight: bold;
}
-div.review_permalink {
- float: right;
- color: #333;
- font-weight: bold;
- margin: 0;
- padding: 0 10px;
- text-shadow: 1px 1px 0 #FFFFFF;
-}
-
-span.review_permalink a {
- color: #777;
- font-size: 11px;
- padding: 0 0 0 20px;
-}
-
span.rulename a:hover {
text-decoration: underline;
}
padding: 10px;
}
-/* REVIEWS */
-div.reviewTitle {
- background-color: #E4ECF3;
- color: #4B9FD5;
- line-height: 2.2em;
- margin: 0;
- margin-bottom: 10px;
- padding: 0 10px;
- border: 1px solid #4B9FD5;
-}
-
-div.reviewTitle h2 {
- color: #4183C4;
- font-weight: bold;
- font-size: 100%;
- text-shadow: 0 1px 0 #FFFFFF;
-}
-
-div.reviewTitle span.actions {
- font-size: 12px;
-}
-
-table.reviewDetails {
- width: 100%;
- border: 0;
-}
-
-table.reviewDetails td {
- vertical-align: top;
- text-align: left;
- padding: 5px 10px;
-}
-
-table.reviewDetails td.key {
- white-space: nowrap;
- min-width: 1%;
- color: #777;
-}
-
-table.reviewDetails td img {
- vertical-align: bottom;
-}
-
.discussion {
width: 100%;
border: 1px solid #DDDDDD;
font-size: 90%;
}
-div.review-filters {
- font-size: 93%;
- margin: 10px;
-}
-
-span.review-filter {
- background-color: #CAE3F2;
- padding-left: 5px;
- padding-right: 5px;
- margin-left: 5px;
-}
-
-span.review-filter a {
- color: #777777;
- font-size: 80%;
- margin-left: 6px;
- text-decoration: none;
- text-shadow: 1px 1px 0 #FFFFFF;
-}
-
/* ACTION PLANS */
table.actionPlans {
margin-top: 10px;
public void should_get_resource_viewers() {
final Views views = new Views(VIEWS);
List resourceViewers = views.getPages(NavigationSection.RESOURCE_TAB);
- assertThat(resourceViewers.size()).isEqualTo(1 + 5 /* default */);
+ assertThat(resourceViewers.size()).isEqualTo(1 + 4 /* default */);
assertThat(resourceViewers.contains(new ViewProxy<FakeResourceViewer>(FAKE_TAB))).isEqualTo(true);
}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.services;
-
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.List;
-
-/**
- * @since 2.8
- */
-public class Review extends Model {
-
- private Long id;
- private Date createdAt = null;
- private Date updatedAt = null;
- private String authorLogin = null;
- private String assigneeLogin = null;
- private String title = null;
- private String type = null;
- private String status = null;
- private String severity = null;
- private String resourceKee = null;
- private Integer line = null;
- private String resolution = null;
- private Long violationId;
- private List<Review.Comment> comments = new ArrayList<Review.Comment>();
-
- /**
- * @return id
- */
- public Long getId() {
- return id;
- }
-
- public Review setId(Long id) {
- this.id = id;
- return this;
- }
-
- /**
- * @return date of creation
- */
- public Date getCreatedAt() {
- return createdAt;
- }
-
- public Review setCreatedAt(Date createdAt) {
- this.createdAt = createdAt;
- return this;
- }
-
- /**
- * @return date of last modification
- */
- public Date getUpdatedAt() {
- return updatedAt;
- }
-
- public Review setUpdatedAt(Date updatedAt) {
- this.updatedAt = updatedAt;
- return this;
- }
-
- /**
- * @return user that initiated review
- */
- public String getAuthorLogin() {
- return authorLogin;
- }
-
- public Review setAuthorLogin(String s) {
- this.authorLogin = s;
- return this;
- }
-
- /**
- * @return assignee
- */
- public String getAssigneeLogin() {
- return assigneeLogin;
- }
-
- public Review setAssigneeLogin(String s) {
- this.assigneeLogin = s;
- return this;
- }
-
- /**
- * @return title
- */
- public String getTitle() {
- return title;
- }
-
- public Review setTitle(String s) {
- this.title = s;
- return this;
- }
-
- /**
- * @deprecated since 2.9.
- */
- @Deprecated
- public String getType() {
- return type;
- }
-
- /**
- * @deprecated since 2.9.
- */
- @Deprecated
- public Review setType(String s) {
- this.type = s;
- return this;
- }
-
- /**
- * @return status
- */
- public String getStatus() {
- return status;
- }
-
- public Review setStatus(String status) {
- this.status = status;
- return this;
- }
-
- /**
- * @return severity
- */
- public String getSeverity() {
- return severity;
- }
-
- public Review setSeverity(String severity) {
- this.severity = severity;
- return this;
- }
-
- /**
- * @return resourceKee
- */
- public String getResourceKee() {
- return resourceKee;
- }
-
- public Review setResourceKee(String resourceKee) {
- this.resourceKee = resourceKee;
- return this;
- }
-
- /**
- * @return line
- */
- public Integer getLine() {
- return line;
- }
-
- public Review setLine(Integer line) {
- this.line = line;
- return this;
- }
-
- /**
- * @since 2.9
- */
- public String getResolution() {
- return resolution;
- }
-
- /**
- * @since 2.9
- */
- public Review setResolution(String resolution) {
- this.resolution = resolution;
- return this;
- }
-
- /**
- * @since 2.9
- * @return violation id
- */
- public Long getViolationId() {
- return violationId;
- }
-
- public Review setViolationId(Long violationId) {
- this.violationId = violationId;
- return this;
- }
-
- /**
- * @return comments
- */
- public List<Review.Comment> getComments() {
- return comments;
- }
-
- public Review addComments(Long id, Date updatedAt, String authorLogin, String text) {
- this.comments.add(new Review.Comment(id, updatedAt, authorLogin, text));
- return this;
- }
-
- /**
- * @since 2.8
- */
- public static final class Comment extends Model {
-
- private Long id = null;
- private String authorLogin = null;
- private Date updatedAt = null;
- private String text = null;
-
- private Comment(Long id, Date updatedAt, String authorLogin, String text) {
- this.id = id;
- this.updatedAt = updatedAt;
- this.authorLogin = authorLogin;
- this.text = text;
- }
-
- /**
- * @since 2.9
- * @return id
- */
- public Long getId() {
- return id;
- }
-
- /**
- * @return user that created this comment
- */
- public String getAuthorLogin() {
- return authorLogin;
- }
-
- /**
- * @return date of last modification
- */
- public Date getUpdatedAt() {
- return updatedAt;
- }
-
- /**
- * @return text
- */
- public String getText() {
- return text;
- }
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.services;
-
-/**
- * @since 2.9
- */
-public class ReviewCreateQuery extends CreateQuery<Review> {
-
- private Long violationId;
- private String comment;
- private String assignee;
- private String status;
- private String resolution;
-
- public ReviewCreateQuery() {
- }
-
- public Long getViolationId() {
- return violationId;
- }
-
- public ReviewCreateQuery setViolationId(Long violationId) {
- this.violationId = violationId;
- return this;
- }
-
- public String getComment() {
- return comment;
- }
-
- public ReviewCreateQuery setComment(String comment) {
- this.comment = comment;
- return this;
- }
-
- public String getAssignee() {
- return assignee;
- }
-
- public ReviewCreateQuery setAssignee(String userLogin) {
- this.assignee = userLogin;
- return this;
- }
-
- public String getStatus() {
- return status;
- }
-
- public ReviewCreateQuery setStatus(String status) {
- this.status = status;
- return this;
- }
-
- public String getResolution() {
- return resolution;
- }
-
- public ReviewCreateQuery setResolution(String resolution) {
- this.resolution = resolution;
- return this;
- }
-
- @Override
- public String getUrl() {
- StringBuilder url = new StringBuilder();
- url.append(ReviewQuery.BASE_URL).append('?');
- appendUrlParameter(url, "violation_id", getViolationId());
- appendUrlParameter(url, "assignee", getAssignee());
- appendUrlParameter(url, "status", getStatus());
- appendUrlParameter(url, "resolution", getResolution());
- return url.toString();
- }
-
- /**
- * Property {@link #comment} is transmitted through request body as content may exceed URL size allowed by the server.
- */
- @Override
- public String getBody() {
- return comment;
- }
-
- @Override
- public Class<Review> getModelClass() {
- return Review.class;
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.services;
-
-/**
- * @since 2.8
- */
-public class ReviewQuery extends Query<Review> {
-
- public static final String BASE_URL = "/api/reviews";
-
- public static final String OUTPUT_PLAIN = "PLAIN";
- public static final String OUTPUT_HTML = "HTML";
-
- /**
- * @deprecated since 2.9, but kept for backward compatibility
- */
- @Deprecated
- private String reviewType;
- private Long id;
- private Long[] ids;
- private String[] statuses;
- private String[] severities;
- private String[] projectKeysOrIds;
- private String[] resourceKeysOrIds;
- private String[] authorLogins;
- private String[] assigneeLogins;
- private String output;
- private String[] resolutions;
-
- public ReviewQuery() {
- }
-
- /**
- * @deprecated since 2.9
- * @return NULL
- */
- @Deprecated
- public String getReviewType() {
- return reviewType;
- }
-
- /**
- * @deprecated since 2.9
- * @param reviewType
- * the reviewType to set
- */
- @Deprecated
- public ReviewQuery setReviewType(String reviewType) {
- this.reviewType = reviewType;
- return this;
- }
-
- /**
- * @return the id
- */
- public Long getId() {
- return id;
- }
-
- /**
- * @param id
- * the id to set
- */
- public ReviewQuery setId(Long id) {
- this.id = id;
- return this;
- }
-
- /**
- * @return the ids
- */
- public Long[] getIds() {
- return ids;
- }
-
- /**
- * @param ids
- * the ids to set
- */
- public ReviewQuery setIds(Long... ids) {
- this.ids = ids;
- return this;
- }
-
- /**
- * @return the statuses
- */
- public String[] getStatuses() {
- return statuses;
- }
-
- /**
- * @param statuses
- * the statuses to set
- */
- public ReviewQuery setStatuses(String... statuses) {
- this.statuses = statuses;
- return this;
- }
-
- /**
- * @return the severities
- */
- public String[] getSeverities() {
- return severities;
- }
-
- /**
- * @param severities
- * the severities to set
- */
- public ReviewQuery setSeverities(String... severities) {
- this.severities = severities;
- return this;
- }
-
- /**
- * @return the projectKeysOrIds
- */
- public String[] getProjectKeysOrIds() {
- return projectKeysOrIds;
- }
-
- /**
- * @param projectKeysOrIds
- * the projectKeysOrIds to set
- */
- public ReviewQuery setProjectKeysOrIds(String... projectKeysOrIds) {
- this.projectKeysOrIds = projectKeysOrIds;
- return this;
- }
-
- /**
- * @return the resourceKeysOrIds
- */
- public String[] getResourceKeysOrIds() {
- return resourceKeysOrIds;
- }
-
- /**
- * @param resourceKeysOrIds
- * the resourceKeysOrIds to set
- */
- public ReviewQuery setResourceKeysOrIds(String... resourceKeysOrIds) {
- this.resourceKeysOrIds = resourceKeysOrIds;
- return this;
- }
-
- /**
- * @deprecated since 3.0. Searching by user ID is not possible anymore. Use {@link #getAuthorLogins()} instead.
- */
- @Deprecated
- public String[] getAuthorLoginsOrIds() {
- return authorLogins;
- }
-
- /**
- * @deprecated since 3.0. Searching by user ID is not possible anymore. Use {@link #setAuthorLogins(String...)} instead.
- */
- @Deprecated
- public ReviewQuery setAuthorLoginsOrIds(String... authorLoginsOrIds) {
- setAuthorLogins(authorLoginsOrIds);
- return this;
- }
-
- /**
- * @return the authorLogins
- */
- public String[] getAuthorLogins() {
- return authorLogins;
- }
-
- /**
- * @param authorLogins
- * the authorLogins to set
- */
- public ReviewQuery setAuthorLogins(String... authorLogins) {
- this.authorLogins = authorLogins;
- return this;
- }
-
- /**
- * @deprecated since 3.0. Searching by user ID is not possible anymore. Use {@link #getAssigneeLogins()} instead.
- */
- @Deprecated
- public String[] getAssigneeLoginsOrIds() {
- return assigneeLogins;
- }
-
- /**
- * @deprecated since 3.0. Searching by user ID is not possible anymore. Use {@link #setAssigneeLogins(String...)} instead.
- */
- @Deprecated
- public ReviewQuery setAssigneeLoginsOrIds(String... assigneeLoginsOrIds) {
- setAssigneeLogins(assigneeLoginsOrIds);
- return this;
- }
-
- /**
- * @return the assigneeLogins
- */
- public String[] getAssigneeLogins() {
- return assigneeLogins;
- }
-
- /**
- * @param assigneeLogins
- * the assigneeLogins to set
- */
- public ReviewQuery setAssigneeLogins(String... assigneeLogins) {
- this.assigneeLogins = assigneeLogins;
- return this;
- }
-
- /**
- * @return the output
- */
- public String getOutput() {
- return output;
- }
-
- /**
- *
- * @param output
- * the output
- */
- public ReviewQuery setOutput(String output) {
- this.output = output;
- return this;
- }
-
- /**
- * @since 2.9
- */
- public String[] getResolutions() {
- return resolutions;
- }
-
- /**
- * @since 2.9
- */
- public ReviewQuery setResolutions(String... resolutions) {
- this.resolutions = resolutions;
- return this;
- }
-
- @Override
- public String getUrl() {
- StringBuilder url = new StringBuilder(BASE_URL);
- url.append('?');
- if (id != null) {
- appendUrlParameter(url, "ids", id);
- } else if (ids != null) {
- appendUrlParameter(url, "ids", ids);
- }
- appendUrlParameter(url, "statuses", statuses);
- appendUrlParameter(url, "severities", severities);
- appendUrlParameter(url, "projects", projectKeysOrIds);
- appendUrlParameter(url, "resources", resourceKeysOrIds);
- appendUrlParameter(url, "authors", authorLogins);
- appendUrlParameter(url, "assignees", assigneeLogins);
- appendUrlParameter(url, "output", output);
- appendUrlParameter(url, "resolutions", resolutions);
- if (resolutions == null && reviewType != null) {
- // Use of the 2.8 deprecated API: handle backward compatibility
- appendUrlParameter(url, "review_type", reviewType);
- }
-
- return url.toString();
- }
-
- @Override
- public Class<Review> getModelClass() {
- return Review.class;
- }
-
- public static ReviewQuery createForReview(Long id) {
- return new ReviewQuery().setId(id);
- }
-
- public static ReviewQuery createForResource(Resource resource) {
- return new ReviewQuery().setResourceKeysOrIds(resource.getId().toString());
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.services;
-
-/**
- * @since 2.9
- */
-public final class ReviewUpdateQuery extends UpdateQuery<Review> {
-
- private long reviewId;
- private String action;
- private String comment;
- private String assignee;
- private String resolution;
-
- /**
- * Creates query to add comment to review.
- */
- public static ReviewUpdateQuery addComment(long id, String comment) {
- return new ReviewUpdateQuery(id, "add_comment").setComment(comment);
- }
-
- /**
- * Creates query to reassign review.
- */
- public static ReviewUpdateQuery reassign(long id, String assignee) {
- return new ReviewUpdateQuery(id, "reassign").setAssignee(assignee);
- }
-
- /**
- * Creates query to resolve review.
- * If resolution "FALSE-POSITIVE", then you must provide comment using {@link #setComment(String)}.
- * Otherwise comment is optional.
- *
- * @param resolution
- * can be "FIXED" or "FALSE-POSITIVE"
- */
- public static ReviewUpdateQuery resolve(long id, String resolution) {
- return new ReviewUpdateQuery(id, "resolve").setResolution(resolution);
- }
-
- /**
- * Creates query to reopen review.
- * If review was resolved as "FALSE-POSITIVE", then you must provide comment using {@link #setComment(String)}.
- * Otherwise comment is optional.
- */
- public static ReviewUpdateQuery reopen(long id) {
- return new ReviewUpdateQuery(id, "reopen");
- }
-
- private ReviewUpdateQuery(long id, String action) {
- this.reviewId = id;
- this.action = action;
- }
-
- public long getReviewId() {
- return reviewId;
- }
-
- public ReviewUpdateQuery setComment(String comment) {
- this.comment = comment;
- return this;
- }
-
- public String getComment() {
- return comment;
- }
-
- public String getAssignee() {
- return assignee;
- }
-
- public ReviewUpdateQuery setAssignee(String userLogin) {
- this.assignee = userLogin;
- return this;
- }
-
- public String getResolution() {
- return resolution;
- }
-
- /**
- * @param resolution
- * can be "FIXED" or "FALSE-POSITIVE"
- */
- public ReviewUpdateQuery setResolution(String resolution) {
- this.resolution = resolution;
- return this;
- }
-
- @Override
- public String getUrl() {
- StringBuilder url = new StringBuilder();
- url.append(ReviewQuery.BASE_URL)
- .append('/').append(action)
- .append('/').append(reviewId)
- .append('?');
- appendUrlParameter(url, "assignee", getAssignee());
- appendUrlParameter(url, "resolution", getResolution());
- return url.toString();
- }
-
- /**
- * Property {@link #comment} transmitted through request body as content may exceed URL size allowed by the server.
- */
- @Override
- public String getBody() {
- return comment;
- }
-
- @Override
- public Class<Review> getModelClass() {
- return Review.class;
- }
-}
import java.util.Date;
+/**
+ * @deprecated in 3.6. Replaced by issues.
+ */
+@Deprecated
public class Violation extends Model {
- private Long id = null;
+ private String id = null;
private String message = null;
private String severity = null;
private Integer line = null;
private String ruleName = null;
private String resourceKey = null;
private String resourceName = null;
- private String resourceScope = null;
private String resourceQualifier = null;
private Date createdAt = null;
private boolean switchedOff;
- private Review review = null;
public String getMessage() {
return message;
return this;
}
- public String getResourceScope() {
- return resourceScope;
- }
-
- public Violation setResourceScope(String resourceScope) {
- this.resourceScope = resourceScope;
- return this;
- }
-
public String getResourceQualifier() {
return resourceQualifier;
}
return switchedOff;
}
- /**
- * @since 2.8
- */
- public Review getReview() {
- return review;
- }
-
- /**
- * @since 2.8
- */
- public Violation setReview(Review review) {
- this.review = review;
- return this;
- }
-
- /**
- * @since 2.9
- */
- public Long getId() {
+ public String getKey() {
return id;
}
- /**
- * @since 2.9
- */
- public void setId(Long id) {
+ public Violation setKey(String id) {
this.id = id;
+ return this;
}
}
*/
package org.sonar.wsclient.services;
+/**
+ * @deprecated in 3.6. Replaced by issues.
+ */
+@Deprecated
public class ViolationQuery extends Query<Violation> {
public static final String BASE_URL = "/api/violations";
private String resourceKeyOrId;
private int depth = 0;
- private String[] scopes;
private String[] qualifiers;
private String[] ruleKeys;
- private String[] categories;
private String[] severities;
private Integer limit;
- private Boolean includeReview;
- private String output;
public ViolationQuery(String resourceKeyOrId) {
this.resourceKeyOrId = resourceKeyOrId;
}
- public String[] getScopes() {
- return scopes;
- }
-
- public ViolationQuery setScopes(String... scopes) {
- this.scopes = scopes;
- return this;
- }
-
public String[] getQualifiers() {
return qualifiers;
}
return this;
}
- public String[] getCategories() {
- return categories;
- }
-
- public ViolationQuery setCategories(String... categories) {
- this.categories = categories;
- return this;
- }
-
/**
* @since 2.5
*/
return this;
}
- /**
- * @since 2.8
- */
- public Boolean getIncludeReview() {
- return includeReview;
- }
-
- /**
- * @since 2.8
- */
- public ViolationQuery setIncludeReview(Boolean includeReview) {
- this.includeReview = includeReview;
- return this;
- }
-
- /**
- * @since 2.8
- */
- public String getOutput() {
- return output;
- }
-
- /**
- * @since 2.8
- */
- public ViolationQuery setOutput(String output) {
- this.output = output;
- return this;
- }
-
@Override
public String getUrl() {
StringBuilder url = new StringBuilder(BASE_URL);
url.append("depth=").append(depth).append("&");
}
appendUrlParameter(url, "limit", limit);
- appendUrlParameter(url, "scopes", scopes);
appendUrlParameter(url, "qualifiers", qualifiers);
appendUrlParameter(url, "rules", ruleKeys);
- appendUrlParameter(url, "categories", categories);
appendUrlParameter(url, "priorities", severities);
- appendUrlParameter(url, "include_review", includeReview);
- appendUrlParameter(url, "output", output);
-
- return url.toString();
+ return url.toString();
}
@Override
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.unmarshallers;
-
-import org.sonar.wsclient.services.Review;
-import org.sonar.wsclient.services.WSUtils;
-
-/**
- * @since 2.8
- */
-public class ReviewUnmarshaller extends AbstractUnmarshaller<Review> {
-
- @Override
- protected Review parse(Object json) {
- WSUtils utils = WSUtils.getINSTANCE();
-
- Review review = new Review();
- review.setId(utils.getLong(json, "id"));
- review.setCreatedAt(utils.getDateTime(json, "createdAt"));
- review.setUpdatedAt(utils.getDateTime(json, "updatedAt"));
- review.setAuthorLogin(utils.getString(json, "author"));
- review.setAssigneeLogin(utils.getString(json, "assignee"));
- review.setTitle(utils.getString(json, "title"));
- review.setStatus(utils.getString(json, "status"));
- review.setSeverity(utils.getString(json, "severity"));
- review.setResourceKee(utils.getString(json, "resource"));
- review.setLine(utils.getInteger(json, "line"));
- review.setResolution(utils.getString(json, "resolution"));
- review.setViolationId(utils.getLong(json, "violationId"));
- review.setType(utils.getString(json, "type"));
-
- Object comments = utils.getField(json, "comments");
- if (comments != null) {
- for (int i = 0; i < utils.getArraySize(comments); i++) {
- Object comment = utils.getArrayElement(comments, i);
- review.addComments(utils.getLong(comment, "id"), utils.getDateTime(comment, "updatedAt"), utils.getString(comment, "author"),
- utils.getString(comment, "text"));
- }
- }
-
- return review;
- }
-}
unmarshallers.put(Rule.class, new RuleUnmarshaller());
unmarshallers.put(TimeMachine.class, new TimeMachineUnmarshaller());
unmarshallers.put(Profile.class, new ProfileUnmarshaller());
- unmarshallers.put(Review.class, new ReviewUnmarshaller());
unmarshallers.put(ManualMeasure.class, new ManualMeasureUnmarshaller());
unmarshallers.put(Authentication.class, new AuthenticationUnmarshaller());
unmarshallers.put(ResourceSearchResult.class, new ResourceSearchUnmarshaller());
WSUtils utils = WSUtils.getINSTANCE();
Violation violation = new Violation();
- violation.setId(utils.getLong(json, "id"));
+ violation.setKey(utils.getString(json, "id"));
violation.setMessage(utils.getString(json, "message"));
violation.setLine(utils.getInteger(json, "line"));
violation.setSeverity(utils.getString(json, "priority"));
violation.setCreatedAt(utils.getDateTime(json, "createdAt"));
violation.setSwitchedOff(utils.getBoolean(json, "switchedOff"));
- Object review = utils.getField(json, "review");
- if (review != null) {
- ReviewUnmarshaller reviewUnmarshaller = new ReviewUnmarshaller();
- violation.setReview(reviewUnmarshaller.parse(review));
- }
-
Object rule = utils.getField(json, "rule");
if (rule != null) {
violation.setRuleKey(utils.getString(rule, "key"));
violation.setResourceKey(utils.getString(resource, "key"));
violation.setResourceName(utils.getString(resource, "name"));
violation.setResourceQualifier(utils.getString(resource, "qualifier"));
- violation.setResourceScope(utils.getString(resource, "scope"));
}
return violation;
}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.services;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-
-public class ReviewCreateQueryTest extends QueryTestCase {
-
- @Test
- public void testCreateReview() {
- ReviewCreateQuery query = new ReviewCreateQuery()
- .setViolationId(13L)
- .setComment("Hello World!");
- assertThat(query.getUrl(), is("/api/reviews?violation_id=13&"));
- assertThat(query.getBody(), is("Hello World!"));
- assertThat(query.getModelClass().getName(), is(Review.class.getName()));
- }
-
- @Test
- public void testCreateAssignedReview() {
- ReviewCreateQuery query = new ReviewCreateQuery()
- .setViolationId(13L)
- .setAssignee("fabrice")
- .setComment("Hello World!");
- assertThat(query.getUrl(), is("/api/reviews?violation_id=13&assignee=fabrice&"));
- assertThat(query.getBody(), is("Hello World!"));
- }
-
- @Test
- public void testCreateResolvedReview() {
- ReviewCreateQuery query = new ReviewCreateQuery()
- .setViolationId(13L)
- .setStatus("RESOLVED")
- .setResolution("FALSE-POSITIVE")
- .setComment("Hello World!");
- assertThat(query.getUrl(), is("/api/reviews?violation_id=13&status=RESOLVED&resolution=FALSE-POSITIVE&"));
- assertThat(query.getBody(), is("Hello World!"));
- }
-
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.services;
-
-import static org.hamcrest.Matchers.is;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import org.junit.Test;
-
-public class ReviewQueryTest extends QueryTestCase {
-
- @Test
- public void queryForResource() {
- Resource resource = mock(Resource.class);
- when(resource.getId()).thenReturn(69);
- ReviewQuery query = ReviewQuery.createForResource(resource);
- assertThat(query.getUrl(), is("/api/reviews?resources=69&"));
- assertThat(query.getModelClass().getName(), is(Review.class.getName()));
- }
-
- @Test
- public void queryById() {
- assertThat(new ReviewQuery().setId(13L).getUrl(), is("/api/reviews?ids=13&"));
- assertThat(new ReviewQuery().setIds(10L, 11L).getUrl(), is("/api/reviews?ids=10,11&"));
- }
-
- @Test
- public void queryByResolution() {
- ReviewQuery query = new ReviewQuery().setStatuses("RESOLVED").setResolutions("FALSE-POSITIVE");
- assertThat(query.getUrl(), is("/api/reviews?statuses=RESOLVED&resolutions=FALSE-POSITIVE&"));
- }
-
- @Test
- public void resourceTreeViolations() {
- ReviewQuery query = new ReviewQuery()
- .setStatuses("OPEN")
- .setSeverities("MINOR", "INFO")
- .setProjectKeysOrIds("com.sonar.foo:bar")
- .setResourceKeysOrIds("2", "3")
- .setAuthorLogins("foo")
- .setAssigneeLogins("admin")
- .setOutput("html");
- assertThat(
- query.getUrl(),
- is("/api/reviews?statuses=OPEN&severities=MINOR,INFO&projects=com.sonar.foo%3Abar&resources=2,3&authors=foo&assignees=admin&output=html&"));
- }
-
- @Test
- public void resourceTreeViolationsForSonar2_8() {
- ReviewQuery query = new ReviewQuery();
- query.setIds(10L, 11L).setReviewType("FALSE_POSITIVE").setStatuses("OPEN").setSeverities("MINOR", "INFO")
- .setProjectKeysOrIds("com.sonar.foo:bar").setResourceKeysOrIds("2", "3").setAuthorLogins("foo").setAssigneeLogins("admin")
- .setOutput("html");
- assertThat(
- query.getUrl(),
- is("/api/reviews?ids=10,11&statuses=OPEN&severities=MINOR,INFO&projects=com.sonar.foo%3Abar&resources=2,3&authors=foo&assignees=admin&output=html&review_type=FALSE_POSITIVE&"));
- }
-
- // http://jira.codehaus.org/browse/SONAR-3283
- @Test
- public void testDeprecatedQueryByUserOrAssigneeId() throws Exception {
- // the de deprecated setters
- ReviewQuery query = new ReviewQuery()
- .setAuthorLoginsOrIds("20")
- .setAssigneeLoginsOrIds("40");
- assertThat(query.getAuthorLogins(), is(new String[] {"20"}));
- assertThat(query.getAssigneeLogins(), is(new String[] {"40"}));
-
- // and test the deprecated getters
- query = new ReviewQuery()
- .setAuthorLogins("foo")
- .setAssigneeLogins("bar");
- assertThat(query.getAuthorLoginsOrIds(), is(new String[] {"foo"}));
- assertThat(query.getAssigneeLoginsOrIds(), is(new String[] {"bar"}));
- }
-}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.services;
-
-import static org.hamcrest.Matchers.nullValue;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-
-public class ReviewUpdateQueryTest extends QueryTestCase {
-
- @Test
- public void testAddComment() {
- ReviewUpdateQuery query = ReviewUpdateQuery.addComment(13, "Hello World!");
- assertThat(query.getUrl(), is("/api/reviews/add_comment/13?"));
- assertThat(query.getBody(), is("Hello World!"));
- assertThat(query.getModelClass().getName(), is(Review.class.getName()));
- }
-
- @Test
- public void testReassign() {
- ReviewUpdateQuery query = ReviewUpdateQuery.reassign(13, "fabrice");
- assertThat(query.getUrl(), is("/api/reviews/reassign/13?assignee=fabrice&"));
- assertThat(query.getBody(), nullValue());
- }
-
- @Test
- public void testResolveAsFalsePositive() {
- ReviewUpdateQuery query = ReviewUpdateQuery.resolve(13, "FALSE-POSITIVE").setComment("Hello World!");
- assertThat(query.getUrl(), is("/api/reviews/resolve/13?resolution=FALSE-POSITIVE&"));
- assertThat(query.getBody(), is("Hello World!"));
- }
-
- @Test
- public void testResolveAsFixed() {
- ReviewUpdateQuery query = ReviewUpdateQuery.resolve(13, "FIXED");
- assertThat(query.getUrl(), is("/api/reviews/resolve/13?resolution=FIXED&"));
- assertThat(query.getBody(), nullValue());
- }
-
- @Test
- public void testReopen() {
- ReviewUpdateQuery query = ReviewUpdateQuery.reopen(13);
- assertThat(query.getUrl(), is("/api/reviews/reopen/13?"));
- assertThat(query.getBody(), nullValue());
- }
-
-}
.setLimit(20)
.setSeverities("MAJOR", "BLOCKER")
.setQualifiers("FIL")
- .setRuleKeys("checkstyle:foo", "pmd:bar")
- .setOutput("html");
+ .setRuleKeys("checkstyle:foo", "pmd:bar");
assertThat(
query.getUrl(),
- is("/api/violations?resource=myproject&depth=-1&limit=20&qualifiers=FIL&rules=checkstyle%3Afoo,pmd%3Abar&priorities=MAJOR,BLOCKER&output=html&"));
+ is("/api/violations?resource=myproject&depth=-1&limit=20&qualifiers=FIL&rules=checkstyle%3Afoo,pmd%3Abar&priorities=MAJOR,BLOCKER&"));
}
}
+++ /dev/null
-/*
- * SonarQube, open source software quality management tool.
- * Copyright (C) 2008-2013 SonarSource
- * mailto:contact AT sonarsource DOT com
- *
- * SonarQube is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License as published by the Free Software Foundation; either
- * version 3 of the License, or (at your option) any later version.
- *
- * SonarQube is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- * Lesser General Public License for more details.
- *
- * You should have received a copy of the GNU Lesser General Public License
- * along with this program; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
- */
-package org.sonar.wsclient.unmarshallers;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.CoreMatchers.nullValue;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
-
-import org.junit.Test;
-import org.sonar.wsclient.services.Review;
-import org.sonar.wsclient.services.Review.Comment;
-
-import java.util.List;
-
-public class ReviewUnmarshallerTest extends UnmarshallerTestCase {
-
- @Test
- public void testEmptyJSON() {
- Review review = new ReviewUnmarshaller().toModel("[]");
- assertThat(review, nullValue());
- }
-
- @Test
- public void testToModels() {
- List<Review> reviews = new ReviewUnmarshaller().toModels(loadFile("/reviews/reviews-2.9.json"));
- assertThat(reviews.size(), is(2));
-
- Review review = reviews.get(0);
- assertThat(review.getId(), is(3L));
- assertNotNull(review.getCreatedAt());
- assertNotNull(review.getUpdatedAt());
- assertThat(review.getAuthorLogin(), is("admin"));
- assertThat(review.getAssigneeLogin(), is("admin"));
- assertThat(review.getTitle(), is("'static' modifier out of order with the JLS suggestions."));
- assertThat(review.getStatus(), is("RESOLVED"));
- assertThat(review.getResolution(), is("FALSE-POSITIVE"));
- assertThat(review.getSeverity(), is("MINOR"));
- assertThat(review.getResourceKee(), is("org.codehaus.sonar:sonar-channel:org.sonar.channel.CodeReaderConfiguration"));
- assertThat(review.getLine(), is(33));
- assertThat(review.getViolationId(), is(1L));
- List<Comment> comments = review.getComments();
- assertThat(comments.size(), is(4));
- Comment comment = comments.get(0);
- assertThat(comment.getId(), is(1L));
- assertNotNull(comment.getUpdatedAt());
- assertThat(comment.getAuthorLogin(), is("admin"));
- assertThat(comment.getText(), is("This is a review.<br/>And this is on multiple lines...<br/><br/><code>Wouhou!!!!!</code>"));
-
- review = reviews.get(1);
- assertThat(review.getAssigneeLogin(), nullValue());
- assertThat(review.getStatus(), is("OPEN"));
- assertThat(review.getResolution(), nullValue());
- }
-
- /*
- * Test Unmarshaller with JSON data received from a Sonar 2.8
- */
- @Test
- public void testToModelsForSonar2_8() {
- List<Review> reviews = new ReviewUnmarshaller().toModels(loadFile("/reviews/reviews-2.8.json"));
- assertThat(reviews.size(), is(2));
-
- Review review = reviews.get(0);
- assertThat(review.getAssigneeLogin(), nullValue());
-
- review = reviews.get(1);
- assertThat(review.getId(), is(3L));
- assertNotNull(review.getCreatedAt());
- assertNotNull(review.getUpdatedAt());
- assertThat(review.getAuthorLogin(), is("admin"));
- assertThat(review.getAssigneeLogin(), is("admin"));
- assertThat(review.getTitle(), is("'static' modifier out of order with the JLS suggestions."));
- assertThat(review.getType(), is("VIOLATION"));
- assertThat(review.getStatus(), is("OPEN"));
- assertThat(review.getSeverity(), is("MINOR"));
- assertThat(review.getResourceKee(), is("org.codehaus.sonar:sonar-channel:org.sonar.channel.CodeReaderConfiguration"));
- assertThat(review.getLine(), is(33));
- List<Comment> comments = review.getComments();
- assertThat(comments.size(), is(4));
- Comment comment = comments.get(0);
- assertNotNull(comment.getUpdatedAt());
- assertThat(comment.getAuthorLogin(), is("admin"));
- assertThat(comment.getText(), is("This is a review.<br/>And this is on multiple lines...<br/><br/><code>Wouhou!!!!!</code>"));
- }
-
-}
import java.util.List;
import org.junit.Test;
-import org.sonar.wsclient.services.Review;
import org.sonar.wsclient.services.Violation;
+/**
+ * @deprecated in 3.6. Replaced by issues.
+ */
+@Deprecated
+
public class ViolationUnmarshallerTest extends UnmarshallerTestCase {
@Test
assertThat(violations.size(), is(2));
violation = violations.get(0);
- assertThat(violation.getId(), is(1L));
+ assertThat(violation.getKey(), is("1"));
assertThat(violation.getMessage(), is("throw java.lang.Exception"));
assertThat(violation.hasLine(), is(true));
assertThat(violation.getLine(), is(97));
is("org.apache.excalibur.components:excalibur-pool-instrumented:org.apache.avalon.excalibur.pool.TraceableResourceLimitingPool"));
assertThat(violation.getResourceName(), is("TraceableResourceLimitingPool"));
assertThat(violation.getResourceQualifier(), is("CLA"));
- assertThat(violation.getResourceScope(), is("FIL"));
assertThat(violation.isSwitchedOff(), is(false));
- assertThat(violation.getReview(), nullValue());
}
@Test
assertThat(violation.isSwitchedOff(), is(true));
}
- @Test
- public void testViolationDecoratedWithReview() {
- Violation violation = new ViolationUnmarshaller().toModel(loadFile("/violations/violation-with-review.json"));
- Review review = violation.getReview();
- assertNotNull(review);
- assertThat(review.getId(), is(3L));
- assertThat(review.getComments().size(), is(4));
- assertThat(review.getComments().get(1).getText(), is("<em>Bold on multiple line?</em>"));
- }
-
/**
* See http://jira.codehaus.org/browse/SONAR-2386
*/
+++ /dev/null
-[{"id":1,"message":"'static' modifier out of order with the JLS suggestions.","line":33,"priority":"MINOR","createdAt":"2011-04-26T15:17:46+0200","rule":{"key":"checkstyle:com.puppycrawl.tools.checkstyle.checks.modifier.ModifierOrderCheck","name":"Modifier Order"},"resource":{"key":"org.codehaus.sonar:sonar-channel:org.sonar.channel.CodeReaderConfiguration","name":"CodeReaderConfiguration","scope":"FIL","qualifier":"CLA","language":"java"},"review":{"id":3,"createdAt":"2011-04-26T15:44:42+0200","updatedAt":"2011-04-26T15:44:42+0200","author":"admin","assignee":"admin","title":"'static' modifier out of order with the JLS suggestions.","type":"VIOLATION","status":"OPEN","severity":"MINOR","resource":"org.codehaus.sonar:sonar-channel:org.sonar.channel.CodeReaderConfiguration","line":33,"comments":[{"author":"admin","updatedAt":"2011-04-26T15:44:42+0200","text":"This is a review.<br/>And this is on multiple lines...<br/><br/>''Wouhou!!!!!''"},{"author":"admin","updatedAt":"2011-04-26T17:10:19+0200","text":"<em>Bold on multiple line?</em>"},{"author":"admin","updatedAt":"2011-04-26T17:11:02+0200","text":"And the bullets:<br/><ul><li>1 bullet</li>\n<li>2 bullets</li></ul>"},{"author":"admin","updatedAt":"2011-04-26T17:27:37+0200","text":"Wazzaa"}]}}]
\ No newline at end of file