package org.sonar.server.component.ws;
-import com.google.common.base.Predicate;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Multiset;
-import com.google.common.io.Resources;
-import org.apache.commons.lang.StringUtils;
+import org.apache.commons.lang.BooleanUtils;
import org.sonar.api.i18n.I18n;
import org.sonar.api.measures.CoreMetrics;
import org.sonar.api.measures.Metric;
import org.sonar.api.server.ws.RequestHandler;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
-import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.Durations;
import org.sonar.api.utils.text.JsonWriter;
-import org.sonar.api.web.NavigationSection;
-import org.sonar.api.web.Page;
import org.sonar.api.web.UserRole;
import org.sonar.core.component.ComponentDto;
-import org.sonar.core.component.SnapshotDto;
import org.sonar.core.measure.db.MeasureDto;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.persistence.MyBatis;
import org.sonar.core.properties.PropertyDto;
import org.sonar.core.properties.PropertyQuery;
-import org.sonar.core.timemachine.Periods;
import org.sonar.server.db.DbClient;
import org.sonar.server.exceptions.NotFoundException;
-import org.sonar.server.issue.IssueService;
-import org.sonar.server.issue.RulesAggregation;
-import org.sonar.server.rule.Rule;
-import org.sonar.server.rule.RuleService;
-import org.sonar.server.rule.index.RuleDoc;
-import org.sonar.server.rule.index.RuleQuery;
-import org.sonar.server.search.QueryContext;
-import org.sonar.server.search.Result;
-import org.sonar.server.ui.ViewProxy;
-import org.sonar.server.ui.Views;
import org.sonar.server.user.UserSession;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
-import java.util.Date;
import java.util.List;
import java.util.Map;
public class ComponentAppAction implements RequestHandler {
- private static final String PARAM_KEY = "key";
+ private static final String PARAM_UUID = "uuid";
private static final String PARAM_PERIOD = "period";
+ private static final List<String> METRIC_KEYS = newArrayList(CoreMetrics.LINES_KEY, CoreMetrics.COVERAGE_KEY, CoreMetrics.IT_COVERAGE_KEY, CoreMetrics.OVERALL_COVERAGE_KEY,
+ CoreMetrics.DUPLICATED_LINES_DENSITY_KEY, CoreMetrics.TECHNICAL_DEBT_KEY, CoreMetrics.SQALE_RATING_KEY, CoreMetrics.SQALE_DEBT_RATIO_KEY);
private final DbClient dbClient;
- private final IssueService issueService;
- private final Views views;
- private final RuleService ruleService;
- private final Periods periods;
private final Durations durations;
private final I18n i18n;
- public ComponentAppAction(DbClient dbClient, IssueService issueService, Views views, RuleService ruleService, Periods periods, Durations durations, I18n i18n) {
+ public ComponentAppAction(DbClient dbClient, Durations durations, I18n i18n) {
this.dbClient = dbClient;
- this.issueService = issueService;
- this.views = views;
- this.ruleService = ruleService;
- this.periods = periods;
this.durations = durations;
this.i18n = i18n;
}
.setDescription("Coverage data required for rendering the component viewer")
.setSince("4.4")
.setInternal(true)
- .setHandler(this)
- .setResponseExample(Resources.getResource(this.getClass(), "components-example-app.json"));
+ .setHandler(this);
action
- .createParam(PARAM_KEY)
+ .createParam(PARAM_UUID)
.setRequired(true)
- .setDescription("File key")
- .setExampleValue("org.codehaus.sonar:sonar-plugin-api:src/main/java/org/sonar/api/Plugin.java");
+ .setDescription("Component UUID")
+ .setExampleValue("d6d9e1e5-5e13-44fa-ab82-3ec29efa8935");
action
.createParam(PARAM_PERIOD)
@Override
public void handle(Request request, Response response) {
- String fileKey = request.mandatoryParam(PARAM_KEY);
+ String componentUuid = request.mandatoryParam(PARAM_UUID);
UserSession userSession = UserSession.get();
JsonWriter json = response.newJsonWriter();
DbSession session = dbClient.openSession(false);
try {
- ComponentDto component = dbClient.componentDao().getNullableByKey(session, fileKey);
+ ComponentDto component = dbClient.componentDao().getNullableByUuid(session, componentUuid);
if (component == null) {
- throw new NotFoundException(String.format("Component '%s' does not exist", fileKey));
+ throw new NotFoundException(String.format("Component '%s' does not exist", componentUuid));
}
- userSession.checkComponentPermission(UserRole.USER, fileKey);
+ userSession.checkComponentPermission(UserRole.USER, component.getKey());
- List<Period> periodList = periods(component.projectUuid(), session);
- Integer periodIndex = request.paramAsInt(PARAM_PERIOD);
- Date periodDate = periodDate(periodIndex, periodList);
-
- RulesAggregation rulesAggregation = issueService.findRulesByComponent(component.key(), periodDate, session);
- Multiset<String> severitiesAggregation = issueService.findSeveritiesByComponent(component.key(), periodDate, session);
Map<String, MeasureDto> measuresByMetricKey = measuresByMetricKey(component, session);
-
appendComponent(json, component, userSession, session);
appendPermissions(json, component, userSession);
- appendPeriods(json, periodList);
- appendIssuesAggregation(json, rulesAggregation, severitiesAggregation);
- appendMeasures(json, measuresByMetricKey, severitiesAggregation, periodIndex);
- appendTabs(json, measuresByMetricKey);
- appendExtensions(json, component, userSession);
- appendManualRules(json);
+ appendMeasures(json, measuresByMetricKey);
+
} finally {
MyBatis.closeQuietly(session);
}
);
boolean isFavourite = propertyDtos.size() == 1;
- json.prop("key", component.key());
+ json.prop("uuid", component.uuid());
json.prop("path", component.path());
json.prop("name", component.name());
json.prop("longName", component.longName());
// Do not display parent project if parent project and project are the same
boolean displayParentProject = parentProject != null && !parentProject.getId().equals(project.getId());
-
- // TODO WS should return parentProject and parentProjectName instead of sub
json.prop("subProject", displayParentProject ? parentProject.key() : null);
json.prop("subProjectName", displayParentProject ? parentProject.longName() : null);
json.prop("project", project.key());
json.prop("fav", isFavourite);
}
- private void appendTabs(JsonWriter json, Map<String, MeasureDto> measuresByMetricKey) {
- List<String> tabs = newArrayList();
- if (measuresByMetricKey.get(CoreMetrics.SCM_AUTHORS_BY_LINE_KEY) != null) {
- tabs.add("scm");
- }
- if (hasCoverage(measuresByMetricKey)) {
- tabs.add("coverage");
- }
- if (measuresByMetricKey.get(CoreMetrics.DUPLICATED_LINES_KEY) != null) {
- tabs.add("duplications");
- }
- if (!tabs.isEmpty()) {
- json.name("tabs").beginArray().values(tabs).endArray();
- }
- }
-
- private boolean hasCoverage(Map<String, MeasureDto> measuresByMetricKey) {
- return measuresByMetricKey.get(CoreMetrics.OVERALL_COVERAGE_KEY) != null
- || measuresByMetricKey.get(CoreMetrics.IT_COVERAGE_KEY) != null
- || measuresByMetricKey.get(CoreMetrics.COVERAGE_KEY) != null;
- }
-
private void appendPermissions(JsonWriter json, ComponentDto component, UserSession userSession) {
boolean hasBrowsePermission = userSession.hasComponentPermission(UserRole.USER, component.key());
json.prop("canMarkAsFavourite", userSession.isLoggedIn() && hasBrowsePermission);
- json.prop("canBulkChange", userSession.isLoggedIn());
json.prop("canCreateManualIssue", userSession.isLoggedIn() && hasBrowsePermission);
}
- private void appendMeasures(JsonWriter json, Map<String, MeasureDto> measuresByMetricKey, Multiset<String> severitiesAggregation, Integer periodIndex) {
+ private void appendMeasures(JsonWriter json, Map<String, MeasureDto> measuresByMetricKey) {
json.name("measures").beginObject();
-
- json.prop("fNcloc", formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.NCLOC_KEY), periodIndex));
- json.prop("fCoverage", formatMeasureOrVariation(coverageMeasure(measuresByMetricKey), periodIndex));
- json.prop("fDuplicationDensity", formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.DUPLICATED_LINES_DENSITY_KEY), periodIndex));
- json.prop("fDebt", formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.TECHNICAL_DEBT_KEY), periodIndex));
- json.prop("fSqaleRating", formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.SQALE_RATING_KEY), periodIndex));
- json.prop("fSqaleDebtRatio", formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.SQALE_DEBT_RATIO_KEY), periodIndex));
- json.prop("fTests", formatMeasureOrVariation(measuresByMetricKey.get(CoreMetrics.TESTS_KEY), periodIndex));
-
- json.prop("fIssues", i18n.formatInteger(UserSession.get().locale(), severitiesAggregation.size()));
- for (String severity : severitiesAggregation.elementSet()) {
- json.prop("f" + StringUtils.capitalize(severity.toLowerCase()) + "Issues", i18n.formatInteger(UserSession.get().locale(), severitiesAggregation.count(severity)));
- }
+ json.prop("lines", formatMeasure(measuresByMetricKey.get(CoreMetrics.LINES_KEY)));
+ json.prop("coverage", formatMeasure(coverageMeasure(measuresByMetricKey)));
+ json.prop("duplicationDensity", formatMeasure(measuresByMetricKey.get(CoreMetrics.DUPLICATED_LINES_DENSITY_KEY)));
+ json.prop("issues", formatMeasure(measuresByMetricKey.get(CoreMetrics.OPEN_ISSUES_KEY)));
+ json.prop("debt", formatMeasure(measuresByMetricKey.get(CoreMetrics.TECHNICAL_DEBT_KEY)));
+ json.prop("sqaleRating", formatMeasure(measuresByMetricKey.get(CoreMetrics.SQALE_RATING_KEY)));
+ json.prop("debtRatio", formatMeasure(measuresByMetricKey.get(CoreMetrics.SQALE_DEBT_RATIO_KEY)));
json.endObject();
}
}
}
- private void appendPeriods(JsonWriter json, List<Period> periodList) {
- json.name("periods").beginArray();
- for (Period period : periodList) {
- Date periodDate = period.date();
- json.beginArray()
- .value(period.index())
- .value(period.label())
- .value(periodDate != null ? DateUtils.formatDateTime(periodDate) : null)
- .endArray();
- }
- json.endArray();
- }
-
- private void appendIssuesAggregation(JsonWriter json, RulesAggregation rulesAggregation, Multiset<String> severitiesAggregation) {
- json.name("severities").beginArray();
- for (String severity : severitiesAggregation.elementSet()) {
- json.beginArray()
- .value(severity)
- .value(i18n.message(UserSession.get().locale(), "severity." + severity, null))
- .value(severitiesAggregation.count(severity))
- .endArray();
- }
- json.endArray();
-
- json.name("rules").beginArray();
- for (RulesAggregation.Rule rule : rulesAggregation.rules()) {
- json.beginArray()
- .value(rule.ruleKey().toString())
- .value(rule.name())
- .value(rulesAggregation.countRule(rule))
- .endArray();
- }
- json.endArray();
- }
-
- private void appendManualRules(JsonWriter json) {
- Result<Rule> result = ruleService.search(new RuleQuery().setRepositories(newArrayList(RuleDoc.MANUAL_REPOSITORY)), new QueryContext().setMaxLimit());
- if (result != null && !result.getHits().isEmpty()) {
- List<Rule> manualRules = result.getHits();
- json.name("manual_rules").beginArray();
- for (Rule manualRule : manualRules) {
- json.beginObject()
- .prop("key", manualRule.key().toString())
- .prop("name", manualRule.name())
- .endObject();
- }
- json.endArray();
- }
- }
-
- private void appendExtensions(JsonWriter json, ComponentDto component, UserSession userSession) {
- List<ViewProxy<Page>> extensionPages = views.getPages(NavigationSection.RESOURCE_TAB, component.scope(), component.qualifier(), component.language(), null);
- Map<String, String> extensions = extensions(extensionPages, component, userSession);
- if (!extensions.isEmpty()) {
- json.name("extensions").beginArray();
- for (Map.Entry<String, String> entry : extensions.entrySet()) {
- json.beginArray().value(entry.getKey()).value(entry.getValue()).endArray();
- }
- json.endArray();
- }
- }
-
- private Map<String, String> extensions(List<ViewProxy<Page>> extensions, ComponentDto component, UserSession userSession) {
- Map<String, String> result = newHashMap();
- List<String> providedExtensions = newArrayList("tests_viewer", "coverage", "duplications", "issues", "source");
- for (ViewProxy<Page> page : extensions) {
- if (!providedExtensions.contains(page.getId())) {
- addExtension(page, result, component, userSession);
- }
- }
- return result;
- }
-
- private void addExtension(ViewProxy<Page> page, Map<String, String> result, ComponentDto component, UserSession userSession) {
- if (page.getUserRoles().length == 0) {
- result.put(page.getId(), page.getTitle());
- } else {
- for (String userRole : page.getUserRoles()) {
- if (userSession.hasComponentPermission(userRole, component.key())) {
- result.put(page.getId(), page.getTitle());
- }
- }
- }
- }
-
- private List<Period> periods(String projectUuid, DbSession session) {
- List<Period> periodList = newArrayList();
- SnapshotDto snapshotDto = dbClient.resourceDao().getLastSnapshotByResourceUuid(projectUuid, session);
- if (snapshotDto != null) {
- for (int i = 1; i <= 5; i++) {
- String mode = snapshotDto.getPeriodMode(i);
- if (mode != null) {
- Date periodDate = snapshotDto.getPeriodDate(i);
- String label = periods.label(mode, snapshotDto.getPeriodModeParameter(i), periodDate);
- if (label != null) {
- periodList.add(new Period(i, label, periodDate));
- }
- }
- }
- }
- return periodList;
- }
-
private Map<String, MeasureDto> measuresByMetricKey(ComponentDto component, DbSession session) {
Map<String, MeasureDto> measuresByMetricKey = newHashMap();
String fileKey = component.getKey();
- for (MeasureDto measureDto : dbClient.measureDao().findByComponentKeyAndMetricKeys(fileKey,
- newArrayList(CoreMetrics.NCLOC_KEY, CoreMetrics.COVERAGE_KEY, CoreMetrics.IT_COVERAGE_KEY, CoreMetrics.OVERALL_COVERAGE_KEY,
- CoreMetrics.DUPLICATED_LINES_KEY, CoreMetrics.DUPLICATED_LINES_DENSITY_KEY, CoreMetrics.TECHNICAL_DEBT_KEY, CoreMetrics.TESTS_KEY,
- CoreMetrics.SCM_AUTHORS_BY_LINE_KEY, CoreMetrics.SQALE_RATING_KEY, CoreMetrics.SQALE_DEBT_RATIO_KEY),
- session)) {
+ for (MeasureDto measureDto : dbClient.measureDao().findByComponentKeyAndMetricKeys(fileKey, METRIC_KEYS, session)) {
measuresByMetricKey.put(measureDto.getKey().metricKey(), measureDto);
}
return measuresByMetricKey;
}
- @CheckForNull
- private Date periodDate(@Nullable final Integer periodIndex, List<Period> periodList) {
- if (periodIndex != null) {
- Period period = Iterables.find(periodList, new Predicate<Period>() {
- @Override
- public boolean apply(@Nullable Period input) {
- return input != null && periodIndex.equals(input.index());
- }
- }, null);
- return period != null ? period.date() : null;
- }
- return null;
- }
-
@CheckForNull
private ComponentDto nullableComponentById(@Nullable Long componentId, DbSession session) {
if (componentId != null) {
return null;
}
- @CheckForNull
- private String formatMeasureOrVariation(@Nullable MeasureDto measure, @Nullable Integer periodIndex) {
- if (periodIndex == null) {
- return formatMeasure(measure);
- } else {
- return formatVariation(measure, periodIndex);
- }
- }
-
@CheckForNull
private String formatMeasure(@Nullable MeasureDto measure) {
if (measure != null) {
Metric.ValueType metricType = metric.getType();
Double value = measure.getValue();
String data = measure.getData();
-
+ if (BooleanUtils.isTrue(metric.isOptimizedBestValue()) && value == null) {
+ value = metric.getBestValue();
+ }
if (metricType.equals(Metric.ValueType.FLOAT) && value != null) {
return i18n.formatDouble(UserSession.get().locale(), value);
}
}
return null;
}
-
- @CheckForNull
- private String formatVariation(@Nullable MeasureDto measure, Integer periodIndex) {
- if (measure != null) {
- Double variation = measure.getVariation(periodIndex);
- if (variation != null) {
- Metric metric = CoreMetrics.getMetric(measure.getKey().metricKey());
- Metric.ValueType metricType = metric.getType();
- if (metricType.equals(Metric.ValueType.FLOAT) || metricType.equals(Metric.ValueType.PERCENT)) {
- return i18n.formatDouble(UserSession.get().locale(), variation);
- }
- if (metricType.equals(Metric.ValueType.INT)) {
- return i18n.formatInteger(UserSession.get().locale(), variation.intValue());
- }
- if (metricType.equals(Metric.ValueType.WORK_DUR)) {
- return durations.format(UserSession.get().locale(), durations.create(variation.longValue()), Durations.DurationFormat.SHORT);
- }
- }
- }
- return null;
- }
-
- protected static class Period {
- Integer index;
- String label;
- Date date;
-
- protected Period(Integer index, String label, @Nullable Date date) {
- this.index = index;
- this.label = label;
- this.date = date;
- }
-
- public Integer index() {
- return index;
- }
-
- public String label() {
- return label;
- }
-
- @CheckForNull
- public Date date() {
- return date;
- }
- }
-
}
package org.sonar.server.component.ws;
-import com.google.common.collect.HashMultiset;
-import com.google.common.collect.LinkedHashMultiset;
-import com.google.common.collect.Multiset;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import org.sonar.api.i18n.I18n;
import org.sonar.api.measures.CoreMetrics;
-import org.sonar.api.rule.RuleKey;
-import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.Durations;
-import org.sonar.api.web.NavigationSection;
-import org.sonar.api.web.Page;
import org.sonar.api.web.UserRole;
import org.sonar.core.component.ComponentDto;
-import org.sonar.core.component.SnapshotDto;
import org.sonar.core.measure.db.MeasureDto;
import org.sonar.core.measure.db.MeasureKey;
import org.sonar.core.persistence.DbSession;
import org.sonar.core.properties.PropertyDto;
import org.sonar.core.properties.PropertyQuery;
import org.sonar.core.resource.ResourceDao;
-import org.sonar.core.rule.RuleDto;
-import org.sonar.core.timemachine.Periods;
import org.sonar.server.component.ComponentTesting;
import org.sonar.server.component.db.ComponentDao;
import org.sonar.server.db.DbClient;
-import org.sonar.server.issue.IssueService;
-import org.sonar.server.issue.RulesAggregation;
import org.sonar.server.measure.persistence.MeasureDao;
-import org.sonar.server.rule.Rule;
-import org.sonar.server.rule.RuleService;
-import org.sonar.server.rule.index.RuleQuery;
-import org.sonar.server.search.QueryContext;
-import org.sonar.server.search.Result;
-import org.sonar.server.ui.ViewProxy;
-import org.sonar.server.ui.Views;
import org.sonar.server.user.MockUserSession;
import org.sonar.server.ws.WsTester;
-import java.util.Date;
import java.util.List;
import java.util.Locale;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
-import static org.mockito.Matchers.isNull;
-import static org.mockito.Mockito.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ComponentAppActionTest {
static final String SUB_PROJECT_KEY = "org.codehaus.sonar:sonar-plugin-api";
static final String COMPONENT_KEY = "org.codehaus.sonar:sonar-plugin-api:src/main/java/org/sonar/api/Plugin.java";
+ static final String COMPONENT_UUID = "ABCDE";
+ static final String PROJECT_UUID = "THE_PROJECT";
@Mock
DbSession session;
@Mock
ComponentDao componentDao;
- @Mock
- ResourceDao resourceDao;
-
@Mock
PropertiesDao propertiesDao;
@Mock
MeasureDao measureDao;
-
- @Mock
- IssueService issueService;
-
- @Mock
- Views views;
-
- @Mock
- RuleService ruleService;
-
- @Mock
- Periods periods;
-
@Mock
Durations durations;
DbClient dbClient = mock(DbClient.class);
when(dbClient.openSession(false)).thenReturn(session);
when(dbClient.componentDao()).thenReturn(componentDao);
- when(dbClient.resourceDao()).thenReturn(resourceDao);
when(dbClient.propertiesDao()).thenReturn(propertiesDao);
when(dbClient.measureDao()).thenReturn(measureDao);
project = ComponentTesting.newProjectDto()
.setId(1L)
.setName("SonarQube")
+ .setUuid(PROJECT_UUID)
.setLongName("SonarQube")
.setKey("org.codehaus.sonar:sonar");
- when(issueService.findSeveritiesByComponent(anyString(), any(Date.class), eq(session))).thenReturn(mock(Multiset.class));
- when(issueService.findRulesByComponent(anyString(), any(Date.class), eq(session))).thenReturn(mock(RulesAggregation.class));
when(measureDao.findByComponentKeyAndMetricKeys(anyString(), anyListOf(String.class), eq(session))).thenReturn(measures);
- tester = new WsTester(new ComponentsWs(new ComponentAppAction(dbClient, issueService, views, ruleService, periods, durations, i18n)));
+ tester = new WsTester(new ComponentsWs(new ComponentAppAction(dbClient, durations, i18n)));
}
@Test
ComponentDto file = ComponentTesting.newFileDto(project)
.setId(10L)
.setKey(COMPONENT_KEY)
+ .setUuid(COMPONENT_UUID)
.setName("Plugin.java")
+ .setProjectUuid("THE_PROJECT")
.setLongName("src/main/java/org/sonar/api/Plugin.java")
.setPath("src/main/java/org/sonar/api/Plugin.java")
.setParentProjectId(5L);
- when(componentDao.getNullableByKey(session, COMPONENT_KEY)).thenReturn(file);
+ when(componentDao.getNullableByUuid(session, COMPONENT_UUID)).thenReturn(file);
when(componentDao.getById(5L, session)).thenReturn(new ComponentDto().setId(5L).setLongName("SonarQube :: Plugin API").setKey(SUB_PROJECT_KEY));
when(componentDao.getByUuid(session, project.uuid())).thenReturn(project);
when(propertiesDao.selectByQuery(any(PropertyQuery.class), eq(session))).thenReturn(newArrayList(new PropertyDto()));
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
+ WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID);
request.execute().assertJson(getClass(), "app.json");
}
- @Test
- public void app_without_sub_project() throws Exception {
- String componentKey = "org.codehaus.sonar:sonar";
- MockUserSession.set().setLogin("john").addComponentPermission(UserRole.USER, componentKey, componentKey);
-
- when(componentDao.getNullableByKey(session, componentKey)).thenReturn(project);
- when(componentDao.getByUuid(session, project.uuid())).thenReturn(project);
- when(propertiesDao.selectByQuery(any(PropertyQuery.class), eq(session))).thenReturn(newArrayList(new PropertyDto()));
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", componentKey);
- request.execute().assertJson(getClass(), "app_without_sub_project.json");
- }
-
- @Test
- public void app_with_sub_project_equals_to_project() throws Exception {
- MockUserSession.set().setLogin("john").addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
-
- ComponentDto file = ComponentTesting.newFileDto(project)
- .setId(10L)
- .setKey(COMPONENT_KEY)
- .setName("Plugin.java")
- .setLongName(null)
- .setPath("src/main/java/org/sonar/api/Plugin.java")
- .setParentProjectId(1L);
- when(componentDao.getNullableByKey(session, COMPONENT_KEY)).thenReturn(file);
- when(componentDao.getById(project.getId(), session)).thenReturn(project);
- when(componentDao.getByUuid(session, project.uuid())).thenReturn(project);
- when(propertiesDao.selectByQuery(any(PropertyQuery.class), eq(session))).thenReturn(newArrayList(new PropertyDto()));
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_sub_project_equals_to_project.json");
- }
-
- @Test
- public void app_with_tabs() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
- addComponent();
-
- addMeasure(CoreMetrics.COVERAGE_KEY, 1.0);
- addMeasure(CoreMetrics.DUPLICATED_LINES_KEY, 2);
- addMeasure(CoreMetrics.SCM_AUTHORS_BY_LINE_KEY, 3);
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_tabs.json");
- }
-
@Test
public void app_with_measures() throws Exception {
MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
addComponent();
- addMeasure(CoreMetrics.NCLOC_KEY, 200);
+ addMeasure(CoreMetrics.LINES_KEY, 200);
addMeasure(CoreMetrics.COVERAGE_KEY, 95.4);
addMeasure(CoreMetrics.DUPLICATED_LINES_DENSITY_KEY, 7.4);
addMeasure(CoreMetrics.SQALE_RATING_KEY, "C");
measures.add(MeasureDto.createFor(MeasureKey.of(COMPONENT_KEY, CoreMetrics.TECHNICAL_DEBT_KEY)).setValue(182.0));
when(durations.format(any(Locale.class), any(Duration.class), eq(Durations.DurationFormat.SHORT))).thenReturn("3h 2min");
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
+ WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID);
request.execute().assertJson(getClass(), "app_with_measures.json");
verify(measureDao).findByComponentKeyAndMetricKeys(eq(COMPONENT_KEY), measureKeysCaptor.capture(), eq(session));
- assertThat(measureKeysCaptor.getValue()).contains(CoreMetrics.NCLOC_KEY, CoreMetrics.COVERAGE_KEY, CoreMetrics.DUPLICATED_LINES_DENSITY_KEY,
+ assertThat(measureKeysCaptor.getValue()).contains(CoreMetrics.LINES_KEY, CoreMetrics.COVERAGE_KEY, CoreMetrics.DUPLICATED_LINES_DENSITY_KEY,
CoreMetrics.TECHNICAL_DEBT_KEY);
}
- @Test
- public void app_with_measures_when_period_is_set() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
- addComponent();
- addPeriod();
-
- addVariationMeasure(CoreMetrics.NCLOC_KEY, 2, 1);
- addVariationMeasure(CoreMetrics.COVERAGE_KEY, 5d, 1);
- addVariationMeasure(CoreMetrics.DUPLICATED_LINES_DENSITY_KEY, 1.2, 1);
- addVariationMeasure(CoreMetrics.SQALE_DEBT_RATIO_KEY, 5d, 1);
-
- measures.add(MeasureDto.createFor(MeasureKey.of(COMPONENT_KEY, CoreMetrics.TECHNICAL_DEBT_KEY)).setVariation(1, 10.0));
- when(durations.format(any(Locale.class), any(Duration.class), eq(Durations.DurationFormat.SHORT))).thenReturn("10min");
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY).setParam("period", "1");
- request.execute().assertJson(getClass(), "app_with_measures_when_period_is_set.json");
-
- verify(measureDao).findByComponentKeyAndMetricKeys(eq(COMPONENT_KEY), measureKeysCaptor.capture(), eq(session));
- assertThat(measureKeysCaptor.getValue()).contains(CoreMetrics.NCLOC_KEY, CoreMetrics.COVERAGE_KEY, CoreMetrics.DUPLICATED_LINES_DENSITY_KEY,
- CoreMetrics.TECHNICAL_DEBT_KEY);
- }
-
- @Test
- public void app_with_issues_measures() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
- addComponent();
-
- Multiset<String> severities = LinkedHashMultiset.create();
- severities.add("BLOCKER", 1);
- severities.add("CRITICAL", 2);
- severities.add("MAJOR", 5);
- severities.add("MINOR", 4);
- severities.add("INFO", 2);
- when(issueService.findSeveritiesByComponent(COMPONENT_KEY, null, session)).thenReturn(severities);
- when(i18n.message(any(Locale.class), eq("severity.BLOCKER"), isNull(String.class))).thenReturn("Blocker");
- when(i18n.message(any(Locale.class), eq("severity.CRITICAL"), isNull(String.class))).thenReturn("Critical");
- when(i18n.message(any(Locale.class), eq("severity.MAJOR"), isNull(String.class))).thenReturn("Major");
- when(i18n.message(any(Locale.class), eq("severity.MINOR"), isNull(String.class))).thenReturn("Minor");
- when(i18n.message(any(Locale.class), eq("severity.INFO"), isNull(String.class))).thenReturn("Info");
-
- when(i18n.formatInteger(any(Locale.class), eq(14))).thenReturn("14");
- when(i18n.formatInteger(any(Locale.class), eq(1))).thenReturn("1");
- when(i18n.formatInteger(any(Locale.class), eq(2))).thenReturn("2");
- when(i18n.formatInteger(any(Locale.class), eq(5))).thenReturn("5");
- when(i18n.formatInteger(any(Locale.class), eq(4))).thenReturn("4");
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_issues_measures.json");
- }
-
- @Test
- public void app_with_issues_measures_when_period_is_set() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
- addComponent();
- addPeriod();
-
- Multiset<String> severities = LinkedHashMultiset.create();
- severities.add("BLOCKER", 1);
- severities.add("CRITICAL", 2);
- severities.add("MAJOR", 5);
- severities.add("MINOR", 4);
- severities.add("INFO", 2);
- when(issueService.findSeveritiesByComponent(eq(COMPONENT_KEY), any(Date.class), eq(session))).thenReturn(severities);
-
- when(i18n.message(any(Locale.class), eq("severity.BLOCKER"), isNull(String.class))).thenReturn("Blocker");
- when(i18n.message(any(Locale.class), eq("severity.CRITICAL"), isNull(String.class))).thenReturn("Critical");
- when(i18n.message(any(Locale.class), eq("severity.MAJOR"), isNull(String.class))).thenReturn("Major");
- when(i18n.message(any(Locale.class), eq("severity.MINOR"), isNull(String.class))).thenReturn("Minor");
- when(i18n.message(any(Locale.class), eq("severity.INFO"), isNull(String.class))).thenReturn("Info");
-
- when(i18n.formatInteger(any(Locale.class), eq(14))).thenReturn("14");
- when(i18n.formatInteger(any(Locale.class), eq(1))).thenReturn("1");
- when(i18n.formatInteger(any(Locale.class), eq(2))).thenReturn("2");
- when(i18n.formatInteger(any(Locale.class), eq(5))).thenReturn("5");
- when(i18n.formatInteger(any(Locale.class), eq(4))).thenReturn("4");
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY).setParam("period", "1");
- request.execute().assertJson(getClass(), "app_with_issues_measures_when_period_is_set.json");
- }
-
- @Test
- public void app_with_tests_measure() throws Exception {
- String componentKey = "org.codehaus.sonar:sonar-server:src/test/java/org/sonar/server/issue/PlanActionTest.java";
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, componentKey);
-
- ComponentDto file = ComponentTesting.newFileDto(project)
- .setId(10L)
- .setQualifier("UTS")
- .setLongName(null)
- .setKey(componentKey).setName("PlanActionTest.java")
- .setPath("src/test/java/org/sonar/server/issue/PlanActionTest.java")
- .setParentProjectId(5L);
- when(componentDao.getNullableByKey(session, componentKey)).thenReturn(file);
- when(componentDao.getById(5L, session)).thenReturn(new ComponentDto().setId(5L).setLongName("SonarQube :: Plugin API").setKey(SUB_PROJECT_KEY));
- when(componentDao.getByUuid(session, project.uuid())).thenReturn(project);
-
- addMeasure(CoreMetrics.TESTS_KEY, 10);
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", componentKey);
- request.execute().assertJson(getClass(), "app_with_tests_measure.json");
-
- verify(measureDao).findByComponentKeyAndMetricKeys(eq(componentKey), measureKeysCaptor.capture(), eq(session));
- assertThat(measureKeysCaptor.getValue()).contains(CoreMetrics.TESTS_KEY);
- }
-
@Test
public void app_with_overall_measure() throws Exception {
MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
addMeasure(CoreMetrics.COVERAGE_KEY, 95.4);
addMeasure(CoreMetrics.IT_COVERAGE_KEY, 85.2);
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
+ WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID);
request.execute().assertJson(getClass(), "app_with_overall_measure.json");
}
addMeasure(CoreMetrics.COVERAGE_KEY, 95.4);
addMeasure(CoreMetrics.IT_COVERAGE_KEY, 85.2);
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
+ WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID);
request.execute().assertJson(getClass(), "app_with_ut_measure.json");
}
addMeasure(CoreMetrics.IT_COVERAGE_KEY, 85.2);
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
+ WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("uuid", COMPONENT_UUID);
request.execute().assertJson(getClass(), "app_with_it_measure.json");
}
- @Test
- public void app_with_periods() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
-
- ComponentDto file = addComponent();
-
- when(resourceDao.getLastSnapshotByResourceUuid(file.projectUuid(), session)).thenReturn(
- new SnapshotDto().setPeriodMode(1, "previous_analysis").setPeriodDate(1, DateUtils.parseDate("2014-05-08"))
- );
- when(periods.label(anyString(), anyString(), any(Date.class))).thenReturn("since previous analysis (May 08 2014)");
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_periods.json");
- }
-
- @Test
- public void app_with_severities() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
-
- addComponent();
-
- Multiset<String> severities = HashMultiset.create();
- severities.add("MAJOR", 5);
- when(issueService.findSeveritiesByComponent(COMPONENT_KEY, null, session)).thenReturn(severities);
- when(i18n.message(any(Locale.class), eq("severity.MAJOR"), isNull(String.class))).thenReturn("Major");
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_severities.json");
- }
-
- @Test
- public void app_with_severities_when_period_is_set() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
- addComponent();
- addPeriod();
-
- Multiset<String> severities = HashMultiset.create();
- severities.add("MAJOR", 5);
- when(issueService.findSeveritiesByComponent(eq(COMPONENT_KEY), any(Date.class), eq(session))).thenReturn(severities);
- when(i18n.message(any(Locale.class), eq("severity.MAJOR"), isNull(String.class))).thenReturn("Major");
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY).setParam("period", "1");
- request.execute().assertJson(getClass(), "app_with_severities_when_period_is_set.json");
- }
-
- @Test
- public void app_with_rules() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
-
- addComponent();
- when(issueService.findRulesByComponent(COMPONENT_KEY, null, session)).thenReturn(
- new RulesAggregation().add(new RuleDto().setRuleKey("AvoidCycle").setRepositoryKey("squid").setName("Avoid Cycle"))
- );
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_rules.json");
- }
-
- @Test
- public void app_with_rules_when_period_is_set() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
-
- addComponent();
-
- Date periodDate = DateUtils.parseDate("2014-05-08");
- when(resourceDao.getLastSnapshotByResourceUuid(project.uuid(), session)).thenReturn(
- new SnapshotDto().setPeriodMode(1, "previous_analysis").setPeriodDate(1, periodDate)
- );
- when(periods.label(anyString(), anyString(), any(Date.class))).thenReturn("since previous analysis (May 08 2014)");
-
- when(issueService.findRulesByComponent(COMPONENT_KEY, periodDate, session)).thenReturn(
- new RulesAggregation().add(new RuleDto().setRuleKey("AvoidCycle").setRepositoryKey("squid").setName("Avoid Cycle"))
- );
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY).setParam("period", "1");
- request.execute().assertJson(getClass(), "app_with_rules_when_period_is_set.json");
- }
-
- @Test
- public void app_with_extension() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
- addComponent();
-
- when(views.getPages(anyString(), anyString(), anyString(), anyString(), any(String[].class))).thenReturn(
- // Issues extension will be ignore
- newArrayList(new ViewProxy<Page>(new MyExtension()), new ViewProxy<Page>(new MyExtension()), new ViewProxy<Page>(new IssuesExtension())));
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_extension.json");
- }
-
- @Test
- public void app_with_extension_having_permission() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
- addComponent();
-
- when(views.getPages(anyString(), anyString(), anyString(), anyString(), any(String[].class))).thenReturn(
- newArrayList(new ViewProxy<Page>(new MyExtensionWithRole())));
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_extension_having_permission.json");
- }
-
- @Test
- public void app_with_manual_rules() throws Exception {
- MockUserSession.set().addComponentPermission(UserRole.USER, SUB_PROJECT_KEY, COMPONENT_KEY);
- addComponent();
-
- Result<Rule> result = mock(Result.class);
- Rule rule = mock(Rule.class);
- when(rule.key()).thenReturn(RuleKey.of("manual", "API"));
- when(rule.name()).thenReturn("API");
- when(result.getHits()).thenReturn(newArrayList(rule));
- when(ruleService.search(any(RuleQuery.class), any(QueryContext.class))).thenReturn(result);
-
- WsTester.TestRequest request = tester.newGetRequest("api/components", "app").setParam("key", COMPONENT_KEY);
- request.execute().assertJson(getClass(), "app_with_manual_rules.json");
- }
-
private ComponentDto addComponent() {
ComponentDto file = ComponentTesting.newFileDto(project)
.setId(10L)
.setQualifier("FIL")
.setKey(COMPONENT_KEY)
+ .setUuid(COMPONENT_UUID)
+ .setProjectUuid(PROJECT_UUID)
.setName("Plugin.java")
.setLongName("src/main/java/org/sonar/api/Plugin.java")
.setPath("src/main/java/org/sonar/api/Plugin.java")
.setParentProjectId(5L);
- when(componentDao.getNullableByKey(session, COMPONENT_KEY)).thenReturn(file);
+ when(componentDao.getNullableByUuid(session, COMPONENT_UUID)).thenReturn(file);
when(componentDao.getById(5L, session)).thenReturn(new ComponentDto().setId(5L).setLongName("SonarQube :: Plugin API").setKey(SUB_PROJECT_KEY));
when(componentDao.getByUuid(session, project.uuid())).thenReturn(project);
return file;
}
- private void addPeriod() {
- Date periodDate = DateUtils.parseDate("2014-05-08");
- when(resourceDao.getLastSnapshotByResourceUuid(project.uuid(), session)).thenReturn(
- new SnapshotDto().setPeriodMode(1, "previous_analysis").setPeriodDate(1, periodDate)
- );
- when(periods.label(anyString(), anyString(), any(Date.class))).thenReturn("since previous analysis (May 08 2014)");
- }
-
private void addMeasure(String metricKey, Integer value) {
measures.add(MeasureDto.createFor(MeasureKey.of(COMPONENT_KEY, metricKey)).setValue(value.doubleValue()));
when(i18n.formatInteger(any(Locale.class), eq(value.intValue()))).thenReturn(Integer.toString(value));
measures.add(MeasureDto.createFor(MeasureKey.of(COMPONENT_KEY, metricKey)).setTextValue(value));
}
- private void addVariationMeasure(String metricKey, Integer value, Integer periodIndex) {
- measures.add(MeasureDto.createFor(MeasureKey.of(COMPONENT_KEY, metricKey)).setVariation(periodIndex, value.doubleValue()));
- when(i18n.formatInteger(any(Locale.class), eq(value))).thenReturn(Integer.toString(value));
- }
-
- private void addVariationMeasure(String metricKey, Double value, Integer periodIndex) {
- measures.add(MeasureDto.createFor(MeasureKey.of(COMPONENT_KEY, metricKey)).setVariation(periodIndex, value));
- when(i18n.formatDouble(any(Locale.class), eq(value))).thenReturn(Double.toString(value));
- }
-
- @NavigationSection(NavigationSection.RESOURCE_TAB)
- private static class MyExtension implements Page {
- public String getId() {
- return "my-extension";
- }
-
- public String getTitle() {
- return "My extension";
- }
- }
-
- @NavigationSection(NavigationSection.RESOURCE_TAB)
- @UserRole(UserRole.USER)
- private static class MyExtensionWithRole implements Page {
- public String getId() {
- return "my-extension-with-permission";
- }
-
- public String getTitle() {
- return "My extension with permission";
- }
- }
-
- @NavigationSection(NavigationSection.RESOURCE_TAB)
- private static class IssuesExtension implements Page {
- public String getId() {
- return "issues";
- }
-
- public String getTitle() {
- return "Issues";
- }
- }
-
}