repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/queue/ReportSubmitter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.queue; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.server.ServerSide; import org.sonar.api.web.UserRole; import org.sonar.ce.queue.CeQueue; import org.sonar.ce.queue.CeTaskSubmit; import org.sonar.ce.task.CeTask; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.server.component.ComponentCreationData; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.component.NewComponent; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.project.ProjectDefaultVisibility; import org.sonar.server.project.Visibility; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.defaultIfBlank; import static org.sonar.server.component.NewComponent.newComponentBuilder; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; @ServerSide public class ReportSubmitter { private final CeQueue queue; private final UserSession userSession; private final ComponentUpdater componentUpdater; private final PermissionTemplateService permissionTemplateService; private final DbClient dbClient; private final BranchSupport branchSupport; private final ProjectDefaultVisibility projectDefaultVisibility; public ReportSubmitter(CeQueue queue, UserSession userSession, ComponentUpdater componentUpdater, PermissionTemplateService permissionTemplateService, DbClient dbClient, BranchSupport branchSupport, ProjectDefaultVisibility projectDefaultVisibility) { this.queue = queue; this.userSession = userSession; this.componentUpdater = componentUpdater; this.permissionTemplateService = permissionTemplateService; this.dbClient = dbClient; this.branchSupport = branchSupport; this.projectDefaultVisibility = projectDefaultVisibility; } public CeTask submit(String projectKey, @Nullable String projectName, Map<String, String> characteristics, InputStream reportInput) { try (DbSession dbSession = dbClient.openSession(false)) { ComponentCreationData componentCreationData = null; // Note: when the main branch is analyzed, the characteristics may or may not have the branch name, so componentKey#isMainBranch is not // reliable! BranchSupport.ComponentKey componentKey = branchSupport.createComponentKey(projectKey, characteristics); Optional<ComponentDto> mainBranchComponentOpt = dbClient.componentDao().selectByKey(dbSession, componentKey.getKey()); ComponentDto mainBranchComponent; if (mainBranchComponentOpt.isPresent()) { mainBranchComponent = mainBranchComponentOpt.get(); validateProject(dbSession, mainBranchComponent, projectKey); } else { componentCreationData = createProject(dbSession, componentKey.getKey(), projectName); mainBranchComponent = componentCreationData.mainBranchComponent(); } BranchDto mainBranch = dbClient.branchDao().selectByUuid(dbSession, mainBranchComponent.branchUuid()) .orElseThrow(() -> new IllegalStateException("Couldn't find the main branch of the project")); ComponentDto branchComponent; if (isMainBranch(componentKey, mainBranch)) { branchComponent = mainBranchComponent; } else if(componentKey.getBranchName().isPresent()) { branchComponent = dbClient.componentDao().selectByKeyAndBranch(dbSession, componentKey.getKey(), componentKey.getBranchName().get()) .orElseGet(() -> branchSupport.createBranchComponent(dbSession, componentKey, mainBranchComponent, mainBranch)); } else { branchComponent = dbClient.componentDao().selectByKeyAndPullRequest(dbSession, componentKey.getKey(), componentKey.getPullRequestKey().get()) .orElseGet(() -> branchSupport.createBranchComponent(dbSession, componentKey, mainBranchComponent, mainBranch)); } if (componentCreationData != null) { componentUpdater.commitAndIndex(dbSession, componentCreationData); } else { dbSession.commit(); } checkScanPermission(branchComponent); return submitReport(dbSession, reportInput, branchComponent, mainBranch, characteristics); } } private static boolean isMainBranch(BranchSupport.ComponentKey componentKey, BranchDto mainBranch) { if (componentKey.isMainBranch()) { return true; } return componentKey.getBranchName().isPresent() && componentKey.getBranchName().get().equals(mainBranch.getKey()); } private void checkScanPermission(ComponentDto project) { // this is a specific and inconsistent behavior. For legacy reasons, "technical users" // defined with global scan permission should be able to analyze a project even if // they don't have the direct permission on the project. // That means that dropping the permission on the project does not have any effects // if user has still the global permission if (!userSession.hasComponentPermission(UserRole.SCAN, project) && !userSession.hasPermission(GlobalPermission.SCAN)) { throw insufficientPrivilegesException(); } } private void validateProject(DbSession dbSession, ComponentDto component, String rawProjectKey) { List<String> errors = new ArrayList<>(); if (!Qualifiers.PROJECT.equals(component.qualifier()) || !Scopes.PROJECT.equals(component.scope())) { errors.add(format("Component '%s' is not a project", rawProjectKey)); } if (!component.branchUuid().equals(component.uuid())) { // Project key is already used as a module of another project ComponentDto anotherBaseProject = dbClient.componentDao().selectOrFailByUuid(dbSession, component.branchUuid()); errors.add(format("The project '%s' is already defined in SonarQube but as a module of project '%s'. " + "If you really want to stop directly analysing project '%s', please first delete it from SonarQube and then relaunch the analysis of project '%s'.", rawProjectKey, anotherBaseProject.getKey(), anotherBaseProject.getKey(), rawProjectKey)); } if (!errors.isEmpty()) { throw BadRequestException.create(errors); } } private ComponentCreationData createProject(DbSession dbSession, String projectKey, @Nullable String projectName) { userSession.checkPermission(GlobalPermission.PROVISION_PROJECTS); String userUuid = userSession.getUuid(); String userName = userSession.getLogin(); boolean wouldCurrentUserHaveScanPermission = permissionTemplateService.wouldUserHaveScanPermissionWithDefaultTemplate(dbSession, userUuid, projectKey); if (!wouldCurrentUserHaveScanPermission) { throw insufficientPrivilegesException(); } NewComponent newProject = newComponentBuilder() .setKey(projectKey) .setName(defaultIfBlank(projectName, projectKey)) .setQualifier(Qualifiers.PROJECT) .setPrivate(getDefaultVisibility(dbSession).isPrivate()) .build(); return componentUpdater.createWithoutCommit(dbSession, newProject, userUuid, userName); } private Visibility getDefaultVisibility(DbSession dbSession) { return projectDefaultVisibility.get(dbSession); } private CeTask submitReport(DbSession dbSession, InputStream reportInput, ComponentDto branch, BranchDto mainBranch, Map<String, String> characteristics) { CeTaskSubmit.Builder submit = queue.prepareSubmit(); // the report file must be saved before submitting the task dbClient.ceTaskInputDao().insert(dbSession, submit.getUuid(), reportInput); dbSession.commit(); submit.setType(CeTaskTypes.REPORT); submit.setComponent(CeTaskSubmit.Component.fromDto(branch.uuid(), mainBranch.getUuid())); submit.setSubmitterUuid(userSession.getUuid()); submit.setCharacteristics(characteristics); return queue.submit(submit.build()); } }
9,152
46.671875
158
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/queue/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.queue; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/ActivityAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import java.util.Collections; import java.util.Date; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.StreamSupport; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.jetbrains.annotations.NotNull; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.Paging; import org.sonar.api.web.UserRole; import org.sonar.ce.task.taskprocessor.CeTaskProcessor; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskQuery; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentQuery; import org.sonar.db.entity.EntityDto; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Ce; import org.sonarqube.ws.Ce.ActivityResponse; import org.sonarqube.ws.Common; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.Boolean.parseBoolean; import static java.lang.Integer.max; import static java.lang.Integer.parseInt; import static java.lang.String.format; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toSet; import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY; import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime; import static org.sonar.api.utils.DateUtils.parseStartingDateOrDateTime; import static org.sonar.db.Pagination.forPage; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_COMPONENT; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_MAX_EXECUTED_AT; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_MIN_SUBMITTED_AT; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_ONLY_CURRENTS; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_STATUS; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_TYPE; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ActivityAction implements CeWsAction { private static final int MAX_PAGE_SIZE = 1000; private static final String[] POSSIBLE_QUALIFIERS = new String[]{Qualifiers.PROJECT, Qualifiers.APP, Qualifiers.VIEW}; private static final String INVALID_QUERY_PARAM_ERROR_MESSAGE = "%s and %s must not be set at the same time"; private final UserSession userSession; private final DbClient dbClient; private final TaskFormatter formatter; private final Set<String> taskTypes; public ActivityAction(UserSession userSession, DbClient dbClient, TaskFormatter formatter, CeTaskProcessor[] taskProcessors) { this.userSession = userSession; this.dbClient = dbClient; this.formatter = formatter; this.taskTypes = new LinkedHashSet<>(); for (CeTaskProcessor taskProcessor : taskProcessors) { taskTypes.addAll(taskProcessor.getHandledCeTaskTypes()); } } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("activity") .setDescription(format("Search for tasks.<br> " + "Requires the system administration permission, " + "or project administration permission if %s is set.", PARAM_COMPONENT)) .setResponseExample(getClass().getResource("activity-example.json")) .setHandler(this) .setChangelog( new Change("5.5", "it's no more possible to specify the page parameter."), new Change("6.1", "field \"logs\" is deprecated and its value is always false"), new Change("6.6", "fields \"branch\" and \"branchType\" added"), new Change("7.1", "field \"pullRequest\" added"), new Change("7.6", format("The use of module keys in parameters '%s' is deprecated", TEXT_QUERY)), new Change("8.8", "field \"logs\" is dropped"), new Change("10.0", "Remove deprecated field 'componentId'"), new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("10.1", "Warnings field will be now be filled (it was always empty in the past).") ) .setSince("5.2"); action.createParam(PARAM_COMPONENT) .setDescription("Key of the component (project) to filter on") .setExampleValue("projectKey") .setSince("8.0"); action.createParam(TEXT_QUERY) .setDescription(format("Limit search to: <ul>" + "<li>component names that contain the supplied string</li>" + "<li>component keys that are exactly the same as the supplied string</li>" + "<li>task ids that are exactly the same as the supplied string</li>" + "</ul>")) .setExampleValue("Apache") .setSince("5.5"); action.createParam(PARAM_STATUS) .setDescription("Comma separated list of task statuses") .setPossibleValues(ImmutableList.builder() .addAll(asList(CeActivityDto.Status.values())) .addAll(asList(CeQueueDto.Status.values())).build()) .setExampleValue(Joiner.on(",").join(CeQueueDto.Status.IN_PROGRESS, CeActivityDto.Status.SUCCESS)) // activity statuses by default to be backward compatible // queued tasks have been added in 5.5 .setDefaultValue(Joiner.on(",").join(CeActivityDto.Status.values())); action.createParam(PARAM_ONLY_CURRENTS) .setDescription("Filter on the last tasks (only the most recent finished task by project)") .setBooleanPossibleValues() .setDefaultValue("false"); action.createParam(PARAM_TYPE) .setDescription("Task type") .setExampleValue(CeTaskTypes.REPORT) .setPossibleValues(taskTypes); action.createParam(PARAM_MIN_SUBMITTED_AT) .setDescription("Minimum date of task submission (inclusive)") .setExampleValue("2017-10-19T13:00:00+0200"); action.createParam(PARAM_MAX_EXECUTED_AT) .setDescription("Maximum date of end of task processing (inclusive)") .setExampleValue("2017-10-19T13:00:00+0200"); action.createPageSize(100, MAX_PAGE_SIZE); action.createPageParam() .setSince("9.4"); } @Override public void handle(org.sonar.api.server.ws.Request wsRequest, Response wsResponse) throws Exception { ActivityResponse activityResponse = doHandle(toSearchWsRequest(wsRequest)); writeProtobuf(activityResponse, wsRequest, wsResponse); } private ActivityResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { EntityDto entity = loadEntity(dbSession, request); checkPermission(entity); // if a task searched by uuid is found all other parameters are ignored Optional<Ce.Task> taskSearchedById = searchTaskByUuid(dbSession, request); if (taskSearchedById.isPresent()) { return buildResponse( singletonList(taskSearchedById.get()), Collections.emptyList(), Paging.forPageIndex(1).withPageSize(1).andTotal(1), 0); } CeTaskQuery query = buildQuery(dbSession, request, entity); return buildPaginatedResponse(dbSession, query, parseInt(request.getP()), parseInt(request.getPs())); } } @NotNull private ActivityResponse buildPaginatedResponse(DbSession dbSession, CeTaskQuery query, int page, int pageSize) { int totalQueuedTasks = countQueuedTasks(dbSession, query); int totalPastTasks = countPastTasks(dbSession, query); int totalTasks = totalQueuedTasks + totalPastTasks; int pastTasksEffectivePage = calculateEffectivePage(page, pageSize, totalQueuedTasks); validatePagingParameters(page, pageSize, totalTasks); List<Ce.Task> queuedTasks = loadQueuedTasks(dbSession, query, page, pageSize); List<Ce.Task> pastTasks = loadPastTasks(dbSession, query, pastTasksEffectivePage, pageSize); return buildResponse( queuedTasks, pastTasks, Paging.forPageIndex(page).withPageSize(pageSize).andTotal(totalTasks), getItemsInLastPage(pageSize, totalQueuedTasks)); } private static void validatePagingParameters(int page, int pageSize, int totalResults) { if (page > 1) { int firstResultIndex = (page - 1) * pageSize + 1; checkArgument(firstResultIndex <= totalResults, "Can return only the first %s results. %sth result asked.", totalResults, firstResultIndex); } } private static int calculateEffectivePage(int page, int pageSize, int otherDatasetSize) { if (pageSize > 0 && page > 0) { int effectivePage = page - (otherDatasetSize / pageSize); if (getItemsInLastPage(pageSize, otherDatasetSize) > 0) { effectivePage--; } return max(1, effectivePage); } return page; } private static int getItemsInLastPage(int pageSize, int totalItems) { if (totalItems > pageSize) { return totalItems % pageSize; } return 0; } @CheckForNull private EntityDto loadEntity(DbSession dbSession, Request request) { String componentKey = request.getComponent(); if (componentKey != null) { Optional<EntityDto> foundEntity; foundEntity = dbClient.entityDao().selectByKey(dbSession, componentKey); return checkFoundWithOptional(foundEntity, "Component '%s' does not exist", componentKey); } else { return null; } } private void checkPermission(@Nullable EntityDto entity) { // fail fast if not logged in userSession.checkLoggedIn(); if (entity == null) { userSession.checkIsSystemAdministrator(); } else { userSession.checkEntityPermission(UserRole.ADMIN, entity); } } private Optional<Ce.Task> searchTaskByUuid(DbSession dbSession, Request request) { String textQuery = request.getQ(); if (textQuery == null) { return Optional.empty(); } Optional<CeQueueDto> queue = dbClient.ceQueueDao().selectByUuid(dbSession, textQuery); if (queue.isPresent()) { return Optional.of(formatter.formatQueue(dbSession, queue.get())); } Optional<CeActivityDto> activity = dbClient.ceActivityDao().selectByUuid(dbSession, textQuery); return activity.map(ceActivityDto -> formatter.formatActivity(dbSession, ceActivityDto, null)); } private CeTaskQuery buildQuery(DbSession dbSession, Request request, @Nullable EntityDto entity) { CeTaskQuery query = new CeTaskQuery(); query.setType(request.getType()); query.setOnlyCurrents(parseBoolean(request.getOnlyCurrents())); Date minSubmittedAt = parseStartingDateOrDateTime(request.getMinSubmittedAt()); query.setMinSubmittedAt(minSubmittedAt == null ? null : minSubmittedAt.getTime()); Date maxExecutedAt = parseEndingDateOrDateTime(request.getMaxExecutedAt()); query.setMaxExecutedAt(maxExecutedAt == null ? null : maxExecutedAt.getTime()); List<String> statuses = request.getStatus(); if (statuses != null && !statuses.isEmpty()) { query.setStatuses(request.getStatus()); } String componentQuery = request.getQ(); if (entity != null) { query.setEntityUuid(entity.getUuid()); } else if (componentQuery != null) { query.setEntityUuids(loadEntities(dbSession, componentQuery).stream() .map(EntityDto::getUuid) .toList()); } return query; } private List<EntityDto> loadEntities(DbSession dbSession, String componentQuery) { ComponentQuery componentDtoQuery = ComponentQuery.builder() .setNameOrKeyQuery(componentQuery) .setQualifiers(POSSIBLE_QUALIFIERS) .build(); List<ComponentDto> componentDtos = dbClient.componentDao().selectByQuery(dbSession, componentDtoQuery, 0, CeTaskQuery.MAX_COMPONENT_UUIDS); return dbClient.entityDao().selectByKeys(dbSession, componentDtos.stream().map(ComponentDto::getKey).collect(toSet())); } private Integer countQueuedTasks(DbSession dbSession, CeTaskQuery query) { return dbClient.ceQueueDao().countByQuery(dbSession, query); } private List<Ce.Task> loadQueuedTasks(DbSession dbSession, CeTaskQuery query, int page, int pageSize) { List<CeQueueDto> dtos = dbClient.ceQueueDao().selectByQueryInDescOrder(dbSession, query, page, pageSize); return formatter.formatQueue(dbSession, dtos); } private Integer countPastTasks(DbSession dbSession, CeTaskQuery query) { return dbClient.ceActivityDao().countByQuery(dbSession, query); } private List<Ce.Task> loadPastTasks(DbSession dbSession, CeTaskQuery query, int page, int pageSize) { List<CeActivityDto> dtos = dbClient.ceActivityDao().selectByQuery(dbSession, query, forPage(page).andSize(pageSize)); return formatter.formatActivity(dbSession, dtos); } private static ActivityResponse buildResponse(Iterable<Ce.Task> queuedTasks, Iterable<Ce.Task> pastTasks, Paging paging, int offset) { Ce.ActivityResponse.Builder wsResponseBuilder = Ce.ActivityResponse.newBuilder(); Set<String> pastIds = StreamSupport .stream(pastTasks.spliterator(), false) .map(Ce.Task::getId) .collect(toSet()); int nbInsertedTasks = 0; for (Ce.Task queuedTask : queuedTasks) { if (nbInsertedTasks < paging.pageSize() && !pastIds.contains(queuedTask.getId())) { wsResponseBuilder.addTasks(queuedTask); nbInsertedTasks++; } } int pastTasksIndex = nbInsertedTasks; for (Ce.Task pastTask : pastTasks) { if (nbInsertedTasks < paging.pageSize() && pastTasksIndex >= offset) { wsResponseBuilder.addTasks(pastTask); nbInsertedTasks++; } pastTasksIndex++; } wsResponseBuilder.setPaging(Common.Paging.newBuilder() .setPageIndex(paging.pageIndex()) .setPageSize(paging.pageSize()) .setTotal(paging.total())); return wsResponseBuilder.build(); } private static Request toSearchWsRequest(org.sonar.api.server.ws.Request request) { Request activityWsRequest = new Request() .setComponent(request.param(PARAM_COMPONENT)) .setQ(request.param(TEXT_QUERY)) .setStatus(request.paramAsStrings(PARAM_STATUS)) .setType(request.param(PARAM_TYPE)) .setMinSubmittedAt(request.param(PARAM_MIN_SUBMITTED_AT)) .setMaxExecutedAt(request.param(PARAM_MAX_EXECUTED_AT)) .setOnlyCurrents(String.valueOf(request.paramAsBoolean(PARAM_ONLY_CURRENTS))) .setPs(String.valueOf(request.mandatoryParamAsInt(Param.PAGE_SIZE))) .setP(String.valueOf(request.mandatoryParamAsInt(Param.PAGE))); checkRequest(activityWsRequest.getComponent() == null || activityWsRequest.getQ() == null, INVALID_QUERY_PARAM_ERROR_MESSAGE, PARAM_COMPONENT, TEXT_QUERY); return activityWsRequest; } private static class Request { private String component; private String maxExecutedAt; private String minSubmittedAt; private String onlyCurrents; private String p; private String ps; private String q; private List<String> status; private String type; Request() { // Nothing to do } /** * Example value: "sample:src/main/xoo/sample/Sample2.xoo" */ private Request setComponent(@Nullable String component) { this.component = component; return this; } @CheckForNull private String getComponent() { return component; } /** * Example value: "2017-10-19T13:00:00+0200" */ private Request setMaxExecutedAt(@Nullable String maxExecutedAt) { this.maxExecutedAt = maxExecutedAt; return this; } @CheckForNull private String getMaxExecutedAt() { return maxExecutedAt; } /** * Example value: "2017-10-19T13:00:00+0200" */ private Request setMinSubmittedAt(@Nullable String minSubmittedAt) { this.minSubmittedAt = minSubmittedAt; return this; } @CheckForNull private String getMinSubmittedAt() { return minSubmittedAt; } /** * Possible values: * <ul> * <li>"true"</li> * <li>"false"</li> * <li>"yes"</li> * <li>"no"</li> * </ul> */ private Request setOnlyCurrents(String onlyCurrents) { this.onlyCurrents = onlyCurrents; return this; } private String getOnlyCurrents() { return onlyCurrents; } /** * Example value: "20" */ private Request setPs(String ps) { this.ps = ps; return this; } private String getPs() { return ps; } /** * Example value: "1" */ private Request setP(String p) { this.p = p; return this; } private String getP() { return p; } /** * Example value: "Apache" */ private Request setQ(@Nullable String q) { this.q = q; return this; } @CheckForNull private String getQ() { return q; } /** * Example value: "IN_PROGRESS,SUCCESS" * Possible values: * <ul> * <li>"SUCCESS"</li> * <li>"FAILED"</li> * <li>"CANCELED"</li> * <li>"PENDING"</li> * <li>"IN_PROGRESS"</li> * </ul> */ private Request setStatus(@Nullable List<String> status) { this.status = status; return this; } @CheckForNull private List<String> getStatus() { return status; } /** * Example value: "REPORT" * Possible values: * <ul> * <li>"REPORT"</li> * </ul> */ private Request setType(@Nullable String type) { this.type = type; return this; } @CheckForNull private String getType() { return type; } } }
18,916
35.170172
146
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/ActivityStatusAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.entity.EntityDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import org.sonar.server.ws.KeyExamples; import org.sonarqube.ws.Ce.ActivityStatusWsResponse; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_COMPONENT; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ActivityStatusAction implements CeWsAction { private final UserSession userSession; private final DbClient dbClient; private final ComponentFinder componentFinder; private final System2 system2; public ActivityStatusAction(UserSession userSession, DbClient dbClient, ComponentFinder componentFinder, System2 system2) { this.userSession = userSession; this.dbClient = dbClient; this.componentFinder = componentFinder; this.system2 = system2; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction("activity_status") .setDescription("Returns CE activity related metrics.<br>" + "Requires 'Administer System' permission or 'Administer' rights on the specified project.") .setSince("5.5") .setResponseExample(getClass().getResource("activity_status-example.json")) .setHandler(this); action.createParam(PARAM_COMPONENT) .setDescription("Key of the component (project) to filter on") .setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001); action.setChangelog( new Change("6.6", "New field 'inProgress' in response"), new Change("7.8", "New field 'pendingTime' in response, only included when there are pending tasks"), new Change("8.8", "Parameter 'componentId' is now deprecated."), new Change("8.8", "Parameter 'componentKey' is now removed. Please use parameter 'component' instead."), new Change("10.0", "Remove deprecated field 'componentId'")); } @Override public void handle(org.sonar.api.server.ws.Request request, Response response) throws Exception { ActivityStatusWsResponse activityStatusResponse = doHandle(toWsRequest(request)); writeProtobuf(activityStatusResponse, request, response); } private ActivityStatusWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { Optional<EntityDto> entity = searchEntity(dbSession, request); String entityUuid = entity.map(EntityDto::getUuid).orElse(null); checkPermissions(entity.orElse(null)); int pendingCount = dbClient.ceQueueDao().countByStatusAndEntityUuid(dbSession, CeQueueDto.Status.PENDING, entityUuid); int inProgressCount = dbClient.ceQueueDao().countByStatusAndEntityUuid(dbSession, CeQueueDto.Status.IN_PROGRESS, entityUuid); int failingCount = dbClient.ceActivityDao().countLastByStatusAndEntityUuid(dbSession, CeActivityDto.Status.FAILED, entityUuid); Optional<Long> creationDate = dbClient.ceQueueDao().selectCreationDateOfOldestPendingByEntityUuid(dbSession, entityUuid); ActivityStatusWsResponse.Builder builder = ActivityStatusWsResponse.newBuilder() .setPending(pendingCount) .setInProgress(inProgressCount) .setFailing(failingCount); creationDate.ifPresent(d -> { long ageOfOldestPendingTime = system2.now() - d; builder.setPendingTime(ageOfOldestPendingTime); }); return builder.build(); } } private Optional<EntityDto> searchEntity(DbSession dbSession, Request request) { EntityDto entity = null; if (request.getComponentKey() != null) { entity = componentFinder.getEntityByKey(dbSession, request.getComponentKey()); } return Optional.ofNullable(entity); } private void checkPermissions(@Nullable EntityDto entity) { if (entity != null) { userSession.checkEntityPermission(UserRole.ADMIN, entity); } else { userSession.checkIsSystemAdministrator(); } } private static Request toWsRequest(org.sonar.api.server.ws.Request request) { return new Request(request.param(PARAM_COMPONENT)); } private static class Request { private final String componentKey; Request(@Nullable String componentKey) { this.componentKey = componentKey; } @CheckForNull public String getComponentKey() { return componentKey; } } }
5,630
38.65493
133
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/AnalysisStatusAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeTaskMessageDto; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.component.BranchDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import org.sonar.server.ws.KeyExamples; import org.sonarqube.ws.Ce.AnalysisStatusWsResponse; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_BRANCH; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_COMPONENT; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_PULL_REQUEST; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class AnalysisStatusAction implements CeWsAction { private final UserSession userSession; private final DbClient dbClient; private final ComponentFinder componentFinder; public AnalysisStatusAction(UserSession userSession, DbClient dbClient, ComponentFinder componentFinder) { this.userSession = userSession; this.dbClient = dbClient; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("analysis_status") .setDescription("Get the analysis status of a given component: a project, branch or pull request.<br>" + "Requires the following permission: 'Browse' on the specified component.") .setSince("7.4") .setResponseExample(getClass().getResource("analysis_status-example.json")) .setInternal(true) .setHandler(this); action.createParam(PARAM_COMPONENT) .setRequired(true) .setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001); action.createParam(PARAM_BRANCH) .setDescription("Branch key") .setExampleValue(KEY_BRANCH_EXAMPLE_001); action.createParam(PARAM_PULL_REQUEST) .setDescription("Pull request id") .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { String projectKey = request.mandatoryParam(PARAM_COMPONENT); String branchKey = request.param(PARAM_BRANCH); String pullRequestKey = request.param(PARAM_PULL_REQUEST); checkRequest(branchKey == null || pullRequestKey == null, "Parameters '%s' and '%s' must not be specified at the same time", PARAM_BRANCH, PARAM_PULL_REQUEST); doHandle(request, response, projectKey, branchKey, pullRequestKey); } private void doHandle(Request request, Response response, String projectKey, @Nullable String branchKey, @Nullable String pullRequestKey) { try (DbSession dbSession = dbClient.openSession(false)) { ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey); userSession.checkEntityPermission(UserRole.USER, project); BranchDto branch = componentFinder.getBranchOrPullRequest(dbSession, project, branchKey, pullRequestKey); AnalysisStatusWsResponse.Builder responseBuilder = AnalysisStatusWsResponse.newBuilder(); CeActivityDto lastActivity = dbClient.ceActivityDao() .selectLastByComponentUuidAndTaskType(dbSession, branch.getUuid(), CeTaskTypes.REPORT).orElse(null); responseBuilder.setComponent(formatComponent(dbSession, project, lastActivity, branchKey, pullRequestKey)); writeProtobuf(responseBuilder.build(), request, response); } } private AnalysisStatusWsResponse.Component formatComponent(DbSession dbSession, ProjectDto project, @Nullable CeActivityDto lastActivity, @Nullable String branchKey, @Nullable String pullRequestKey) { AnalysisStatusWsResponse.Component.Builder builder = AnalysisStatusWsResponse.Component.newBuilder() .setKey(project.getKey()) .setName(project.getName()); if (branchKey != null) { builder.setBranch(branchKey); } else if (pullRequestKey != null) { builder.setPullRequest(pullRequestKey); } if (lastActivity == null) { return builder.build(); } List<CeTaskMessageDto> warnings; String userUuid = userSession.getUuid(); if (userUuid != null) { warnings = dbClient.ceTaskMessageDao().selectNonDismissedByUserAndTask(dbSession, lastActivity.getUuid(), userUuid); } else { warnings = lastActivity.getCeTaskMessageDtos(); } List<AnalysisStatusWsResponse.Warning> result = warnings.stream().map(dto -> AnalysisStatusWsResponse.Warning.newBuilder() .setKey(dto.getUuid()) .setMessage(dto.getMessage()) .setDismissable(dto.getType().isDismissible()) .build()) .toList(); builder.addAllWarnings(result); return builder.build(); } }
6,026
40.565517
141
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/CancelAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import java.util.Optional; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.ce.queue.CeQueue; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.component.ComponentDto; import org.sonar.server.user.UserSession; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; public class CancelAction implements CeWsAction { public static final String PARAM_TASK_ID = "id"; private final UserSession userSession; private final DbClient dbClient; private final CeQueue queue; public CancelAction(UserSession userSession, DbClient dbClient, CeQueue queue) { this.userSession = userSession; this.dbClient = dbClient; this.queue = queue; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("cancel") .setDescription("Cancels a pending task.<br/>" + "In-progress tasks cannot be canceled.<br/>" + "Requires one of the following permissions:" + "<ul>" + "<li>'Administer System'</li>" + "<li>'Administer' rights on the project related to the task</li>" + "</ul>") .setInternal(true) .setPost(true) .setSince("5.2") .setHandler(this); action .createParam(PARAM_TASK_ID) .setRequired(true) .setDescription("Id of the task to cancel.") .setExampleValue(Uuids.UUID_EXAMPLE_01); } @Override public void handle(Request wsRequest, Response wsResponse) { String taskId = wsRequest.mandatoryParam(PARAM_TASK_ID); try (DbSession dbSession = dbClient.openSession(false)) { Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskId); queueDto.ifPresent(dto -> { checkPermission(dbSession, dto); queue.cancel(dbSession, dto); }); } wsResponse.noContent(); } private void checkPermission(DbSession dbSession, CeQueueDto ceQueueDto) { if (userSession.isSystemAdministrator()) { return; } String componentUuid = ceQueueDto.getComponentUuid(); if (componentUuid == null) { throw insufficientPrivilegesException(); } Optional<ComponentDto> component = dbClient.componentDao().selectByUuid(dbSession, componentUuid); if (!component.isPresent()) { throw insufficientPrivilegesException(); } userSession.checkComponentPermission(UserRole.ADMIN, component.get()); } }
3,529
33.950495
102
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/CancelAllAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.server.user.UserSession; public class CancelAllAction implements CeWsAction { private final UserSession userSession; private final CeQueue queue; public CancelAllAction(UserSession userSession, CeQueue queue) { this.userSession = userSession; this.queue = queue; } @Override public void define(WebService.NewController controller) { controller.createAction("cancel_all") .setDescription("Cancels all pending tasks. Requires system administration permission. In-progress tasks are not canceled.") .setInternal(true) .setPost(true) .setSince("5.2") .setHandler(this); } @Override public void handle(Request wsRequest, Response wsResponse) { userSession.checkIsSystemAdministrator(); queue.cancelAll(); wsResponse.noContent(); } }
1,859
32.818182
130
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/CeWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.sonar.api.server.ws.WebService; public class CeWs implements WebService { public static final String ENDPOINT = "api/ce"; private final CeWsAction[] actions; public CeWs(CeWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context .createController(ENDPOINT) .setDescription("Get information on Compute Engine tasks."); for (CeWsAction action : actions) { action.define(controller); } controller.done(); } }
1,425
30.688889
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/CeWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.sonar.api.server.ws.WebService; import org.sonar.server.ws.WsAction; /** * Used by {@link CeWs} to loop over all its actions */ public interface CeWsAction extends WsAction { @Override void define(WebService.NewController controller); }
1,131
34.375
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/CeWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.sonar.core.platform.Module; import org.sonar.server.ce.queue.BranchSupport; import org.sonar.server.ce.queue.ReportSubmitter; public class CeWsModule extends Module { @Override protected void configureModule() { add( BranchSupport.class, ReportSubmitter.class, CeWs.class, ActivityAction.class, ActivityStatusAction.class, AnalysisStatusAction.class, CancelAction.class, CancelAllAction.class, ComponentAction.class, InfoAction.class, IsQueueEmptyWs.class, IndexationStatusAction.class, PauseAction.class, ResumeAction.class, SubmitAction.class, TaskFormatter.class, TaskAction.class, TaskTypesAction.class, WorkerCountAction.class, DismissAnalysisWarningAction.class); } }
1,693
30.962264
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/CeWsParameters.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; public class CeWsParameters { public static final String ACTION_WORKER_COUNT = "worker_count"; public static final String PARAM_COMPONENT = "component"; public static final String PARAM_TYPE = "type"; public static final String PARAM_STATUS = "status"; public static final String PARAM_ONLY_CURRENTS = "onlyCurrents"; public static final String PARAM_MIN_SUBMITTED_AT = "minSubmittedAt"; public static final String PARAM_MAX_EXECUTED_AT = "maxExecutedAt"; public static final String PARAM_BRANCH = "branch"; public static final String PARAM_PULL_REQUEST = "pullRequest"; private CeWsParameters() { // prevent instantiation } }
1,533
37.35
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/ComponentAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import java.util.List; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskQuery; import org.sonar.db.component.ComponentDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import org.sonar.server.ws.KeyExamples; import org.sonarqube.ws.Ce; import org.sonarqube.ws.Ce.ComponentResponse; import static java.lang.String.format; import static org.sonar.db.Pagination.forPage; import static org.sonar.server.ce.ws.CeWsParameters.PARAM_COMPONENT; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ComponentAction implements CeWsAction { private final UserSession userSession; private final DbClient dbClient; private final TaskFormatter formatter; private final ComponentFinder componentFinder; public ComponentAction(UserSession userSession, DbClient dbClient, TaskFormatter formatter, ComponentFinder componentFinder) { this.userSession = userSession; this.dbClient = dbClient; this.formatter = formatter; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("component") .setDescription("Get the pending tasks, in-progress tasks and the last executed task of a given component (usually a project).<br>" + "Requires the following permission: 'Browse' on the specified component.") .setSince("5.2") .setResponseExample(getClass().getResource("component-example.json")) .setChangelog( new Change("6.1", "field \"logs\" is deprecated and its value is always false"), new Change("6.6", "fields \"branch\" and \"branchType\" added"), new Change("7.6", format("The use of module keys in parameter \"%s\" is deprecated", PARAM_COMPONENT)), new Change("8.8", "field \"logs\" is dropped"), new Change("8.8", "Deprecated parameter 'componentId' has been removed."), new Change("8.8", "Parameter 'component' is now required.")) .setHandler(this); action.createParam(PARAM_COMPONENT) .setRequired(true) .setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request wsRequest, Response wsResponse) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto component = loadComponent(dbSession, wsRequest); userSession.checkComponentPermission(UserRole.USER, component); List<CeQueueDto> queueDtos = dbClient.ceQueueDao().selectByEntityUuid(dbSession, component.uuid()); CeTaskQuery activityQuery = new CeTaskQuery() .setEntityUuid(component.uuid()) .setOnlyCurrents(true); List<CeActivityDto> activityDtos = dbClient.ceActivityDao().selectByQuery(dbSession, activityQuery, forPage(1).andSize(1)); Ce.ComponentResponse.Builder wsResponseBuilder = ComponentResponse.newBuilder(); wsResponseBuilder.addAllQueue(formatter.formatQueue(dbSession, queueDtos)); if (activityDtos.size() == 1) { wsResponseBuilder.setCurrent(formatter.formatActivity(dbSession, activityDtos.get(0), null)); } writeProtobuf(wsResponseBuilder.build(), wsRequest, wsResponse); } } private ComponentDto loadComponent(DbSession dbSession, Request wsRequest) { String componentKey = wsRequest.mandatoryParam(PARAM_COMPONENT); return componentFinder.getByKey(dbSession, componentKey); } }
4,623
43.038095
139
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/DismissAnalysisWarningAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import java.util.Optional; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeTaskMessageDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDismissedMessageDto; import org.sonar.db.user.UserDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.user.UserSession; import static java.lang.String.format; import static java.util.Objects.requireNonNull; import static org.sonar.server.exceptions.NotFoundException.checkFound; public class DismissAnalysisWarningAction implements CeWsAction { private static final String MESSAGE_NOT_FOUND = "Message '%s' not found."; private static final String MESSAGE_CANNOT_BE_DISMISSED = "Message '%s' cannot be dismissed."; private static final String PARAM_COMPONENT_KEY = "component"; private static final String PARAM_MESSAGE_KEY = "warning"; private final UserSession userSession; private final DbClient dbClient; private final ComponentFinder componentFinder; public DismissAnalysisWarningAction(UserSession userSession, DbClient dbClient, ComponentFinder componentFinder) { this.userSession = userSession; this.dbClient = dbClient; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller .createAction("dismiss_analysis_warning") .setPost(true) .setDescription("Permanently dismiss a specific analysis warning. Requires authentication and 'Browse' permission on the specified project.") .setSince("8.5") .setInternal(true) .setHandler(this); action.createParam(PARAM_COMPONENT_KEY) .setDescription("Key of the project") .setRequired(true) .setExampleValue(Uuids.UUID_EXAMPLE_01); action.createParam(PARAM_MESSAGE_KEY) .setDescription("Key of the warning") .setRequired(true) .setExampleValue(Uuids.UUID_EXAMPLE_02); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); String userLogin = requireNonNull(userSession.getLogin()); String projectKey = request.mandatoryParam(PARAM_COMPONENT_KEY); String messageKey = request.mandatoryParam(PARAM_MESSAGE_KEY); try (DbSession dbSession = dbClient.openSession(false)) { UserDto user = getUser(dbSession, userLogin); ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey); userSession.checkEntityPermission(UserRole.USER, project); CeTaskMessageDto messageDto = dbClient.ceTaskMessageDao() .selectByUuid(dbSession, messageKey) .orElseThrow(() -> new NotFoundException(format(MESSAGE_NOT_FOUND, messageKey))); if (!messageDto.getType().isDismissible()) { throw new IllegalArgumentException(format(MESSAGE_CANNOT_BE_DISMISSED, messageKey)); } Optional<UserDismissedMessageDto> result = dbClient.userDismissedMessagesDao().selectByUserAndProjectAndMessageType(dbSession, user, project, messageDto.getType()); if (!result.isPresent()) { dbClient.userDismissedMessagesDao().insert(dbSession, new UserDismissedMessageDto() .setUuid(Uuids.create()) .setUserUuid(user.getUuid()) .setProjectUuid(project.getUuid()) .setCeMessageType(messageDto.getType())); dbSession.commit(); } response.noContent(); } } private UserDto getUser(DbSession dbSession, String userLogin) { return checkFound(dbClient.userDao().selectByLogin(dbSession, userLogin), "User '%s' not found", userLogin); } }
4,752
39.974138
170
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/IndexationStatusAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.issue.index.IssueSyncProgress; import org.sonarqube.ws.Ce.IndexationStatusWsResponse; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class IndexationStatusAction implements CeWsAction { private final IssueIndexSyncProgressChecker issueIndexSyncChecker; private final DbClient dbClient; public IndexationStatusAction(DbClient dbClient, IssueIndexSyncProgressChecker issueIndexSyncChecker) { this.dbClient = dbClient; this.issueIndexSyncChecker = issueIndexSyncChecker; } @Override public void define(WebService.NewController controller) { controller.createAction("indexation_status") .setDescription("Returns percentage of completed issue synchronization.") .setResponseExample(getClass().getResource("indexation_status-example.json")) .setHandler(this) .setInternal(true) .setSince("8.4"); } @Override public void handle(Request wsRequest, Response wsResponse) throws Exception { IndexationStatusWsResponse activityResponse = doHandle(); writeProtobuf(activityResponse, wsRequest, wsResponse); } private IndexationStatusWsResponse doHandle() { IssueSyncProgress issueSyncProgress; try (DbSession dbSession = dbClient.openSession(false)) { issueSyncProgress = issueIndexSyncChecker.getIssueSyncProgress(dbSession); } return IndexationStatusWsResponse.newBuilder() .setIsCompleted(issueSyncProgress.isCompleted()) .setPercentCompleted(issueSyncProgress.toPercentCompleted()) .setHasFailures(issueSyncProgress.hasFailures()) .build(); } }
2,733
36.972222
105
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/InfoAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.process.ProcessProperties; import org.sonar.server.user.AbstractUserSession; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; import org.sonar.server.ws.WsUtils; import org.sonarqube.ws.Ce; public class InfoAction implements CeWsAction { private final UserSession userSession; private final SystemPasscode systemPasscode; private final CeQueue ceQueue; public InfoAction(UserSession userSession, SystemPasscode systemPasscode, CeQueue ceQueue) { this.userSession = userSession; this.systemPasscode = systemPasscode; this.ceQueue = ceQueue; } @Override public void define(WebService.NewController controller) { controller.createAction("info") .setDescription("Gets information about Compute Engine. Requires the system administration permission or " + "system passcode (see " + ProcessProperties.Property.WEB_SYSTEM_PASS_CODE + " in sonar.properties).") .setSince("7.2") .setInternal(true) .setHandler(this) .setResponseExample(getClass().getResource("info-example.json")); } @Override public void handle(Request request, Response response) throws Exception { if (!systemPasscode.isValid(request) && !userSession.isSystemAdministrator()) { throw AbstractUserSession.insufficientPrivilegesException(); } Ce.InfoWsResponse.Builder builder = Ce.InfoWsResponse.newBuilder(); CeQueue.WorkersPauseStatus status = ceQueue.getWorkersPauseStatus(); builder.setWorkersPauseStatus(convert(status)); WsUtils.writeProtobuf(builder.build(), request, response); } private static Ce.WorkersPauseStatus convert(CeQueue.WorkersPauseStatus status) { switch (status) { case PAUSING: return Ce.WorkersPauseStatus.PAUSING; case PAUSED: return Ce.WorkersPauseStatus.PAUSED; case RESUMED: return Ce.WorkersPauseStatus.RESUMED; default: throw new IllegalStateException("Unsupported WorkersPauseStatus: " + status); } } }
3,066
36.864198
114
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/IsQueueEmptyWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.apache.commons.io.IOUtils; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.RequestHandler; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import static java.nio.charset.StandardCharsets.UTF_8; /** * Internal WebService with one action */ public class IsQueueEmptyWs implements WebService { public static final String API_ENDPOINT = "api/analysis_reports"; private final IsQueueEmptyAction action; public IsQueueEmptyWs(DbClient dbClient) { this.action = new IsQueueEmptyAction(dbClient); } @Override public void define(Context context) { NewController controller = context .createController(API_ENDPOINT) .setDescription("Get details about Compute Engine tasks."); action.define(controller); controller.done(); } static class IsQueueEmptyAction implements RequestHandler { private final DbClient dbClient; public IsQueueEmptyAction(DbClient dbClient) { this.dbClient = dbClient; } public void define(WebService.NewController controller) { controller .createAction("is_queue_empty") .setDescription("Check if the queue of Compute Engine is empty") .setResponseExample(getClass().getResource("is_queue_empty-example.txt")) .setSince("5.1") .setInternal(true) .setHandler(this); } @Override public void handle(Request request, Response response) throws Exception { boolean isQueueEmpty = false; try (DbSession dbSession = dbClient.openSession(false)) { isQueueEmpty = dbClient.ceQueueDao().selectAllInAscOrder(dbSession).isEmpty(); } catch (Exception e) { // ignore this FP : https://gist.github.com/simonbrandhof/3d98f854d427519ef5b858a73b59585b LoggerFactory.getLogger(getClass()).error("Cannot select rows from ce_queue", e); } IOUtils.write(String.valueOf(isQueueEmpty), response.stream().output(), UTF_8); } } }
2,957
34.214286
98
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/PauseAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.process.ProcessProperties; import org.sonar.server.user.AbstractUserSession; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; public class PauseAction implements CeWsAction { private final UserSession userSession; private final SystemPasscode systemPasscode; private final CeQueue ceQueue; public PauseAction(UserSession userSession, SystemPasscode systemPasscode, CeQueue ceQueue) { this.userSession = userSession; this.systemPasscode = systemPasscode; this.ceQueue = ceQueue; } @Override public void define(WebService.NewController controller) { controller.createAction("pause") .setDescription("Requests pause of Compute Engine workers. Requires the system administration permission or " + "system passcode (see " + ProcessProperties.Property.WEB_SYSTEM_PASS_CODE + " in sonar.properties).") .setSince("7.2") .setInternal(true) .setHandler(this) .setPost(true); } @Override public void handle(Request request, Response response) throws Exception { if (!systemPasscode.isValid(request) && !userSession.isSystemAdministrator()) { throw AbstractUserSession.insufficientPrivilegesException(); } ceQueue.pauseWorkers(); } }
2,312
35.714286
117
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/ResumeAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.ce.queue.CeQueue; import org.sonar.process.ProcessProperties; import org.sonar.server.user.AbstractUserSession; import org.sonar.server.user.SystemPasscode; import org.sonar.server.user.UserSession; public class ResumeAction implements CeWsAction { private final UserSession userSession; private final SystemPasscode systemPasscode; private final CeQueue ceQueue; public ResumeAction(UserSession userSession, SystemPasscode systemPasscode, CeQueue ceQueue) { this.userSession = userSession; this.systemPasscode = systemPasscode; this.ceQueue = ceQueue; } @Override public void define(WebService.NewController controller) { controller.createAction("resume") .setDescription("Resumes pause of Compute Engine workers. Requires the system administration permission or " + "system passcode (see " + ProcessProperties.Property.WEB_SYSTEM_PASS_CODE + " in sonar.properties).") .setSince("7.2") .setInternal(true) .setHandler(this) .setPost(true); } @Override public void handle(Request request, Response response) throws Exception { if (!systemPasscode.isValid(request) && !userSession.isSystemAdministrator()) { throw AbstractUserSession.insufficientPrivilegesException(); } ceQueue.resumeWorkers(); } }
2,315
35.761905
116
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/SubmitAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import java.io.BufferedInputStream; import java.io.InputStream; import java.util.LinkedHashMap; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.ce.task.CeTask; import org.sonar.db.ce.CeTaskCharacteristicDto; import org.sonar.server.ce.queue.ReportSubmitter; import org.sonar.server.ws.WsUtils; import org.sonarqube.ws.Ce; import static org.apache.commons.lang.StringUtils.abbreviate; import static org.apache.commons.lang.StringUtils.defaultIfBlank; import static org.sonar.core.component.ComponentKeys.MAX_COMPONENT_KEY_LENGTH; import static org.sonar.db.component.ComponentValidator.MAX_COMPONENT_NAME_LENGTH; import static org.sonar.server.exceptions.BadRequestException.checkRequest; public class SubmitAction implements CeWsAction { private static final String PARAM_PROJECT_KEY = "projectKey"; private static final String PARAM_PROJECT_NAME = "projectName"; private static final String PARAM_REPORT_DATA = "report"; private static final String PARAM_ANALYSIS_CHARACTERISTIC = "characteristic"; private final ReportSubmitter reportSubmitter; public SubmitAction(ReportSubmitter reportSubmitter) { this.reportSubmitter = reportSubmitter; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("submit") .setDescription("Submits a scanner report to the queue. Report is processed asynchronously. Requires analysis permission. " + "If the project does not exist, then the provisioning permission is also required.") .setPost(true) .setInternal(true) .setSince("5.2") .setHandler(this) .setResponseExample(getClass().getResource("submit-example.json")); action .createParam(PARAM_PROJECT_KEY) .setRequired(true) .setMaximumLength(MAX_COMPONENT_KEY_LENGTH) .setDescription("Key of project") .setExampleValue("my_project"); action .createParam(PARAM_PROJECT_NAME) .setRequired(false) .setDescription("Optional name of the project, used only if the project does not exist yet. If name is longer than %d, it is abbreviated.", MAX_COMPONENT_NAME_LENGTH) .setExampleValue("My Project"); action .createParam(PARAM_REPORT_DATA) .setRequired(true) .setDescription("Report file. Format is not an API, it changes among SonarQube versions."); action .createParam(PARAM_ANALYSIS_CHARACTERISTIC) .setRequired(false) .setDescription("Optional characteristic of the analysis. Can be repeated to define multiple characteristics.") .setExampleValue("branchType=long") .setSince("6.6"); } @Override public void handle(Request wsRequest, Response wsResponse) throws Exception { String projectKey = wsRequest.mandatoryParam(PARAM_PROJECT_KEY); String projectName = abbreviate(defaultIfBlank(wsRequest.param(PARAM_PROJECT_NAME), projectKey), MAX_COMPONENT_NAME_LENGTH); Map<String, String> characteristics = parseTaskCharacteristics(wsRequest); try (InputStream report = new BufferedInputStream(wsRequest.mandatoryParamAsPart(PARAM_REPORT_DATA).getInputStream())) { CeTask task = reportSubmitter.submit(projectKey, projectName, characteristics, report); Ce.SubmitResponse submitResponse = Ce.SubmitResponse.newBuilder() .setTaskId(task.getUuid()) .setProjectId(task.getComponent().get().getUuid()) .build(); WsUtils.writeProtobuf(submitResponse, wsRequest, wsResponse); } } private static Map<String, String> parseTaskCharacteristics(Request wsRequest) { Map<String, String> characteristics = new LinkedHashMap<>(); for (String param : wsRequest.multiParam(PARAM_ANALYSIS_CHARACTERISTIC)) { String[] pair = StringUtils.split(param, "=", 2); checkRequest(pair.length == 2, "Parameter '%s' must be a key-value pair with the format 'key=value'.", PARAM_ANALYSIS_CHARACTERISTIC); checkRequest(!characteristics.containsKey(pair[0]), "Key '%s' was provided twice with parameters '%s'", pair[0], PARAM_ANALYSIS_CHARACTERISTIC); if (CeTaskCharacteristicDto.SUPPORTED_KEYS.contains(pair[0])) { characteristics.put(pair[0], pair[1]); } } return characteristics; } }
5,271
41.516129
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/TaskAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.core.util.Uuids; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.permission.GlobalPermission; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Ce; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class TaskAction implements CeWsAction { public static final String ACTION = "task"; public static final String PARAM_TASK_UUID = "id"; private static final String PARAM_ADDITIONAL_FIELDS = "additionalFields"; private final DbClient dbClient; private final TaskFormatter wsTaskFormatter; private final UserSession userSession; public TaskAction(DbClient dbClient, TaskFormatter wsTaskFormatter, UserSession userSession) { this.dbClient = dbClient; this.wsTaskFormatter = wsTaskFormatter; this.userSession = userSession; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction(ACTION) .setDescription("Give Compute Engine task details such as type, status, duration and associated component.<br/>" + "Requires one of the following permissions: " + "<ul>" + "<li>'Administer' at global or project level</li>" + "<li>'Execute Analysis' at global or project level</li>" + "</ul>" + "Since 6.1, field \"logs\" is deprecated and its value is always false.") .setResponseExample(getClass().getResource("task-example.json")) .setSince("5.2") .setChangelog( new Change("6.6", "fields \"branch\" and \"branchType\" added"), new Change("10.1", "Warnings field will be now always be filled (it is not necessary to mention it explicitly in 'additionalFields'). " + "'additionalFields' value `warning' is deprecated."), new Change("10.1", "'Project Administrator' is added to the list of allowed permissions to access this endpoint")) .setHandler(this); action .createParam(PARAM_TASK_UUID) .setRequired(true) .setDescription("Id of task") .setExampleValue(Uuids.UUID_EXAMPLE_01); action.createParam(PARAM_ADDITIONAL_FIELDS) .setSince("6.1") .setDescription("Comma-separated list of the optional fields to be returned in response.") .setPossibleValues(AdditionalField.possibleValues()); } @Override public void handle(Request wsRequest, Response wsResponse) throws Exception { String taskUuid = wsRequest.mandatoryParam(PARAM_TASK_UUID); try (DbSession dbSession = dbClient.openSession(false)) { Ce.TaskResponse.Builder wsTaskResponse = Ce.TaskResponse.newBuilder(); Optional<CeQueueDto> queueDto = dbClient.ceQueueDao().selectByUuid(dbSession, taskUuid); if (queueDto.isPresent()) { Optional<ComponentDto> component = loadComponent(dbSession, queueDto.get().getComponentUuid()); checkPermission(component); wsTaskResponse.setTask(wsTaskFormatter.formatQueue(dbSession, queueDto.get())); } else { CeActivityDto ceActivityDto = checkFoundWithOptional( dbClient.ceActivityDao().selectByUuid(dbSession, taskUuid), "No activity found for task '%s'", taskUuid); Optional<ComponentDto> component = loadComponent(dbSession, ceActivityDto.getComponentUuid()); checkPermission(component); Set<AdditionalField> additionalFields = AdditionalField.getFromRequest(wsRequest); maskErrorStacktrace(ceActivityDto, additionalFields); wsTaskResponse.setTask( wsTaskFormatter.formatActivity(dbSession, ceActivityDto, extractScannerContext(dbSession, ceActivityDto, additionalFields))); } writeProtobuf(wsTaskResponse.build(), wsRequest, wsResponse); } } private Optional<ComponentDto> loadComponent(DbSession dbSession, @Nullable String projectUuid) { if (projectUuid == null) { return Optional.empty(); } return dbClient.componentDao().selectByUuid(dbSession, projectUuid); } private void checkPermission(Optional<ComponentDto> component) { if (component.isPresent()) { checkComponentPermission(component.get()); } else { userSession.checkIsSystemAdministrator(); } } private void checkComponentPermission(ComponentDto component) { if (userSession.hasPermission(GlobalPermission.ADMINISTER) || userSession.hasPermission(GlobalPermission.SCAN) || userSession.hasComponentPermission(UserRole.ADMIN, component) || userSession.hasComponentPermission(UserRole.SCAN, component)) { return; } throw insufficientPrivilegesException(); } private static void maskErrorStacktrace(CeActivityDto ceActivityDto, Set<AdditionalField> additionalFields) { if (!additionalFields.contains(AdditionalField.STACKTRACE)) { ceActivityDto.setErrorStacktrace(null); } } @CheckForNull private String extractScannerContext(DbSession dbSession, CeActivityDto activityDto, Set<AdditionalField> additionalFields) { if (additionalFields.contains(AdditionalField.SCANNER_CONTEXT)) { return dbClient.ceScannerContextDao().selectScannerContext(dbSession, activityDto.getUuid()) .orElse(null); } return null; } private enum AdditionalField { STACKTRACE("stacktrace"), SCANNER_CONTEXT("scannerContext"), @Deprecated(forRemoval = true, since = "10.1") WARNINGS("warnings"); private final String label; AdditionalField(String label) { this.label = label; } public String getLabel() { return label; } public static Set<AdditionalField> getFromRequest(Request wsRequest) { List<String> strings = wsRequest.paramAsStrings(PARAM_ADDITIONAL_FIELDS); if (strings == null) { return Collections.emptySet(); } return strings.stream() .map(s -> { for (AdditionalField field : AdditionalField.values()) { if (field.label.equalsIgnoreCase(s)) { return field; } } return null; }) .filter(Objects::nonNull) .collect(Collectors.toSet()); } public static Collection<String> possibleValues() { return Arrays.stream(values()) .map(AdditionalField::getLabel) .toList(); } } }
7,936
37.717073
143
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/TaskFormatter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskCharacteristicDto; import org.sonar.db.ce.CeTaskMessageDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.user.UserDto; import org.sonarqube.ws.Ce; import org.sonarqube.ws.Common; import static java.lang.String.format; import static java.util.Collections.singletonList; import static java.util.Optional.ofNullable; import static org.sonar.api.utils.DateUtils.formatDateTime; /** * Converts {@link CeActivityDto} and {@link CeQueueDto} to the protobuf objects * used to write WS responses (see ws-ce.proto in module sonar-ws) */ public class TaskFormatter { private final DbClient dbClient; private final System2 system2; public TaskFormatter(DbClient dbClient, System2 system2) { this.dbClient = dbClient; this.system2 = system2; } public List<Ce.Task> formatQueue(DbSession dbSession, List<CeQueueDto> dtos) { DtoCache cache = DtoCache.forQueueDtos(dbClient, dbSession, dtos); return dtos.stream().map(input -> formatQueue(input, cache)).toList(); } public Ce.Task formatQueue(DbSession dbSession, CeQueueDto queue) { return formatQueue(queue, DtoCache.forQueueDtos(dbClient, dbSession, singletonList(queue))); } private Ce.Task formatQueue(CeQueueDto dto, DtoCache cache) { Ce.Task.Builder builder = Ce.Task.newBuilder(); if (dto.getComponentUuid() != null) { builder.setComponentId(dto.getComponentUuid()); setComponent(builder, dto.getComponentUuid(), cache); } builder.setId(dto.getUuid()); builder.setStatus(Ce.TaskStatus.valueOf(dto.getStatus().name())); builder.setType(dto.getTaskType()); cache.getUser(dto.getSubmitterUuid()).ifPresent(user -> builder.setSubmitterLogin(user.getLogin())); builder.setSubmittedAt(formatDateTime(new Date(dto.getCreatedAt()))); ofNullable(dto.getStartedAt()).map(DateUtils::formatDateTime).ifPresent(builder::setStartedAt); ofNullable(computeExecutionTimeMs(dto)).ifPresent(builder::setExecutionTimeMs); setBranchOrPullRequest(builder, dto.getUuid(), cache); return builder.build(); } public Ce.Task formatActivity(DbSession dbSession, CeActivityDto dto, @Nullable String scannerContext) { return formatActivity(dto, DtoCache.forActivityDtos(dbClient, dbSession, singletonList(dto)), scannerContext); } public List<Ce.Task> formatActivity(DbSession dbSession, List<CeActivityDto> dtos) { DtoCache cache = DtoCache.forActivityDtos(dbClient, dbSession, dtos); return dtos.stream() .map(input -> formatActivity(input, cache, null)) .toList(); } private static Ce.Task formatActivity(CeActivityDto activityDto, DtoCache cache, @Nullable String scannerContext) { Ce.Task.Builder builder = Ce.Task.newBuilder(); builder.setId(activityDto.getUuid()); builder.setStatus(Ce.TaskStatus.valueOf(activityDto.getStatus().name())); builder.setType(activityDto.getTaskType()); ofNullable(activityDto.getNodeName()).ifPresent(builder::setNodeName); ofNullable(activityDto.getComponentUuid()).ifPresent(uuid -> setComponent(builder, uuid, cache).setComponentId(uuid)); String analysisUuid = activityDto.getAnalysisUuid(); ofNullable(analysisUuid).ifPresent(builder::setAnalysisId); setBranchOrPullRequest(builder, activityDto.getUuid(), cache); ofNullable(analysisUuid).ifPresent(builder::setAnalysisId); cache.getUser(activityDto.getSubmitterUuid()).ifPresent(user -> builder.setSubmitterLogin(user.getLogin())); builder.setSubmittedAt(formatDateTime(new Date(activityDto.getSubmittedAt()))); ofNullable(activityDto.getStartedAt()).map(DateUtils::formatDateTime).ifPresent(builder::setStartedAt); ofNullable(activityDto.getExecutedAt()).map(DateUtils::formatDateTime).ifPresent(builder::setExecutedAt); ofNullable(activityDto.getExecutionTimeMs()).ifPresent(builder::setExecutionTimeMs); ofNullable(activityDto.getErrorMessage()).ifPresent(builder::setErrorMessage); ofNullable(activityDto.getErrorStacktrace()).ifPresent(builder::setErrorStacktrace); ofNullable(activityDto.getErrorType()).ifPresent(builder::setErrorType); ofNullable(scannerContext).ifPresent(builder::setScannerContext); builder.setHasScannerContext(activityDto.isHasScannerContext()); List<String> warnings = extractWarningMessages(activityDto); builder.setWarningCount(warnings.size()); warnings.forEach(builder::addWarnings); return builder.build(); } private static Ce.Task.Builder setComponent(Ce.Task.Builder builder, @Nullable String componentUuid, DtoCache componentDtoCache) { ComponentDto componentDto = componentDtoCache.getComponent(componentUuid); if (componentDto == null) { return builder; } builder.setComponentKey(componentDto.getKey()); builder.setComponentName(componentDto.name()); builder.setComponentQualifier(componentDto.qualifier()); return builder; } private static Ce.Task.Builder setBranchOrPullRequest(Ce.Task.Builder builder, String taskUuid, DtoCache componentDtoCache) { componentDtoCache.getBranchKey(taskUuid).ifPresent( b -> { Common.BranchType branchType = componentDtoCache.getBranchType(taskUuid) .orElseThrow(() -> new IllegalStateException(format("Could not find branch type of task '%s'", taskUuid))); switch (branchType) { case BRANCH: builder.setBranchType(branchType); builder.setBranch(b); break; default: throw new IllegalStateException(String.format("Unknown branch type '%s'", branchType)); } }); componentDtoCache.getPullRequest(taskUuid).ifPresent(builder::setPullRequest); return builder; } private static List<String> extractWarningMessages(CeActivityDto dto) { return dto.getCeTaskMessageDtos().stream() .filter(ceTaskMessageDto -> ceTaskMessageDto.getType().isWarning()) .map(CeTaskMessageDto::getMessage) .toList(); } private static class DtoCache { private final Map<String, ComponentDto> componentsByUuid; private final Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid; private final Map<String, UserDto> usersByUuid; private DtoCache(Map<String, ComponentDto> componentsByUuid, Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid, Map<String, UserDto> usersByUuid) { this.componentsByUuid = componentsByUuid; this.characteristicsByTaskUuid = characteristicsByTaskUuid; this.usersByUuid = usersByUuid; } static DtoCache forQueueDtos(DbClient dbClient, DbSession dbSession, Collection<CeQueueDto> ceQueueDtos) { Map<String, ComponentDto> componentsByUuid = dbClient.componentDao().selectByUuids(dbSession, componentUuidsOfCeQueues(ceQueueDtos)) .stream() .collect(Collectors.toMap(ComponentDto::uuid, Function.identity())); Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid = dbClient.ceTaskCharacteristicsDao() .selectByTaskUuids(dbSession, ceQueueDtos.stream().map(CeQueueDto::getUuid).toList()) .stream().collect(MoreCollectors.index(CeTaskCharacteristicDto::getTaskUuid)); Set<String> submitterUuids = ceQueueDtos.stream().map(CeQueueDto::getSubmitterUuid).filter(Objects::nonNull).collect(Collectors.toSet()); Map<String, UserDto> usersByUuid = dbClient.userDao().selectByUuids(dbSession, submitterUuids).stream().collect(Collectors.toMap(UserDto::getUuid, Function.identity())); return new DtoCache(componentsByUuid, characteristicsByTaskUuid, usersByUuid); } private static Set<String> componentUuidsOfCeQueues(Collection<CeQueueDto> ceQueueDtos) { return ceQueueDtos.stream() .filter(Objects::nonNull) .map(CeQueueDto::getComponentUuid) .filter(Objects::nonNull) .collect(Collectors.toSet()); } static DtoCache forActivityDtos(DbClient dbClient, DbSession dbSession, Collection<CeActivityDto> ceActivityDtos) { Map<String, ComponentDto> componentsByUuid = dbClient.componentDao().selectByUuids( dbSession, getComponentUuidsOfCeActivities(ceActivityDtos)) .stream() .collect(Collectors.toMap(ComponentDto::uuid, Function.identity())); Multimap<String, CeTaskCharacteristicDto> characteristicsByTaskUuid = dbClient.ceTaskCharacteristicsDao() .selectByTaskUuids(dbSession, ceActivityDtos.stream().map(CeActivityDto::getUuid).toList()) .stream().collect(MoreCollectors.index(CeTaskCharacteristicDto::getTaskUuid)); Set<String> submitterUuids = ceActivityDtos.stream().map(CeActivityDto::getSubmitterUuid).filter(Objects::nonNull).collect(Collectors.toSet()); Map<String, UserDto> usersByUuid = dbClient.userDao().selectByUuids(dbSession, submitterUuids).stream().collect(Collectors.toMap(UserDto::getUuid, Function.identity())); return new DtoCache(componentsByUuid, characteristicsByTaskUuid, usersByUuid); } private static Set<String> getComponentUuidsOfCeActivities(Collection<CeActivityDto> ceActivityDtos) { return ceActivityDtos.stream() .filter(Objects::nonNull) .map(CeActivityDto::getComponentUuid) .filter(Objects::nonNull) .collect(Collectors.toSet()); } @CheckForNull ComponentDto getComponent(@Nullable String uuid) { if (uuid == null) { return null; } return componentsByUuid.get(uuid); } Optional<String> getBranchKey(String taskUuid) { return characteristicsByTaskUuid.get(taskUuid).stream() .filter(c -> c.getKey().equals(CeTaskCharacteristicDto.BRANCH_KEY)) .map(CeTaskCharacteristicDto::getValue) .findAny(); } Optional<Common.BranchType> getBranchType(String taskUuid) { return characteristicsByTaskUuid.get(taskUuid).stream() .filter(c -> c.getKey().equals(CeTaskCharacteristicDto.BRANCH_TYPE_KEY)) .map(c -> Common.BranchType.valueOf(c.getValue())) .findAny(); } Optional<String> getPullRequest(String taskUuid) { return characteristicsByTaskUuid.get(taskUuid).stream() .filter(c -> c.getKey().equals(CeTaskCharacteristicDto.PULL_REQUEST)) .map(CeTaskCharacteristicDto::getValue) .findAny(); } Optional<UserDto> getUser(@Nullable String userUuid) { if (userUuid == null) { return Optional.empty(); } return Optional.ofNullable(usersByUuid.get(userUuid)); } } /** * now - startedAt */ @CheckForNull private Long computeExecutionTimeMs(CeQueueDto dto) { Long startedAt = dto.getStartedAt(); if (startedAt == null) { return null; } return system2.now() - startedAt; } }
12,209
44.055351
175
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/TaskTypesAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import com.google.common.collect.ImmutableSet; import java.util.Set; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.ce.task.taskprocessor.CeTaskProcessor; import org.sonarqube.ws.Ce; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class TaskTypesAction implements CeWsAction { private final Set<String> taskTypes; public TaskTypesAction(CeTaskProcessor[] taskProcessors) { ImmutableSet.Builder<String> taskTypesBuilder = ImmutableSet.builder(); for (CeTaskProcessor taskProcessor : taskProcessors) { taskTypesBuilder.addAll(taskProcessor.getHandledCeTaskTypes()); } this.taskTypes = taskTypesBuilder.build(); } @Override public void define(WebService.NewController controller) { controller.createAction("task_types") .setDescription("List available task types") .setResponseExample(getClass().getResource("task_types-example.json")) .setSince("5.5") .setInternal(true) .setHandler(this); } @Override public void handle(Request request, Response response) throws Exception { Ce.TaskTypesWsResponse taskTypesWsResponse = Ce.TaskTypesWsResponse.newBuilder() .addAllTaskTypes(taskTypes) .build(); writeProtobuf(taskTypesWsResponse, request, response); } }
2,238
35.112903
84
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/WorkerCountAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import javax.annotation.Nullable; import javax.inject.Inject; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.ce.configuration.WorkerCountProvider; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Ce.WorkerCountResponse; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonar.server.ce.ws.CeWsParameters.ACTION_WORKER_COUNT; public class WorkerCountAction implements CeWsAction { private static final int DEFAULT_WORKER_COUNT = 1; private final UserSession userSession; private final WorkerCountProvider workerCountProvider; @Inject public WorkerCountAction(UserSession userSession, @Nullable WorkerCountProvider workerCountProvider) { this.userSession = userSession; this.workerCountProvider = workerCountProvider; } public WorkerCountAction(UserSession userSession) { this(userSession, null); } @Override public void define(WebService.NewController controller) { controller.createAction(ACTION_WORKER_COUNT) .setDescription("Return number of Compute Engine workers.<br/>" + "Requires the system administration permission") .setResponseExample(getClass().getResource("worker_count-example.json")) .setSince("6.5") .setInternal(true) .setHandler(this); } @Override public void handle(Request wsRequest, Response wsResponse) throws Exception { userSession.checkIsSystemAdministrator(); writeProtobuf(createResponse(), wsRequest, wsResponse); } private WorkerCountResponse createResponse(){ WorkerCountResponse.Builder builder = WorkerCountResponse.newBuilder(); if (workerCountProvider == null) { return builder .setValue(DEFAULT_WORKER_COUNT) .setCanSetWorkerCount(false) .build(); } return builder .setValue(workerCountProvider.get()) .setCanSetWorkerCount(true) .build(); } }
2,859
33.047619
104
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/ce/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.ce.ws; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentCleanerService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component; import java.util.List; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.es.Indexers; import org.sonar.server.es.Indexers.BranchEvent; import org.sonar.server.es.Indexers.EntityEvent; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Collections.singletonList; @ServerSide public class ComponentCleanerService { private final DbClient dbClient; private final Indexers indexers; public ComponentCleanerService(DbClient dbClient, Indexers indexers) { this.dbClient = dbClient; this.indexers = indexers; } public void delete(DbSession dbSession, List<ProjectDto> projects) { for (ProjectDto project : projects) { deleteEntity(dbSession, project); } } public void deleteBranch(DbSession dbSession, BranchDto branch) { if (branch.isMain()) { throw new IllegalArgumentException("Only non-main branches can be deleted"); } dbClient.purgeDao().deleteBranch(dbSession, branch.getUuid()); indexers.commitAndIndexBranches(dbSession, singletonList(branch), BranchEvent.DELETION); } public void deleteEntity(DbSession dbSession, EntityDto entity) { checkArgument(!entity.getQualifier().equals(Qualifiers.SUBVIEW), "Qualifier can't be subview"); dbClient.purgeDao().deleteProject(dbSession, entity.getUuid(), entity.getQualifier(), entity.getName(), entity.getKey()); dbClient.userDao().cleanHomepage(dbSession, entity); if (Qualifiers.PROJECT.equals(entity.getQualifier())) { dbClient.userTokenDao().deleteByProjectUuid(dbSession, entity.getKey(), entity.getUuid()); } // Note that we do not send an event for each individual branch being deleted with the project indexers.commitAndIndexEntities(dbSession, singletonList(entity), EntityEvent.DELETION); } }
2,906
38.821918
125
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentCreationData.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component; import javax.annotation.Nullable; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.project.ProjectDto; public record ComponentCreationData(ComponentDto mainBranchComponent, @Nullable PortfolioDto portfolioDto, @Nullable BranchDto mainBranchDto, @Nullable ProjectDto projectDto) { }
1,299
40.935484
141
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentFinder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component; import java.util.Collection; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.resources.Scopes; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.exceptions.NotFoundException; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static org.sonar.server.exceptions.BadRequestException.checkRequest; public class ComponentFinder { private static final String MSG_COMPONENT_ID_OR_KEY_TEMPLATE = "Either '%s' or '%s' must be provided"; private static final String MSG_PARAMETER_MUST_NOT_BE_EMPTY = "The '%s' parameter must not be empty"; private static final String LABEL_PROJECT = "Project"; private static final String LABEL_COMPONENT = "Component"; private static final String LABEL_PROJECT_NOT_FOUND = "Project '%s' not found"; private static final String LABEL_ENTITY_NOT_FOUND = "Component '%s' not found"; private final DbClient dbClient; private final ResourceTypes resourceTypes; public ComponentFinder(DbClient dbClient, ResourceTypes resourceTypes) { this.dbClient = dbClient; this.resourceTypes = resourceTypes; } public ComponentDto getByUuidOrKey(DbSession dbSession, @Nullable String componentUuid, @Nullable String componentKey, ParamNames parameterNames) { checkByUuidOrKey(componentUuid, componentKey, parameterNames); if (componentUuid != null) { return getByUuidFromMainBranch(dbSession, checkParamNotEmpty(componentUuid, parameterNames.getUuidParam())); } return getByKey(dbSession, checkParamNotEmpty(componentKey, parameterNames.getKeyParam())); } public EntityDto getEntityByUuidOrKey(DbSession dbSession, @Nullable String entityUuid, @Nullable String entityKey, ParamNames parameterNames) { checkByUuidOrKey(entityUuid, entityKey, parameterNames); if (entityUuid != null) { return getEntityByUuid(dbSession, checkParamNotEmpty(entityUuid, parameterNames.getUuidParam())); } return getEntityByKey(dbSession, checkParamNotEmpty(entityKey, parameterNames.getKeyParam())); } public EntityDto getEntityByKey(DbSession dbSession, String entityKey) { return dbClient.entityDao().selectByKey(dbSession, entityKey) .orElseThrow(() -> new NotFoundException(String.format(LABEL_ENTITY_NOT_FOUND, entityKey))); } public EntityDto getEntityByUuid(DbSession dbSession, String entityUuid) { return dbClient.entityDao().selectByUuid(dbSession, entityUuid) .orElseThrow(() -> new NotFoundException(String.format(LABEL_ENTITY_NOT_FOUND, entityUuid))); } public ProjectDto getProjectByKey(DbSession dbSession, String projectKey) { return dbClient.projectDao().selectProjectByKey(dbSession, projectKey) .orElseThrow(() -> new NotFoundException(String.format(LABEL_PROJECT_NOT_FOUND, projectKey))); } public ProjectDto getApplicationByKey(DbSession dbSession, String applicationKey) { return dbClient.projectDao().selectApplicationByKey(dbSession, applicationKey) .orElseThrow(() -> new NotFoundException(String.format("Application '%s' not found", applicationKey))); } public ProjectDto getProjectOrApplicationByKey(DbSession dbSession, String projectKey) { return dbClient.projectDao().selectProjectOrAppByKey(dbSession, projectKey) .orElseThrow(() -> new NotFoundException(String.format(LABEL_PROJECT_NOT_FOUND, projectKey))); } public ProjectDto getProjectByUuid(DbSession dbSession, String projectUuid) { return dbClient.projectDao().selectByUuid(dbSession, projectUuid) .filter(p -> Qualifiers.PROJECT.equals(p.getQualifier())) .orElseThrow(() -> new NotFoundException(String.format(LABEL_PROJECT_NOT_FOUND, projectUuid))); } public ProjectDto getProjectByUuidOrKey(DbSession dbSession, @Nullable String projectUuid, @Nullable String projectKey, ParamNames parameterNames) { checkByUuidOrKey(projectUuid, projectKey, parameterNames); if (projectUuid != null) { return getProjectByUuid(dbSession, checkParamNotEmpty(projectUuid, parameterNames.getUuidParam())); } return getProjectByKey(dbSession, checkParamNotEmpty(projectKey, parameterNames.getKeyParam())); } private static String checkParamNotEmpty(String value, String param) { checkArgument(!value.isEmpty(), MSG_PARAMETER_MUST_NOT_BE_EMPTY, param); return value; } public BranchDto getBranchByUuid(DbSession dbSession, String branchUuid) { return dbClient.branchDao().selectByUuid(dbSession, branchUuid) .orElseThrow(() -> new NotFoundException(String.format("Branch uuid '%s' not found", branchUuid))); } public BranchDto getBranchOrPullRequest(DbSession dbSession, EntityDto entity, @Nullable String branchKey, @Nullable String pullRequestKey) { return getBranchOrPullRequest(dbSession, entity.getUuid(), entity.getKey(), branchKey, pullRequestKey); } public ProjectAndBranch getAppOrProjectAndBranch(DbSession dbSession, String projectKey, @Nullable String branchKey, @Nullable String pullRequestKey) { ProjectDto projectOrApp = getProjectOrApplicationByKey(dbSession, projectKey); BranchDto branch = getBranchOrPullRequest(dbSession, projectOrApp, branchKey, pullRequestKey); return new ProjectAndBranch(projectOrApp, branch); } public static class ProjectAndBranch { private final ProjectDto project; private final BranchDto branch; public ProjectAndBranch(ProjectDto project, BranchDto branch) { this.project = project; this.branch = branch; } public ProjectDto getProject() { return project; } public BranchDto getBranch() { return branch; } } public BranchDto getBranchOrPullRequest(DbSession dbSession, String projectUuid, String projectKey, @Nullable String branchKey, @Nullable String pullRequestKey) { if (branchKey != null) { return dbClient.branchDao().selectByBranchKey(dbSession, projectUuid, branchKey) .orElseThrow(() -> new NotFoundException(String.format("Branch '%s' in project '%s' not found", branchKey, projectKey))); } else if (pullRequestKey != null) { return dbClient.branchDao().selectByPullRequestKey(dbSession, projectUuid, pullRequestKey) .orElseThrow(() -> new NotFoundException(String.format("Pull request '%s' in project '%s' not found", pullRequestKey, projectKey))); } return dbClient.branchDao().selectMainBranchByProjectUuid(dbSession, projectUuid) .orElseThrow(() -> new NotFoundException(String.format("Main branch in project '%s' not found", projectKey))); } public BranchDto getMainBranch(DbSession dbSession, ProjectDto projectDto) { return dbClient.branchDao().selectMainBranchByProjectUuid(dbSession, projectDto.getUuid()) .orElseThrow(() -> new IllegalStateException(String.format("Can't find main branch for project '%s'", projectDto.getKey()))); } private static void checkByUuidOrKey(@Nullable String componentUuid, @Nullable String componentKey, ParamNames parameterNames) { checkArgument(componentUuid != null ^ componentKey != null, MSG_COMPONENT_ID_OR_KEY_TEMPLATE, parameterNames.getUuidParam(), parameterNames.getKeyParam()); } public ComponentDto getByKey(DbSession dbSession, String key) { return getByKey(dbSession, key, LABEL_COMPONENT); } private ComponentDto getByKey(DbSession dbSession, String key, String label) { return checkComponent(dbSession, dbClient.componentDao().selectByKey(dbSession, key), "%s key '%s' not found", label, key); } public ComponentDto getByUuidFromMainBranch(DbSession dbSession, String uuid) { return getByUuidFromMainBranch(dbSession, uuid, LABEL_COMPONENT); } private ComponentDto getByUuidFromMainBranch(DbSession dbSession, String uuid, String label) { return checkComponent(dbSession, dbClient.componentDao().selectByUuid(dbSession, uuid), "%s id '%s' not found", label, uuid); } private ComponentDto checkComponent(DbSession session, Optional<ComponentDto> componentDto, String message, Object... messageArguments) { if (componentDto.isPresent() && componentDto.get().isEnabled()) { if (dbClient.branchDao().selectByUuid(session, componentDto.get().branchUuid()).map(BranchDto::isMain).orElse(true)) { return componentDto.get(); } } throw new NotFoundException(format(message, messageArguments)); } public ComponentDto getRootComponentByUuidOrKey(DbSession dbSession, @Nullable String projectUuid, @Nullable String projectKey) { ComponentDto project; if (projectUuid != null) { project = getByUuidFromMainBranch(dbSession, projectUuid, LABEL_PROJECT); } else { project = getByKey(dbSession, projectKey, LABEL_PROJECT); } checkIsProject(project); return project; } private ComponentDto checkIsProject(ComponentDto component) { Set<String> rootQualifiers = getRootQualifiers(resourceTypes); checkRequest(component.scope().equals(Scopes.PROJECT) && rootQualifiers.contains(component.qualifier()), format( "Component '%s' (id: %s) must be a project%s.", component.getKey(), component.uuid(), rootQualifiers.contains(Qualifiers.VIEW) ? " or a view" : "")); return component; } private static Set<String> getRootQualifiers(ResourceTypes resourceTypes) { Collection<ResourceType> rootTypes = resourceTypes.getRoots(); return rootTypes .stream() .map(ResourceType::getQualifier) .collect(Collectors.toSet()); } public ComponentDto getByKeyAndBranch(DbSession dbSession, String key, String branch) { Optional<ComponentDto> componentDto = dbClient.componentDao().selectByKeyAndBranch(dbSession, key, branch); if (componentDto.isPresent() && componentDto.get().isEnabled()) { return componentDto.get(); } throw new NotFoundException(format("Component '%s' on branch '%s' not found", key, branch)); } public ComponentDto getByKeyAndPullRequest(DbSession dbSession, String key, String pullRequest) { Optional<ComponentDto> componentDto = dbClient.componentDao().selectByKeyAndPullRequest(dbSession, key, pullRequest); if (componentDto.isPresent() && componentDto.get().isEnabled()) { return componentDto.get(); } throw new NotFoundException(format("Component '%s' of pull request '%s' not found", key, pullRequest)); } public ComponentDto getByKeyAndOptionalBranchOrPullRequest(DbSession dbSession, String key, @Nullable String branch, @Nullable String pullRequest) { checkArgument(branch == null || pullRequest == null, "Either branch or pull request can be provided, not both"); if (branch != null) { return getByKeyAndBranch(dbSession, key, branch); } else if (pullRequest != null) { return getByKeyAndPullRequest(dbSession, key, pullRequest); } return getByKey(dbSession, key); } public Optional<ComponentDto> getOptionalByKeyAndOptionalBranchOrPullRequest(DbSession dbSession, String key, @Nullable String branch, @Nullable String pullRequest) { checkArgument(branch == null || pullRequest == null, "Either branch or pull request can be provided, not both"); if (branch != null) { return dbClient.componentDao().selectByKeyAndBranch(dbSession, key, branch); } else if (pullRequest != null) { return dbClient.componentDao().selectByKeyAndPullRequest(dbSession, key, pullRequest); } return dbClient.componentDao().selectByKey(dbSession, key); } public enum ParamNames { PROJECT_ID_AND_KEY("projectId", "projectKey"), PROJECT_UUID_AND_KEY("projectUuid", "projectKey"), PROJECT_UUID_AND_PROJECT("projectUuid", "project"), UUID_AND_KEY("uuid", "key"), ID_AND_KEY("id", "key"), COMPONENT_ID_AND_KEY("componentId", "componentKey"), BASE_COMPONENT_ID_AND_KEY("baseComponentId", "component"), DEVELOPER_ID_AND_KEY("developerId", "developerKey"), COMPONENT_ID_AND_COMPONENT("componentId", "component"), PROJECT_ID_AND_PROJECT("projectId", "project"), PROJECT_ID_AND_FROM("projectId", "from"); private final String uuidParamName; private final String keyParamName; ParamNames(String uuidParamName, String keyParamName) { this.uuidParamName = uuidParamName; this.keyParamName = keyParamName; } public String getUuidParam() { return uuidParamName; } public String getKeyParam() { return keyParamName; } } }
13,650
44.352159
168
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.sonar.api.server.ServerSide; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.project.ProjectDto; import org.sonar.db.pushevent.PushEventDto; import org.sonar.server.es.Indexers; import org.sonar.server.project.Project; import org.sonar.server.project.ProjectLifeCycleListeners; import org.sonar.server.project.RekeyedProject; import org.sonar.server.user.UserSession; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Collections.singleton; import static java.util.Collections.singletonList; import static org.sonar.core.component.ComponentKeys.checkProjectKey; @ServerSide public class ComponentService { private static final Gson GSON = new GsonBuilder().create(); private final DbClient dbClient; private final UserSession userSession; private final Indexers indexers; private final ProjectLifeCycleListeners projectLifeCycleListeners; public ComponentService(DbClient dbClient, UserSession userSession, Indexers indexers, ProjectLifeCycleListeners projectLifeCycleListeners) { this.dbClient = dbClient; this.userSession = userSession; this.indexers = indexers; this.projectLifeCycleListeners = projectLifeCycleListeners; } public void updateKey(DbSession dbSession, ProjectDto project, String newKey) { userSession.checkEntityPermission(UserRole.ADMIN, project); checkProjectKey(newKey); dbClient.componentKeyUpdaterDao().updateKey(dbSession, project.getUuid(), project.getKey(), newKey); indexers.commitAndIndexEntities(dbSession, singletonList(project), Indexers.EntityEvent.PROJECT_KEY_UPDATE); Project newProject = new Project(project.getUuid(), newKey, project.getName(), project.getDescription(), project.getTags()); projectLifeCycleListeners.onProjectsRekeyed(singleton(new RekeyedProject(newProject, project.getKey()))); persistEvent(project, newKey); } private void persistEvent(ProjectDto project, String newProjectKey) { ProjectKeyChangedEvent event = new ProjectKeyChangedEvent(project.getKey(), newProjectKey); try (DbSession dbSession = dbClient.openSession(false)) { PushEventDto eventDto = new PushEventDto() .setName("ProjectKeyChanged") .setProjectUuid(project.getUuid()) .setPayload(serializeIssueToPushEvent(event)); dbClient.pushEventDao().insert(dbSession, eventDto); dbSession.commit(); } } private static byte[] serializeIssueToPushEvent(ProjectKeyChangedEvent event) { return GSON.toJson(event).getBytes(UTF_8); } }
3,534
41.083333
143
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ComponentUpdater.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component; import com.google.common.annotations.VisibleForTesting; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.utils.System2; import org.sonar.core.i18n.I18n; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.portfolio.PortfolioDto; import org.sonar.db.portfolio.PortfolioDto.SelectionMode; import org.sonar.db.project.ProjectDto; import org.sonar.server.es.Indexers; import org.sonar.server.favorite.FavoriteUpdater; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.project.DefaultBranchNameResolver; import org.springframework.beans.factory.annotation.Autowired; import static java.util.Collections.singletonList; import static org.sonar.core.component.ComponentKeys.ALLOWED_CHARACTERS_MESSAGE; import static org.sonar.core.component.ComponentKeys.isValidProjectKey; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.exceptions.BadRequestException.throwBadRequestException; public class ComponentUpdater { private static final Set<String> PROJ_APP_QUALIFIERS = Set.of(Qualifiers.PROJECT, Qualifiers.APP); private static final String KEY_ALREADY_EXISTS_ERROR = "Could not create %s with key: \"%s\". A similar key already exists: \"%s\""; private static final String MALFORMED_KEY_ERROR = "Malformed key for %s: '%s'. %s."; private final DbClient dbClient; private final I18n i18n; private final System2 system2; private final PermissionTemplateService permissionTemplateService; private final FavoriteUpdater favoriteUpdater; private final Indexers indexers; private final UuidFactory uuidFactory; private final DefaultBranchNameResolver defaultBranchNameResolver; private final boolean useDifferentUuids; @Autowired public ComponentUpdater(DbClient dbClient, I18n i18n, System2 system2, PermissionTemplateService permissionTemplateService, FavoriteUpdater favoriteUpdater, Indexers indexers, UuidFactory uuidFactory, DefaultBranchNameResolver defaultBranchNameResolver) { this(dbClient, i18n, system2, permissionTemplateService, favoriteUpdater, indexers, uuidFactory, defaultBranchNameResolver, false); } @VisibleForTesting public ComponentUpdater(DbClient dbClient, I18n i18n, System2 system2, PermissionTemplateService permissionTemplateService, FavoriteUpdater favoriteUpdater, Indexers indexers, UuidFactory uuidFactory, DefaultBranchNameResolver defaultBranchNameResolver, boolean useDifferentUuids) { this.dbClient = dbClient; this.i18n = i18n; this.system2 = system2; this.permissionTemplateService = permissionTemplateService; this.favoriteUpdater = favoriteUpdater; this.indexers = indexers; this.uuidFactory = uuidFactory; this.defaultBranchNameResolver = defaultBranchNameResolver; this.useDifferentUuids = useDifferentUuids; } /** * - Create component * - Apply default permission template * - Add component to favorite if the component has the 'Project Creators' permission * - Index component in es indexes */ public ComponentCreationData create(DbSession dbSession, NewComponent newComponent, @Nullable String userUuid, @Nullable String userLogin) { ComponentCreationData componentCreationData = createWithoutCommit(dbSession, newComponent, userUuid, userLogin, null); commitAndIndex(dbSession, componentCreationData); return componentCreationData; } public void commitAndIndex(DbSession dbSession, ComponentCreationData componentCreationData) { if (componentCreationData.portfolioDto() != null) { indexers.commitAndIndexEntities(dbSession, singletonList(componentCreationData.portfolioDto()), Indexers.EntityEvent.CREATION); } else if (componentCreationData.projectDto() != null) { indexers.commitAndIndexEntities(dbSession, singletonList(componentCreationData.projectDto()), Indexers.EntityEvent.CREATION); } } /** * Create component without committing. * Don't forget to call commitAndIndex(...) when ready to commit. */ public ComponentCreationData createWithoutCommit(DbSession dbSession, NewComponent newComponent, @Nullable String userUuid, @Nullable String userLogin) { return createWithoutCommit(dbSession, newComponent, userUuid, userLogin, null); } /** * Create component without committing. * Don't forget to call commitAndIndex(...) when ready to commit. */ public ComponentCreationData createWithoutCommit(DbSession dbSession, NewComponent newComponent, @Nullable String userUuid, @Nullable String userLogin, @Nullable String mainBranchName) { checkKeyFormat(newComponent.qualifier(), newComponent.key()); checkKeyAlreadyExists(dbSession, newComponent); long now = system2.now(); ComponentDto componentDto = createRootComponent(dbSession, newComponent, now); BranchDto mainBranch = null; ProjectDto projectDto = null; PortfolioDto portfolioDto = null; if (isProjectOrApp(componentDto)) { projectDto = toProjectDto(componentDto, now); dbClient.projectDao().insert(dbSession, projectDto); addToFavourites(dbSession, projectDto, userUuid, userLogin); mainBranch = createMainBranch(dbSession, componentDto.uuid(), projectDto.getUuid(), mainBranchName); permissionTemplateService.applyDefaultToNewComponent(dbSession, projectDto, userUuid); } else if (isPortfolio(componentDto)) { portfolioDto = toPortfolioDto(componentDto, now); dbClient.portfolioDao().insert(dbSession, portfolioDto); permissionTemplateService.applyDefaultToNewComponent(dbSession, portfolioDto, userUuid); } else { throw new IllegalArgumentException("Component " + componentDto + " is not a top level entity"); } return new ComponentCreationData(componentDto, portfolioDto, mainBranch, projectDto); } private void addToFavourites(DbSession dbSession, ProjectDto projectDto, @Nullable String userUuid, @Nullable String userLogin) { if (permissionTemplateService.hasDefaultTemplateWithPermissionOnProjectCreator(dbSession, projectDto)) { favoriteUpdater.add(dbSession, projectDto, userUuid, userLogin, false); } } private void checkKeyFormat(String qualifier, String key) { checkRequest(isValidProjectKey(key), MALFORMED_KEY_ERROR, getQualifierToDisplay(qualifier), key, ALLOWED_CHARACTERS_MESSAGE); } private void checkKeyAlreadyExists(DbSession dbSession, NewComponent newComponent) { List<ComponentDto> componentDtos = dbClient.componentDao().selectByKeyCaseInsensitive(dbSession, newComponent.key()); if (!componentDtos.isEmpty()) { String alreadyExistingKeys = componentDtos .stream() .map(ComponentDto::getKey) .collect(Collectors.joining(", ")); throwBadRequestException(KEY_ALREADY_EXISTS_ERROR, getQualifierToDisplay(newComponent.qualifier()), newComponent.key(), alreadyExistingKeys); } } private ComponentDto createRootComponent(DbSession session, NewComponent newComponent, long now) { String uuid = uuidFactory.create(); ComponentDto component = new ComponentDto() .setUuid(uuid) .setUuidPath(ComponentDto.UUID_PATH_OF_ROOT) .setBranchUuid(uuid) .setKey(newComponent.key()) .setName(newComponent.name()) .setDescription(newComponent.description()) .setLongName(newComponent.name()) .setScope(Scopes.PROJECT) .setQualifier(newComponent.qualifier()) .setPrivate(newComponent.isPrivate()) .setCreatedAt(new Date(now)); dbClient.componentDao().insert(session, component, true); return component; } private ProjectDto toProjectDto(ComponentDto component, long now) { return new ProjectDto() .setUuid(useDifferentUuids ? uuidFactory.create() : component.uuid()) .setKey(component.getKey()) .setQualifier(component.qualifier()) .setName(component.name()) .setPrivate(component.isPrivate()) .setDescription(component.description()) .setUpdatedAt(now) .setCreatedAt(now); } private static PortfolioDto toPortfolioDto(ComponentDto component, long now) { return new PortfolioDto() .setUuid(component.uuid()) .setRootUuid(component.branchUuid()) .setKey(component.getKey()) .setName(component.name()) .setPrivate(component.isPrivate()) .setDescription(component.description()) .setSelectionMode(SelectionMode.NONE.name()) .setUpdatedAt(now) .setCreatedAt(now); } private static boolean isProjectOrApp(ComponentDto componentDto) { return PROJ_APP_QUALIFIERS.contains(componentDto.qualifier()); } private static boolean isPortfolio(ComponentDto componentDto) { return Qualifiers.VIEW.contains(componentDto.qualifier()); } private BranchDto createMainBranch(DbSession session, String componentUuid, String projectUuid, @Nullable String mainBranch) { BranchDto branch = new BranchDto() .setBranchType(BranchType.BRANCH) .setUuid(componentUuid) .setIsMain(true) .setKey(Optional.ofNullable(mainBranch).orElse(defaultBranchNameResolver.getEffectiveMainBranchName())) .setMergeBranchUuid(null) .setExcludeFromPurge(true) .setProjectUuid(projectUuid); dbClient.branchDao().upsert(session, branch); return branch; } private String getQualifierToDisplay(String qualifier) { return i18n.message(Locale.getDefault(), "qualifier." + qualifier, "Project"); } }
10,748
42.168675
147
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/NewComponent.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.db.component.ComponentValidator.checkComponentKey; import static org.sonar.db.component.ComponentValidator.checkComponentName; import static org.sonar.db.component.ComponentValidator.checkComponentQualifier; @Immutable public class NewComponent { private final String key; private final String qualifier; private final String name; private final String description; private final boolean isPrivate; private NewComponent(NewComponent.Builder builder) { this.key = builder.key; this.qualifier = builder.qualifier; this.name = builder.name; this.isPrivate = builder.isPrivate; this.description = builder.description; } public static Builder newComponentBuilder() { return new Builder(); } public String key() { return key; } public String name() { return name; } public String qualifier() { return qualifier; } public boolean isPrivate() { return isPrivate; } @CheckForNull public String description() { return description; } public boolean isProject() { return PROJECT.equals(qualifier); } public static class Builder { private String description; private String key; private String qualifier = PROJECT; private String name; private boolean isPrivate = false; private Builder() { // use static factory method newComponentBuilder() } public Builder setKey(String key) { this.key = key; return this; } public Builder setQualifier(String qualifier) { this.qualifier = qualifier; return this; } public Builder setName(String name) { this.name = name; return this; } public Builder setPrivate(boolean isPrivate) { this.isPrivate = isPrivate; return this; } public Builder setDescription(@Nullable String description) { this.description = description; return this; } public NewComponent build() { checkComponentKey(key); checkComponentName(name); checkComponentQualifier(qualifier); return new NewComponent(this); } } }
3,173
25.231405
80
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ProjectKeyChangedEvent.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component; import java.io.Serializable; public class ProjectKeyChangedEvent implements Serializable { private static final String EVENT = "ProjectKeyChanged"; private final String oldProjectKey; private final String newProjectKey; public ProjectKeyChangedEvent(String oldProjectKey, String newProjectKey) { this.oldProjectKey = oldProjectKey; this.newProjectKey = newProjectKey; } public String getEvent() { return EVENT; } public String getOldProjectKey() { return oldProjectKey; } public String getNewProjectKey() { return newProjectKey; } }
1,462
29.479167
77
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component; import javax.annotation.ParametersAreNonnullByDefault;
966
39.291667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/AppAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.text.JsonWriter; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_BRANCH; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_PULL_REQUEST; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; public class AppAction implements ComponentsWsAction { static final String PARAM_COMPONENT = "component"; private final DbClient dbClient; private final UserSession userSession; private final ComponentFinder componentFinder; private final ComponentViewerJsonWriter componentViewerJsonWriter; public AppAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, ComponentViewerJsonWriter componentViewerJsonWriter) { this.dbClient = dbClient; this.userSession = userSession; this.componentFinder = componentFinder; this.componentViewerJsonWriter = componentViewerJsonWriter; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("app") .setDescription("Coverage data required for rendering the component viewer.<br>" + "Either branch or pull request can be provided, not both<br>" + "Requires the following permission: 'Browse'.") .setResponseExample(getClass().getResource("app-example.json")) .setSince("4.4") .setChangelog( new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("9.6", "The fields 'subProject', 'subProjectName' were removed from the response."), new Change("7.6", String.format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT))) .setInternal(true) .setHandler(this); action.createParam(PARAM_COMPONENT) .setDescription("Component key") .setExampleValue(KEY_PROJECT_EXAMPLE_001) .setRequired(true) .setSince("6.4"); action.createParam(PARAM_BRANCH) .setDescription("Branch key. Not available in the community edition.") .setSince("6.6") .setExampleValue(KEY_BRANCH_EXAMPLE_001); action.createParam(PARAM_PULL_REQUEST) .setDescription("Pull request id. Not available in the community edition.") .setSince("7.1") .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001); } @Override public void handle(Request request, Response response) { try (DbSession session = dbClient.openSession(false)) { ComponentDto component = loadComponent(session, request); userSession.checkComponentPermission(UserRole.USER, component); EntityDto entity = dbClient.entityDao().selectByComponentUuid(session, component.uuid()) .orElseThrow(() -> new IllegalStateException("Couldn't find entity for component " + component.uuid())); writeJsonResponse(response, session, entity, component, request); } } private ComponentDto loadComponent(DbSession dbSession, Request request) { String branch = request.param(PARAM_BRANCH); String pullRequest = request.param(PARAM_PULL_REQUEST); String componentKey = request.mandatoryParam(PARAM_COMPONENT); return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest); } private void writeJsonResponse(Response response, DbSession session, EntityDto entity, ComponentDto component, Request request) { try (JsonWriter json = response.newJsonWriter()) { json.beginObject(); componentViewerJsonWriter.writeComponent(json, entity, component, userSession, session, request.param(PARAM_BRANCH), request.param(PARAM_PULL_REQUEST)); appendPermissions(json, userSession); componentViewerJsonWriter.writeMeasures(json, component, session); json.endObject(); } } private static void appendPermissions(JsonWriter json, UserSession userSession) { json.prop("canMarkAsFavorite", userSession.isLoggedIn()); } }
5,416
43.04065
150
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ApplicationLeakProjects.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.gson.Gson; import com.google.gson.annotations.SerializedName; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Optional; public class ApplicationLeakProjects { @SerializedName("leakProjects") private List<LeakProject> projects = new ArrayList<>(); public ApplicationLeakProjects() { // even if empty constructor is not required for Gson, it is strongly recommended: // http://stackoverflow.com/a/18645370/229031 } public ApplicationLeakProjects addProject(LeakProject project) { this.projects.add(project); return this; } public Optional<LeakProject> getOldestLeak() { return projects.stream().min(Comparator.comparingLong(o -> o.leak)); } public static ApplicationLeakProjects parse(String json) { Gson gson = new Gson(); return gson.fromJson(json, ApplicationLeakProjects.class); } public String format() { Gson gson = new Gson(); return gson.toJson(this, ApplicationLeakProjects.class); } public static class LeakProject { @SerializedName("id") private String id; @SerializedName("leak") private long leak; public LeakProject() { // even if empty constructor is not required for Gson, it is strongly recommended: // http://stackoverflow.com/a/18645370/229031 } public LeakProject setId(String id) { this.id = id; return this; } public String getId() { return id; } public LeakProject setLeak(long leak) { this.leak = leak; return this; } public long getLeak() { return leak; } } }
2,515
27.269663
88
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentDtoToWsComponent.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import java.util.Arrays; import java.util.Set; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.project.Visibility; import org.sonarqube.ws.Components; import static com.google.common.base.Strings.emptyToNull; import static java.util.Optional.ofNullable; import static org.sonar.api.utils.DateUtils.formatDateTime; class ComponentDtoToWsComponent { /** * The concept of "visibility" will only be configured for these qualifiers. */ private static final Set<String> QUALIFIERS_WITH_VISIBILITY = Set.of(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP); private ComponentDtoToWsComponent() { // prevent instantiation } static Components.Component.Builder projectOrAppToWsComponent(ProjectDto project, @Nullable SnapshotDto lastAnalysis) { Components.Component.Builder wsComponent = Components.Component.newBuilder() .setKey(project.getKey()) .setName(project.getName()) .setQualifier(project.getQualifier()); ofNullable(emptyToNull(project.getDescription())).ifPresent(wsComponent::setDescription); ofNullable(lastAnalysis).ifPresent( analysis -> { wsComponent.setAnalysisDate(formatDateTime(analysis.getCreatedAt())); ofNullable(analysis.getPeriodDate()).ifPresent(leak -> wsComponent.setLeakPeriodDate(formatDateTime(leak))); ofNullable(analysis.getProjectVersion()).ifPresent(wsComponent::setVersion); }); if (QUALIFIERS_WITH_VISIBILITY.contains(project.getQualifier())) { wsComponent.setVisibility(Visibility.getLabel(project.isPrivate())); wsComponent.getTagsBuilder().addAllTags(project.getTags()); } return wsComponent; } public static Components.Component.Builder componentDtoToWsComponent(ComponentDto dto, @Nullable ProjectDto parentProjectDto, @Nullable SnapshotDto lastAnalysis, boolean isMainBranch, @Nullable String branch, @Nullable String pullRequest) { Components.Component.Builder wsComponent = Components.Component.newBuilder() .setKey(ComponentDto.removeBranchAndPullRequestFromKey(dto.getKey())) .setName(dto.name()) .setQualifier(dto.qualifier()); ofNullable(emptyToNull(branch)).ifPresent(wsComponent::setBranch); ofNullable(emptyToNull(pullRequest)).ifPresent(wsComponent::setPullRequest); ofNullable(emptyToNull(dto.path())).ifPresent(wsComponent::setPath); ofNullable(emptyToNull(dto.description())).ifPresent(wsComponent::setDescription); ofNullable(emptyToNull(dto.language())).ifPresent(wsComponent::setLanguage); ofNullable(lastAnalysis).ifPresent( analysis -> { wsComponent.setAnalysisDate(formatDateTime(analysis.getCreatedAt())); ofNullable(analysis.getPeriodDate()).ifPresent(leak -> wsComponent.setLeakPeriodDate(formatDateTime(leak))); ofNullable(analysis.getProjectVersion()).ifPresent(wsComponent::setVersion); }); if (QUALIFIERS_WITH_VISIBILITY.contains(dto.qualifier())) { wsComponent.setVisibility(Visibility.getLabel(dto.isPrivate())); if (Arrays.asList(Qualifiers.PROJECT, Qualifiers.APP).contains(dto.qualifier()) && parentProjectDto != null && isMainBranch) { wsComponent.getTagsBuilder().addAllTags(parentProjectDto.getTags()); } } return wsComponent; } }
4,313
44.893617
132
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentViewerJsonWriter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.common.collect.Maps; import java.util.Collections; import java.util.List; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.BooleanUtils; import org.sonar.api.measures.Metric; import org.sonar.api.utils.text.JsonWriter; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.db.entity.EntityDto; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.metric.MetricDto; import org.sonar.db.property.PropertyDto; import org.sonar.db.property.PropertyQuery; import org.sonar.server.user.UserSession; import static org.sonar.api.measures.CoreMetrics.COVERAGE; import static org.sonar.api.measures.CoreMetrics.COVERAGE_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.LINES; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; import static org.sonar.api.measures.CoreMetrics.TESTS; import static org.sonar.api.measures.CoreMetrics.TESTS_KEY; import static org.sonar.api.measures.CoreMetrics.VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.VIOLATIONS_KEY; public class ComponentViewerJsonWriter { private static final List<String> METRIC_KEYS = List.of( LINES_KEY, VIOLATIONS_KEY, COVERAGE_KEY, DUPLICATED_LINES_DENSITY_KEY, TESTS_KEY); private final DbClient dbClient; public ComponentViewerJsonWriter(DbClient dbClient) { this.dbClient = dbClient; } public void writeComponentWithoutFav(JsonWriter json, EntityDto entity, ComponentDto component, @Nullable String branch, @Nullable String pullRequest) { json.prop("key", component.getKey()); json.prop("uuid", component.uuid()); json.prop("path", component.path()); json.prop("name", component.name()); json.prop("longName", component.longName()); json.prop("q", component.qualifier()); json.prop("project", entity.getKey()); json.prop("projectName", entity.getName()); if (branch != null) { json.prop("branch", branch); } if (pullRequest != null) { json.prop("pullRequest", pullRequest); } } public void writeComponent(JsonWriter json, EntityDto entity, ComponentDto component, UserSession userSession, DbSession session, @Nullable String branch, @Nullable String pullRequest) { writeComponentWithoutFav(json, entity, component, branch, pullRequest); List<PropertyDto> propertyDtos = dbClient.propertiesDao().selectByQuery(PropertyQuery.builder() .setKey("favourite") .setEntityUuid(entity.getUuid()) .setUserUuid(userSession.getUuid()) .build(), session); boolean isFavourite = propertyDtos.size() == 1; json.prop("fav", isFavourite); } public void writeMeasures(JsonWriter json, ComponentDto component, DbSession session) { Map<String, LiveMeasureDto> measuresByMetricKey = loadMeasuresGroupedByMetricKey(component, session); json.name("measures").beginObject(); json.prop("lines", formatMeasure(measuresByMetricKey, LINES)); json.prop("coverage", formatMeasure(measuresByMetricKey, COVERAGE)); json.prop("duplicationDensity", formatMeasure(measuresByMetricKey, DUPLICATED_LINES_DENSITY)); json.prop("issues", formatMeasure(measuresByMetricKey, VIOLATIONS)); json.prop("tests", formatMeasure(measuresByMetricKey, TESTS)); json.endObject(); } private Map<String, LiveMeasureDto> loadMeasuresGroupedByMetricKey(ComponentDto component, DbSession dbSession) { List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, METRIC_KEYS); Map<String, MetricDto> metricsByUuid = Maps.uniqueIndex(metrics, MetricDto::getUuid); List<LiveMeasureDto> measures = dbClient.liveMeasureDao() .selectByComponentUuidsAndMetricUuids(dbSession, Collections.singletonList(component.uuid()), metricsByUuid.keySet()); return Maps.uniqueIndex(measures, m -> metricsByUuid.get(m.getMetricUuid()).getKey()); } @CheckForNull private static String formatMeasure(Map<String, LiveMeasureDto> measuresByMetricKey, Metric metric) { LiveMeasureDto measure = measuresByMetricKey.get(metric.getKey()); return formatMeasure(measure, metric); } private static String formatMeasure(@Nullable LiveMeasureDto measure, Metric metric) { if (measure == null) { return null; } Double value = getDoubleValue(measure, metric); if (value != null) { return Double.toString(value); } return null; } @CheckForNull private static Double getDoubleValue(LiveMeasureDto measure, Metric metric) { Double value = measure.getValue(); if (BooleanUtils.isTrue(metric.isOptimizedBestValue()) && value == null) { value = metric.getBestValue(); } return value; } }
5,810
39.075862
156
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentsWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import java.util.Arrays; import org.sonar.api.server.ws.WebService; import static org.sonarqube.ws.client.component.ComponentsWsParameters.CONTROLLER_COMPONENTS; public class ComponentsWs implements WebService { private final ComponentsWsAction[] actions; public ComponentsWs(ComponentsWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController(CONTROLLER_COMPONENTS) .setSince("4.2") .setDescription("Get information about a component (file, directory, project, ...) and its ancestors or descendants. " + "Update a project or module key."); Arrays.stream(actions) .forEach(action -> action.define(controller)); controller.done(); } }
1,670
33.102041
126
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentsWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import org.sonar.server.ws.WsAction; public interface ComponentsWsAction extends WsAction { // marker interface }
1,000
36.074074
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ComponentsWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import org.sonar.core.platform.Module; public class ComponentsWsModule extends Module { @Override protected void configureModule() { add( ComponentsWs.class, // actions AppAction.class, SearchAction.class, SuggestionsAction.class, TreeAction.class, ShowAction.class, SearchProjectsAction.class); } }
1,242
31.710526
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/FilterParser.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.common.base.Splitter; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.server.measure.index.ProjectMeasuresQuery; import static com.google.common.base.Strings.isNullOrEmpty; import static java.util.Objects.requireNonNull; public class FilterParser { private static final String DOUBLE_QUOTES = "\""; private static final Splitter CRITERIA_SPLITTER = Splitter.on(Pattern.compile(" and ", Pattern.CASE_INSENSITIVE)).trimResults().omitEmptyStrings(); private static final Splitter IN_VALUES_SPLITTER = Splitter.on(",").trimResults().omitEmptyStrings(); private static final Pattern PATTERN_WITH_COMPARISON_OPERATOR = Pattern.compile("(\\w+)\\s*+(<=?|>=?|=)\\s*+([^<>=]*+)", Pattern.CASE_INSENSITIVE); private static final Pattern PATTERN_WITHOUT_OPERATOR = Pattern.compile("(\\w+)\\s*+", Pattern.CASE_INSENSITIVE); private static final Pattern PATTERN_WITH_IN_OPERATOR = Pattern.compile("(\\w+)\\s+(in)\\s+\\(([^()]*)\\)", Pattern.CASE_INSENSITIVE); private FilterParser() { // Only static methods } public static List<Criterion> parse(String filter) { return StreamSupport.stream(CRITERIA_SPLITTER.split(filter).spliterator(), false) .map(FilterParser::parseCriterion) .toList(); } private static Criterion parseCriterion(String rawCriterion) { try { return Stream.of( tryParsingCriterionWithoutOperator(rawCriterion), tryParsingCriterionWithInOperator(rawCriterion), tryParsingCriterionWithComparisonOperator(rawCriterion) ) .filter(Optional::isPresent) .map(Optional::get) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Criterion is invalid")); } catch (Exception e) { throw new IllegalArgumentException(String.format("Cannot parse '%s' : %s", rawCriterion, e.getMessage()), e); } } private static Optional<Criterion> tryParsingCriterionWithoutOperator(String criterion) { Matcher matcher = PATTERN_WITHOUT_OPERATOR.matcher(criterion); if (!matcher.matches()) { return Optional.empty(); } Criterion.Builder builder = new Criterion.Builder(); builder.setKey(matcher.group(1)); return Optional.of(builder.build()); } private static Optional<Criterion> tryParsingCriterionWithComparisonOperator(String criterion) { Matcher matcher = PATTERN_WITH_COMPARISON_OPERATOR.matcher(criterion); if (!matcher.matches()) { return Optional.empty(); } Criterion.Builder builder = new Criterion.Builder(); builder.setKey(matcher.group(1)); String operatorValue = matcher.group(2); String value = matcher.group(3); if (!isNullOrEmpty(operatorValue) && !isNullOrEmpty(value)) { builder.setOperator(ProjectMeasuresQuery.Operator.getByValue(operatorValue)); builder.setValue(sanitizeValue(value)); } return Optional.of(builder.build()); } private static Optional<Criterion> tryParsingCriterionWithInOperator(String criterion) { Matcher matcher = PATTERN_WITH_IN_OPERATOR.matcher(criterion); if (!matcher.matches()) { return Optional.empty(); } Criterion.Builder builder = new Criterion.Builder(); builder.setKey(matcher.group(1)); builder.setOperator(ProjectMeasuresQuery.Operator.IN); builder.setValues(IN_VALUES_SPLITTER.splitToList(matcher.group(3))); return Optional.of(builder.build()); } @CheckForNull private static String sanitizeValue(@Nullable String value) { if (value == null) { return null; } if (value.length() > 2 && value.startsWith(DOUBLE_QUOTES) && value.endsWith(DOUBLE_QUOTES)) { return value.substring(1, value.length() - 1); } return value; } public static class Criterion { private final String key; private final ProjectMeasuresQuery.Operator operator; private final String value; private final List<String> values; private Criterion(Builder builder) { this.key = builder.key; this.operator = builder.operator; this.value = builder.value; this.values = builder.values; } public String getKey() { return key; } @CheckForNull public ProjectMeasuresQuery.Operator getOperator() { return operator; } @CheckForNull public String getValue() { return value; } public List<String> getValues() { return values; } public static Builder builder() { return new Builder(); } public static class Builder { private String key; private ProjectMeasuresQuery.Operator operator; private String value; private List<String> values = new ArrayList<>(); public Builder setKey(String key) { this.key = key; return this; } public Builder setOperator(@Nullable ProjectMeasuresQuery.Operator operator) { this.operator = operator; return this; } public Builder setValue(@Nullable String value) { this.value = value; return this; } public Builder setValues(List<String> values) { this.values = requireNonNull(values, "Values cannot be null"); return this; } public Criterion build() { return new Criterion(this); } } } }
6,396
32.846561
149
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/MeasuresWsParameters.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.common.collect.ImmutableSortedSet; import java.util.Set; public class MeasuresWsParameters { public static final String CONTROLLER_MEASURES = "api/measures"; // actions public static final String ACTION_COMPONENT_TREE = "component_tree"; public static final String ACTION_COMPONENT = "component"; public static final String ACTION_SEARCH_HISTORY = "search_history"; // parameters public static final String PARAM_COMPONENT = "component"; public static final String PARAM_BRANCH = "branch"; public static final String PARAM_PULL_REQUEST = "pullRequest"; public static final String PARAM_STRATEGY = "strategy"; public static final String PARAM_QUALIFIERS = "qualifiers"; public static final String PARAM_METRICS = "metrics"; public static final String PARAM_METRIC_KEYS = "metricKeys"; public static final String PARAM_METRIC_SORT = "metricSort"; public static final String PARAM_METRIC_PERIOD_SORT = "metricPeriodSort"; public static final String PARAM_METRIC_SORT_FILTER = "metricSortFilter"; public static final String PARAM_ADDITIONAL_FIELDS = "additionalFields"; public static final String PARAM_PROJECT_KEYS = "projectKeys"; public static final String PARAM_FROM = "from"; public static final String PARAM_TO = "to"; public static final String ADDITIONAL_METRICS = "metrics"; public static final String ADDITIONAL_PERIOD = "period"; public static final Set<String> ADDITIONAL_FIELDS = ImmutableSortedSet.of(ADDITIONAL_METRICS, ADDITIONAL_PERIOD); private MeasuresWsParameters() { // static constants only } }
2,475
40.966102
115
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ProjectMeasuresQueryFactory.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Stream; import javax.annotation.Nullable; import org.sonar.api.measures.Metric.Level; import org.sonar.api.resources.Qualifiers; import org.sonar.server.component.ws.FilterParser.Criterion; import org.sonar.server.measure.index.ProjectMeasuresQuery; import org.sonar.server.measure.index.ProjectMeasuresQuery.Operator; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Collections.singleton; import static java.util.Locale.ENGLISH; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.EQ; import static org.sonar.server.measure.index.ProjectMeasuresQuery.Operator.IN; import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_LANGUAGES; import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_QUALIFIER; import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_TAGS; class ProjectMeasuresQueryFactory { public static final String IS_FAVORITE_CRITERION = "isFavorite"; public static final String QUERY_KEY = "query"; private static final String NO_DATA = "NO_DATA"; private static final Map<String, BiConsumer<Criterion, ProjectMeasuresQuery>> CRITERION_PROCESSORS = ImmutableMap.<String, BiConsumer<Criterion, ProjectMeasuresQuery>>builder() .put(IS_FAVORITE_CRITERION.toLowerCase(ENGLISH), (criterion, query) -> processIsFavorite(criterion)) .put(FILTER_LANGUAGES, ProjectMeasuresQueryFactory::processLanguages) .put(FILTER_TAGS, ProjectMeasuresQueryFactory::processTags) .put(FILTER_QUALIFIER, ProjectMeasuresQueryFactory::processQualifier) .put(QUERY_KEY, ProjectMeasuresQueryFactory::processQuery) .put(ALERT_STATUS_KEY, ProjectMeasuresQueryFactory::processQualityGateStatus) .build(); private ProjectMeasuresQueryFactory() { // prevent instantiation } static ProjectMeasuresQuery newProjectMeasuresQuery(List<Criterion> criteria, @Nullable Set<String> projectUuids) { ProjectMeasuresQuery query = new ProjectMeasuresQuery(); Optional.ofNullable(projectUuids).ifPresent(query::setProjectUuids); criteria.forEach(criterion -> processCriterion(criterion, query)); return query; } private static void processCriterion(Criterion criterion, ProjectMeasuresQuery query) { String key = criterion.getKey().toLowerCase(ENGLISH); CRITERION_PROCESSORS.getOrDefault(key, ProjectMeasuresQueryFactory::processMetricCriterion).accept(criterion, query); } private static void processIsFavorite(Criterion criterion) { checkArgument(criterion.getOperator() == null && criterion.getValue() == null, "Filter on favorites should be declared without an operator nor a value"); } private static void processLanguages(Criterion criterion, ProjectMeasuresQuery query) { checkOperator(criterion); Operator operator = criterion.getOperator(); String value = criterion.getValue(); List<String> values = criterion.getValues(); if (value != null && EQ.equals(operator)) { query.setLanguages(singleton(value)); return; } if (!values.isEmpty() && IN.equals(operator)) { query.setLanguages(new HashSet<>(values)); return; } throw new IllegalArgumentException("Languages should be set either by using 'languages = java' or 'languages IN (java, js)'"); } private static void processTags(Criterion criterion, ProjectMeasuresQuery query) { checkOperator(criterion); Operator operator = criterion.getOperator(); String value = criterion.getValue(); List<String> values = criterion.getValues(); if (value != null && EQ.equals(operator)) { query.setTags(singleton(value)); return; } if (!values.isEmpty() && IN.equals(operator)) { query.setTags(new HashSet<>(values)); return; } throw new IllegalArgumentException("Tags should be set either by using 'tags = java' or 'tags IN (finance, platform)'"); } private static void processQualifier(Criterion criterion, ProjectMeasuresQuery query) { checkOperator(criterion); checkValue(criterion); Operator operator = criterion.getOperator(); String value = criterion.getValue(); checkArgument(EQ.equals(operator), "Only equals operator is available for qualifier criteria"); String qualifier = Stream.of(Qualifiers.APP, Qualifiers.PROJECT).filter(q -> q.equalsIgnoreCase(value)).findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Unknown qualifier : '%s'", value))); query.setQualifiers(Sets.newHashSet(qualifier)); } private static void processQuery(Criterion criterion, ProjectMeasuresQuery query) { checkOperator(criterion); Operator operatorValue = criterion.getOperator(); String value = criterion.getValue(); checkArgument(value != null, "Query is invalid"); checkArgument(EQ.equals(operatorValue), "Query should only be used with equals operator"); query.setQueryText(value); } private static void processQualityGateStatus(Criterion criterion, ProjectMeasuresQuery query) { checkOperator(criterion); checkValue(criterion); Operator operator = criterion.getOperator(); String value = criterion.getValue(); checkArgument(EQ.equals(operator), "Only equals operator is available for quality gate criteria"); Level qualityGate = Arrays.stream(Level.values()).filter(level -> level.name().equalsIgnoreCase(value)).findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Unknown quality gate status : '%s'", value))); query.setQualityGateStatus(qualityGate); } private static void processMetricCriterion(Criterion criterion, ProjectMeasuresQuery query) { checkOperator(criterion); checkValue(criterion); query.addMetricCriterion(createMetricCriterion(criterion, criterion.getKey().toLowerCase(ENGLISH), criterion.getOperator())); } private static MetricCriterion createMetricCriterion(Criterion criterion, String metricKey, Operator operator) { if (NO_DATA.equalsIgnoreCase(criterion.getValue())) { checkArgument(EQ.equals(operator), "%s can only be used with equals operator", NO_DATA); return MetricCriterion.createNoData(metricKey); } return MetricCriterion.create(metricKey, operator, parseValue(criterion.getValue())); } private static double parseValue(String value) { try { return Double.parseDouble(value); } catch (NumberFormatException e) { throw new IllegalArgumentException(format("Value '%s' is not a number", value)); } } private static void checkValue(Criterion criterion) { checkArgument(criterion.getValue() != null, "Value cannot be null for '%s'", criterion.getKey()); } private static void checkOperator(Criterion criterion) { checkArgument(criterion.getOperator() != null, "Operator cannot be null for '%s'", criterion.getKey()); } }
8,190
44.759777
178
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ProjectMeasuresQueryValidator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.server.measure.index.ProjectMeasuresQuery; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Arrays.asList; import static org.sonar.db.measure.ProjectMeasuresIndexerIterator.METRIC_KEYS; import static org.sonar.server.measure.index.ProjectMeasuresQuery.MetricCriterion; import static org.sonar.server.measure.index.ProjectMeasuresQuery.SORT_BY_LAST_ANALYSIS_DATE; import static org.sonar.server.measure.index.ProjectMeasuresQuery.SORT_BY_NAME; public class ProjectMeasuresQueryValidator { static final Set<String> NON_METRIC_SORT_KEYS = new HashSet<>(asList(SORT_BY_NAME, SORT_BY_LAST_ANALYSIS_DATE)); private ProjectMeasuresQueryValidator() { } public static void validate(ProjectMeasuresQuery query) { validateFilterKeys(query.getMetricCriteria().stream().map(MetricCriterion::getMetricKey).collect(Collectors.toSet())); validateSort(query.getSort()); } private static void validateFilterKeys(Set<String> metricsKeys) { String invalidKeys = metricsKeys.stream() .filter(metric -> !METRIC_KEYS.contains(metric)) .map(metric -> '\''+metric+'\'') .collect(Collectors.joining(", ")); checkArgument(invalidKeys.isEmpty(), "Following metrics are not supported: %s", invalidKeys); } private static void validateSort(@Nullable String sort) { if (sort == null) { return; } if (NON_METRIC_SORT_KEYS.contains(sort)) { return; } validateFilterKeys(Collections.singleton(sort)); } }
2,551
37.666667
122
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SearchAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.common.collect.ImmutableSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.Paging; import org.sonar.core.i18n.I18n; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.entity.EntityDto; import org.sonar.server.component.index.ComponentIndex; import org.sonar.server.component.index.ComponentQuery; import org.sonar.server.es.SearchIdResult; import org.sonar.server.es.SearchOptions; import org.sonarqube.ws.Components; import org.sonarqube.ws.Components.SearchWsResponse; import static java.util.Objects.requireNonNull; import static java.util.stream.Collectors.toMap; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.SUBVIEW; import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.server.es.SearchOptions.MAX_PAGE_SIZE; import static org.sonar.server.ws.WsParameterBuilder.createQualifiersParameter; import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.component.ComponentsWsParameters.ACTION_SEARCH; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_QUALIFIERS; public class SearchAction implements ComponentsWsAction { private static final ImmutableSet<String> VALID_QUALIFIERS = ImmutableSet.<String>builder() .add(APP, PROJECT, VIEW, SUBVIEW) .build(); private final ComponentIndex componentIndex; private final DbClient dbClient; private final ResourceTypes resourceTypes; private final I18n i18n; public SearchAction(ComponentIndex componentIndex, DbClient dbClient, ResourceTypes resourceTypes, I18n i18n) { this.componentIndex = componentIndex; this.dbClient = dbClient; this.resourceTypes = resourceTypes; this.i18n = i18n; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_SEARCH) .setSince("6.3") .setDescription("Search for components") .addPagingParams(100, MAX_PAGE_SIZE) .setChangelog( new Change("8.4", "Param 'language' has been removed"), new Change("8.4", String.format("The use of 'DIR','FIL','UTS' and 'BRC' as values for parameter '%s' is no longer supported", PARAM_QUALIFIERS)), new Change("8.0", "Field 'id' from response has been removed"), new Change("7.6", String.format("The use of 'BRC' as value for parameter '%s' is deprecated", PARAM_QUALIFIERS))) .setResponseExample(getClass().getResource("search-components-example.json")) .setHandler(this); action.createParam(Param.TEXT_QUERY) .setDescription("Limit search to: <ul>" + "<li>component names that contain the supplied string</li>" + "<li>component keys that are exactly the same as the supplied string</li>" + "</ul>") .setExampleValue("sonar"); createQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes), VALID_QUALIFIERS) .setRequired(true); } @Override public void handle(org.sonar.api.server.ws.Request wsRequest, Response wsResponse) throws Exception { SearchWsResponse searchWsResponse = doHandle(toSearchWsRequest(wsRequest)); writeProtobuf(searchWsResponse, wsRequest, wsResponse); } private static SearchRequest toSearchWsRequest(org.sonar.api.server.ws.Request request) { return new SearchRequest() .setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS)) .setQuery(request.param(Param.TEXT_QUERY)) .setPage(request.mandatoryParamAsInt(Param.PAGE)) .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE)); } private SearchWsResponse doHandle(SearchRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { ComponentQuery esQuery = buildEsQuery(request); SearchIdResult<String> results = componentIndex.search(esQuery, new SearchOptions().setPage(request.getPage(), request.getPageSize())); List<EntityDto> components = dbClient.entityDao().selectByUuids(dbSession, results.getUuids()); Map<String, String> projectKeysByUuids = searchProjectsKeysByUuids(dbSession, components); return buildResponse(components, projectKeysByUuids, Paging.forPageIndex(request.getPage()).withPageSize(request.getPageSize()).andTotal((int) results.getTotal())); } } private Map<String, String> searchProjectsKeysByUuids(DbSession dbSession, List<EntityDto> entities) { Set<String> projectUuidsToSearch = entities.stream() .map(EntityDto::getAuthUuid) .collect(Collectors.toSet()); List<EntityDto> projects = dbClient.entityDao().selectByUuids(dbSession, projectUuidsToSearch); return projects.stream().collect(toMap(EntityDto::getUuid, EntityDto::getKey)); } private static ComponentQuery buildEsQuery(SearchRequest request) { return ComponentQuery.builder() .setQuery(request.getQuery()) .setQualifiers(request.getQualifiers()) .build(); } private static SearchWsResponse buildResponse(List<EntityDto> components, Map<String, String> projectKeysByUuids, Paging paging) { SearchWsResponse.Builder responseBuilder = SearchWsResponse.newBuilder(); responseBuilder.getPagingBuilder() .setPageIndex(paging.pageIndex()) .setPageSize(paging.pageSize()) .setTotal(paging.total()) .build(); components.stream() .map(dto -> dtoToComponent(dto, projectKeysByUuids.get(dto.getAuthUuid()))) .forEach(responseBuilder::addComponents); return responseBuilder.build(); } private static Components.Component dtoToComponent(EntityDto dto, String projectKey) { Components.Component.Builder builder = Components.Component.newBuilder() .setKey(dto.getKey()) .setProject(projectKey) .setName(dto.getName()) .setQualifier(dto.getQualifier()); return builder.build(); } static class SearchRequest { private List<String> qualifiers; private Integer page; private Integer pageSize; private String query; public List<String> getQualifiers() { return qualifiers; } public SearchRequest setQualifiers(List<String> qualifiers) { this.qualifiers = requireNonNull(qualifiers); return this; } @CheckForNull public Integer getPage() { return page; } public SearchRequest setPage(int page) { this.page = page; return this; } @CheckForNull public Integer getPageSize() { return pageSize; } public SearchRequest setPageSize(int pageSize) { this.pageSize = pageSize; return this; } @CheckForNull public String getQuery() { return query; } public SearchRequest setQuery(@Nullable String query) { this.query = query; return this; } } }
8,225
37.619718
153
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SearchProjectsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.core.platform.EditionProvider.Edition; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; import org.sonar.db.property.PropertyDto; import org.sonar.db.property.PropertyQuery; import org.sonar.server.component.ws.FilterParser.Criterion; import org.sonar.server.component.ws.SearchProjectsAction.SearchResults.SearchResultsBuilder; import org.sonar.server.es.Facets; import org.sonar.server.es.SearchIdResult; import org.sonar.server.es.SearchOptions; import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.measure.index.ProjectMeasuresIndex; import org.sonar.server.measure.index.ProjectMeasuresQuery; import org.sonar.server.project.Visibility; import org.sonar.server.qualitygate.ProjectsInWarning; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Common; import org.sonarqube.ws.Components.Component; import org.sonarqube.ws.Components.SearchProjectsWsResponse; import static com.google.common.base.MoreObjects.firstNonNull; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.collect.Sets.newHashSet; import static java.util.Collections.emptyList; import static java.util.Collections.emptyMap; import static java.util.Objects.requireNonNull; import static java.util.Optional.ofNullable; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.api.server.ws.WebService.Param.FACETS; import static org.sonar.api.server.ws.WebService.Param.FIELDS; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.db.measure.ProjectMeasuresIndexerIterator.METRIC_KEYS; import static org.sonar.server.component.ws.ProjectMeasuresQueryFactory.IS_FAVORITE_CRITERION; import static org.sonar.server.component.ws.ProjectMeasuresQueryFactory.newProjectMeasuresQuery; import static org.sonar.server.component.ws.ProjectMeasuresQueryValidator.NON_METRIC_SORT_KEYS; import static org.sonar.server.measure.index.ProjectMeasuresQuery.SORT_BY_LAST_ANALYSIS_DATE; import static org.sonar.server.measure.index.ProjectMeasuresQuery.SORT_BY_NAME; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.component.ComponentsWsParameters.ACTION_SEARCH_PROJECTS; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_FILTER; import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_LANGUAGES; import static org.sonarqube.ws.client.project.ProjectsWsParameters.FILTER_TAGS; public class SearchProjectsAction implements ComponentsWsAction { public static final int MAX_PAGE_SIZE = 500; public static final int DEFAULT_PAGE_SIZE = 100; private static final String ALL = "_all"; private static final String ANALYSIS_DATE = "analysisDate"; private static final String LEAK_PERIOD_DATE = "leakPeriodDate"; private static final String METRIC_LEAK_PROJECTS_KEY = "leak_projects"; private static final String HTML_POSSIBLE_VALUES_TEXT = "The possible values are:"; private static final String HTML_UL_START_TAG = "<ul>"; private static final String HTML_UL_END_TAG = "</ul>"; private static final Set<String> POSSIBLE_FIELDS = newHashSet(ALL, ANALYSIS_DATE, LEAK_PERIOD_DATE); private final DbClient dbClient; private final ProjectMeasuresIndex index; private final UserSession userSession; private final ProjectsInWarning projectsInWarning; private final PlatformEditionProvider editionProvider; private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker; public SearchProjectsAction(DbClient dbClient, ProjectMeasuresIndex index, UserSession userSession, ProjectsInWarning projectsInWarning, PlatformEditionProvider editionProvider, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) { this.dbClient = dbClient; this.index = index; this.userSession = userSession; this.projectsInWarning = projectsInWarning; this.editionProvider = editionProvider; this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_SEARCH_PROJECTS) .setSince("6.2") .setDescription("Search for projects") .addPagingParams(DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE) .setInternal(true) .setChangelog( new Change("8.3", "Add 'qualifier' filter and facet"), new Change("8.0", "Field 'id' from response has been removed")) .setResponseExample(getClass().getResource("search_projects-example.json")) .setHandler(this); action.createFieldsParam(POSSIBLE_FIELDS) .setDescription("Comma-separated list of the fields to be returned in response") .setSince("6.4"); action.createParam(FACETS) .setDescription("Comma-separated list of the facets to be computed. No facet is computed by default.") .setPossibleValues(Arrays.stream(ProjectMeasuresIndex.Facet.values()) .map(ProjectMeasuresIndex.Facet::getName) .sorted() .toList()); action .createParam(PARAM_FILTER) .setMinimumLength(2) .setDescription("Filter of projects on name, key, measure value, quality gate, language, tag or whether a project is a favorite or not.<br>" + "The filter must be encoded to form a valid URL (for example '=' must be replaced by '%3D').<br>" + "Examples of use:" + HTML_UL_START_TAG + " <li>to filter my favorite projects with a failed quality gate and a coverage greater than or equals to 60% and a coverage strictly lower than 80%:<br>" + " <code>filter=\"alert_status = ERROR and isFavorite and coverage >= 60 and coverage < 80\"</code></li>" + " <li>to filter projects with a reliability, security and maintainability rating equals or worse than B:<br>" + " <code>filter=\"reliability_rating>=2 and security_rating>=2 and sqale_rating>=2\"</code></li>" + " <li>to filter projects without duplication data:<br>" + " <code>filter=\"duplicated_lines_density = NO_DATA\"</code></li>" + HTML_UL_END_TAG + "To filter on project name or key, use the 'query' keyword, for instance : <code>filter='query = \"Sonar\"'</code>.<br>" + "<br>" + "To filter on a numeric metric, provide the metric key.<br>" + "These are the supported metric keys:<br>" + HTML_UL_START_TAG + METRIC_KEYS.stream().sorted().map(key -> "<li>" + key + "</li>").collect(Collectors.joining()) + HTML_UL_END_TAG + "<br>" + "To filter on a rating, provide the corresponding metric key (ex: reliability_rating for reliability rating).<br>" + HTML_POSSIBLE_VALUES_TEXT + HTML_UL_START_TAG + " <li>'1' for rating A</li>" + " <li>'2' for rating B</li>" + " <li>'3' for rating C</li>" + " <li>'4' for rating D</li>" + " <li>'5' for rating E</li>" + HTML_UL_END_TAG + "To filter on a Quality Gate status use the metric key 'alert_status'. Only the '=' operator can be used.<br>" + HTML_POSSIBLE_VALUES_TEXT + HTML_UL_START_TAG + " <li>'OK' for Passed</li>" + " <li>'WARN' for Warning</li>" + " <li>'ERROR' for Failed</li>" + HTML_UL_END_TAG + "To filter on languages use the 'languages' keyword: " + HTML_UL_START_TAG + " <li>to filter on a single language you can use 'languages = java'</li>" + " <li>to filter on several languages you must use 'languages IN (java, js)'</li>" + HTML_UL_END_TAG + "Use the WS api/languages/list to find the key of a language.<br> " + "To filter on tags use the 'tags' keyword:" + HTML_UL_START_TAG + " <li>to filter on one tag you can use <code>tags = finance</code></li>" + " <li>to filter on several tags you must use <code>tags in (offshore, java)</code></li>" + HTML_UL_END_TAG + "To filter on a qualifier use key 'qualifier'. Only the '=' operator can be used.<br>" + HTML_POSSIBLE_VALUES_TEXT + HTML_UL_START_TAG + " <li>TRK - for projects</li>" + " <li>APP - for applications</li>" + HTML_UL_END_TAG); action.createParam(Param.SORT) .setDescription("Sort projects by numeric metric key, quality gate status (using '%s'), last analysis date (using '%s'), or by project name.", ALERT_STATUS_KEY, SORT_BY_LAST_ANALYSIS_DATE, PARAM_FILTER) .setDefaultValue(SORT_BY_NAME) .setPossibleValues( Stream.concat(METRIC_KEYS.stream(), NON_METRIC_SORT_KEYS.stream()).sorted().toList()) .setSince("6.4"); action.createParam(Param.ASCENDING) .setDescription("Ascending sort") .setBooleanPossibleValues() .setDefaultValue(true); } @Override public void handle(Request httpRequest, Response httpResponse) throws Exception { SearchProjectsWsResponse response = doHandle(toRequest(httpRequest)); writeProtobuf(response, httpRequest, httpResponse); } private SearchProjectsWsResponse doHandle(SearchProjectsRequest request) { try (DbSession dbSession = dbClient.openSession(false)) { SearchResults searchResults = searchData(dbSession, request); boolean needIssueSync = dbClient.branchDao().hasAnyBranchWhereNeedIssueSync(dbSession, true); return buildResponse(request, searchResults, needIssueSync); } } private SearchResults searchData(DbSession dbSession, SearchProjectsRequest request) { Set<String> favoriteProjectUuids = loadFavoriteProjectUuids(dbSession); List<Criterion> criteria = FilterParser.parse(firstNonNull(request.getFilter(), "")); ProjectMeasuresQuery query = newProjectMeasuresQuery(criteria, hasFavoriteFilter(criteria) ? favoriteProjectUuids : null) .setIgnoreWarning(projectsInWarning.count() == 0L) .setSort(request.getSort()) .setAsc(request.getAsc()); Set<String> qualifiersBasedOnEdition = getQualifiersBasedOnEdition(query); query.setQualifiers(qualifiersBasedOnEdition); ProjectMeasuresQueryValidator.validate(query); SearchIdResult<String> esResults = index.search(query, new SearchOptions() .addFacets(request.getFacets()) .setPage(request.getPage(), request.getPageSize())); List<String> projectUuids = esResults.getUuids(); Ordering<ProjectDto> ordering = Ordering.explicit(projectUuids).onResultOf(ProjectDto::getUuid); List<ProjectDto> projects = ordering.immutableSortedCopy(dbClient.projectDao().selectByUuids(dbSession, new HashSet<>(projectUuids))); Map<String, BranchDto> mainBranchByUuid = dbClient.branchDao().selectMainBranchesByProjectUuids(dbSession, projectUuids) .stream() .collect(Collectors.toMap(BranchDto::getUuid, b -> b)); List<SnapshotDto> snapshots = getSnapshots(dbSession, request, mainBranchByUuid.keySet()); Map<String, SnapshotDto> analysisByProjectUuid = snapshots.stream() .collect(Collectors.toMap(s -> mainBranchByUuid.get(s.getRootComponentUuid()).getProjectUuid(), s -> s)); Map<String, Long> applicationsBranchLeakPeriod = getApplicationsLeakPeriod(dbSession, request, qualifiersBasedOnEdition, mainBranchByUuid.keySet()); Map<String, Long> applicationsLeakPeriod = applicationsBranchLeakPeriod.entrySet() .stream() .collect(Collectors.toMap(e -> mainBranchByUuid.get(e.getKey()).getProjectUuid(), Entry::getValue)); List<String> projectsInsync = getProjectUuidsWithBranchesNeedIssueSync(dbSession, Sets.newHashSet(projectUuids)); return SearchResultsBuilder.builder() .projects(projects) .favoriteProjectUuids(favoriteProjectUuids) .searchResults(esResults) .analysisByProjectUuid(analysisByProjectUuid) .applicationsLeakPeriods(applicationsLeakPeriod) .projectsWithIssuesInSync(projectsInsync) .query(query) .build(); } private List<String> getProjectUuidsWithBranchesNeedIssueSync(DbSession dbSession, Set<String> projectUuids) { return issueIndexSyncProgressChecker.findProjectUuidsWithIssuesSyncNeed(dbSession, projectUuids); } private Set<String> getQualifiersBasedOnEdition(ProjectMeasuresQuery query) { Set<String> availableQualifiers = getQualifiersFromEdition(); Set<String> requestQualifiers = query.getQualifiers().orElse(availableQualifiers); Set<String> resolvedQualifiers = requestQualifiers.stream() .filter(availableQualifiers::contains) .collect(Collectors.toSet()); if (!resolvedQualifiers.isEmpty()) { return resolvedQualifiers; } else { throw new IllegalArgumentException("Invalid qualifier, available are: " + String.join(",", availableQualifiers)); } } private Set<String> getQualifiersFromEdition() { Optional<Edition> edition = editionProvider.get(); if (!edition.isPresent()) { return Sets.newHashSet(Qualifiers.PROJECT); } return switch (edition.get()) { case ENTERPRISE, DATACENTER, DEVELOPER -> Sets.newHashSet(Qualifiers.PROJECT, Qualifiers.APP); default -> Sets.newHashSet(Qualifiers.PROJECT); }; } private static boolean hasFavoriteFilter(List<Criterion> criteria) { return criteria.stream() .map(Criterion::getKey) .anyMatch(IS_FAVORITE_CRITERION::equalsIgnoreCase); } private Set<String> loadFavoriteProjectUuids(DbSession dbSession) { if (!userSession.isLoggedIn()) { return Collections.emptySet(); } List<PropertyDto> props = dbClient.propertiesDao().selectByQuery( PropertyQuery.builder() .setUserUuid(userSession.getUuid()) .setKey("favourite") .build(), dbSession); Set<String> favoriteDbUuids = props.stream() .map(PropertyDto::getEntityUuid) .filter(Objects::nonNull) .collect(Collectors.toSet()); return dbClient.projectDao().selectByUuids(dbSession, favoriteDbUuids).stream() .map(ProjectDto::getUuid) .collect(Collectors.toSet()); } private List<SnapshotDto> getSnapshots(DbSession dbSession, SearchProjectsRequest request, Collection<String> mainBranchUuids) { if (request.getAdditionalFields().contains(ANALYSIS_DATE) || request.getAdditionalFields().contains(LEAK_PERIOD_DATE)) { return dbClient.snapshotDao().selectLastAnalysesByRootComponentUuids(dbSession, mainBranchUuids); } return emptyList(); } private Map<String, Long> getApplicationsLeakPeriod(DbSession dbSession, SearchProjectsRequest request, Set<String> qualifiers, Collection<String> mainBranchUuids) { if (qualifiers.contains(Qualifiers.APP) && request.getAdditionalFields().contains(LEAK_PERIOD_DATE)) { return dbClient.liveMeasureDao().selectByComponentUuidsAndMetricKeys(dbSession, mainBranchUuids, Collections.singleton(METRIC_LEAK_PROJECTS_KEY)) .stream() .filter(lm -> !Objects.isNull(lm.getDataAsString())) .map(lm -> Maps.immutableEntry(lm.getComponentUuid(), ApplicationLeakProjects.parse(lm.getDataAsString()).getOldestLeak())) .filter(entry -> entry.getValue().isPresent()) .collect(Collectors.toMap(Entry::getKey, entry -> entry.getValue().get().getLeak())); } return emptyMap(); } private static SearchProjectsRequest toRequest(Request httpRequest) { RequestBuilder request = new RequestBuilder() .setFilter(httpRequest.param(PARAM_FILTER)) .setSort(httpRequest.mandatoryParam(Param.SORT)) .setAsc(httpRequest.mandatoryParamAsBoolean(Param.ASCENDING)) .setPage(httpRequest.mandatoryParamAsInt(Param.PAGE)) .setPageSize(httpRequest.mandatoryParamAsInt(Param.PAGE_SIZE)); if (httpRequest.hasParam(FACETS)) { request.setFacets(httpRequest.mandatoryParamAsStrings(FACETS)); } if (httpRequest.hasParam(FIELDS)) { List<String> paramsAsString = httpRequest.mandatoryParamAsStrings(FIELDS); if (paramsAsString.contains(ALL)) { request.setAdditionalFields(List.of(ANALYSIS_DATE, LEAK_PERIOD_DATE)); } else { request.setAdditionalFields(paramsAsString); } } return request.build(); } private SearchProjectsWsResponse buildResponse(SearchProjectsRequest request, SearchResults searchResults, boolean needIssueSync) { Function<ProjectDto, Component> dbToWsComponent = new DbToWsComponent(request, searchResults, userSession.isLoggedIn(), needIssueSync); return Stream.of(SearchProjectsWsResponse.newBuilder()) .map(response -> response.setPaging(Common.Paging.newBuilder() .setPageIndex(request.getPage()) .setPageSize(request.getPageSize()) .setTotal(searchResults.total))) .map(response -> { searchResults.projects.stream() .map(dbToWsComponent) .forEach(response::addComponents); return response; }) .map(response -> addFacets(searchResults, response)) .map(SearchProjectsWsResponse.Builder::build) .findFirst() .orElseThrow(() -> new IllegalStateException("SearchProjectsWsResponse not built")); } private static SearchProjectsWsResponse.Builder addFacets(SearchResults searchResults, SearchProjectsWsResponse.Builder wsResponse) { Facets esFacets = searchResults.facets; EsToWsFacet esToWsFacet = new EsToWsFacet(); searchResults.query.getLanguages().ifPresent(languages -> addMandatoryValuesToFacet(esFacets, FILTER_LANGUAGES, languages)); searchResults.query.getTags().ifPresent(tags -> addMandatoryValuesToFacet(esFacets, FILTER_TAGS, tags)); Common.Facets wsFacets = esFacets.getAll().entrySet().stream() .map(esToWsFacet) .collect(Collector.of( Common.Facets::newBuilder, Common.Facets.Builder::addFacets, (result1, result2) -> { throw new IllegalStateException("Parallel execution forbidden"); }, Common.Facets.Builder::build)); wsResponse.setFacets(wsFacets); return wsResponse; } private static void addMandatoryValuesToFacet(Facets facets, String facetName, Iterable<String> mandatoryValues) { Map<String, Long> buckets = facets.get(facetName); if (buckets == null) { return; } for (String mandatoryValue : mandatoryValues) { if (!buckets.containsKey(mandatoryValue)) { buckets.put(mandatoryValue, 0L); } } } private static class EsToWsFacet implements Function<Entry<String, LinkedHashMap<String, Long>>, Common.Facet> { private final BucketToFacetValue bucketToFacetValue = new BucketToFacetValue(); private final Common.Facet.Builder wsFacet = Common.Facet.newBuilder(); @Override public Common.Facet apply(Entry<String, LinkedHashMap<String, Long>> esFacet) { wsFacet .clear() .setProperty(esFacet.getKey()); LinkedHashMap<String, Long> buckets = esFacet.getValue(); if (buckets != null) { buckets.entrySet() .stream() .map(bucketToFacetValue) .forEach(wsFacet::addValues); } else { wsFacet.addAllValues(Collections.emptyList()); } return wsFacet.build(); } } private static class BucketToFacetValue implements Function<Entry<String, Long>, Common.FacetValue> { private final Common.FacetValue.Builder facetValue; private BucketToFacetValue() { this.facetValue = Common.FacetValue.newBuilder(); } @Override public Common.FacetValue apply(Entry<String, Long> bucket) { return facetValue .clear() .setVal(bucket.getKey()) .setCount(bucket.getValue()) .build(); } } private static class DbToWsComponent implements Function<ProjectDto, Component> { private final SearchProjectsRequest request; private final Component.Builder wsComponent; private final Set<String> favoriteProjectUuids; private final List<String> projectsWithIssuesInSync; private final boolean isUserLoggedIn; private final Map<String, SnapshotDto> analysisByProjectUuid; private final Map<String, Long> applicationsLeakPeriod; private final boolean needIssueSync; private DbToWsComponent(SearchProjectsRequest request, SearchResults searchResults, boolean isUserLoggedIn, boolean needIssueSync) { this.request = request; this.analysisByProjectUuid = searchResults.analysisByProjectUuid; this.applicationsLeakPeriod = searchResults.applicationsLeakPeriods; this.wsComponent = Component.newBuilder(); this.favoriteProjectUuids = searchResults.favoriteProjectUuids; this.projectsWithIssuesInSync = searchResults.projectsWithIssuesInSync; this.isUserLoggedIn = isUserLoggedIn; this.needIssueSync = needIssueSync; } @Override public Component apply(ProjectDto dbProject) { wsComponent .clear() .setKey(dbProject.getKey()) .setName(dbProject.getName()) .setQualifier(dbProject.getQualifier()) .setVisibility(Visibility.getLabel(dbProject.isPrivate())); wsComponent.getTagsBuilder().addAllTags(dbProject.getTags()); SnapshotDto snapshotDto = analysisByProjectUuid.get(dbProject.getUuid()); if (snapshotDto != null) { if (request.getAdditionalFields().contains(ANALYSIS_DATE)) { wsComponent.setAnalysisDate(formatDateTime(snapshotDto.getCreatedAt())); } if (request.getAdditionalFields().contains(LEAK_PERIOD_DATE)) { if (Qualifiers.APP.equals(dbProject.getQualifier())) { ofNullable(applicationsLeakPeriod.get(dbProject.getUuid())).ifPresent(leakPeriodDate -> wsComponent.setLeakPeriodDate(formatDateTime(leakPeriodDate))); } else { ofNullable(snapshotDto.getPeriodDate()).ifPresent(leakPeriodDate -> wsComponent.setLeakPeriodDate(formatDateTime(leakPeriodDate))); } } } if (isUserLoggedIn) { wsComponent.setIsFavorite(favoriteProjectUuids.contains(dbProject.getUuid())); } if (Qualifiers.APP.equals(dbProject.getQualifier())) { wsComponent.setNeedIssueSync(needIssueSync); } else { wsComponent.setNeedIssueSync(projectsWithIssuesInSync.contains(dbProject.getUuid())); } return wsComponent.build(); } } public static class SearchResults { private final List<ProjectDto> projects; private final Set<String> favoriteProjectUuids; private final List<String> projectsWithIssuesInSync; private final Facets facets; private final Map<String, SnapshotDto> analysisByProjectUuid; private final Map<String, Long> applicationsLeakPeriods; private final ProjectMeasuresQuery query; private final int total; private SearchResults(List<ProjectDto> projects, Set<String> favoriteProjectUuids, SearchIdResult<String> searchResults, Map<String, SnapshotDto> analysisByProjectUuid, Map<String, Long> applicationsLeakPeriods, List<String> projectsWithIssuesInSync, ProjectMeasuresQuery query) { this.projects = projects; this.favoriteProjectUuids = favoriteProjectUuids; this.projectsWithIssuesInSync = projectsWithIssuesInSync; this.total = (int) searchResults.getTotal(); this.facets = searchResults.getFacets(); this.analysisByProjectUuid = analysisByProjectUuid; this.applicationsLeakPeriods = applicationsLeakPeriods; this.query = query; } public static final class SearchResultsBuilder { private List<ProjectDto> projects; private Set<String> favoriteProjectUuids; private List<String> projectsWithIssuesInSync; private Map<String, SnapshotDto> analysisByProjectUuid; private Map<String, Long> applicationsLeakPeriods; private ProjectMeasuresQuery query; private SearchIdResult<String> searchResults; private SearchResultsBuilder() { } public static SearchResultsBuilder builder() { return new SearchResultsBuilder(); } public SearchResultsBuilder projects(List<ProjectDto> projects) { this.projects = projects; return this; } public SearchResultsBuilder favoriteProjectUuids(Set<String> favoriteProjectUuids) { this.favoriteProjectUuids = favoriteProjectUuids; return this; } public SearchResultsBuilder projectsWithIssuesInSync(List<String> projectsWithIssuesInSync) { this.projectsWithIssuesInSync = projectsWithIssuesInSync; return this; } public SearchResultsBuilder analysisByProjectUuid(Map<String, SnapshotDto> analysisByProjectUuid) { this.analysisByProjectUuid = analysisByProjectUuid; return this; } public SearchResultsBuilder applicationsLeakPeriods(Map<String, Long> applicationsLeakPeriods) { this.applicationsLeakPeriods = applicationsLeakPeriods; return this; } public SearchResultsBuilder query(ProjectMeasuresQuery query) { this.query = query; return this; } public SearchResultsBuilder searchResults(SearchIdResult<String> searchResults) { this.searchResults = searchResults; return this; } public SearchResults build() { return new SearchResults(projects, favoriteProjectUuids, searchResults, analysisByProjectUuid, applicationsLeakPeriods, projectsWithIssuesInSync, query); } } } static class SearchProjectsRequest { private final int page; private final int pageSize; private final String filter; private final List<String> facets; private final String sort; private final Boolean asc; private final List<String> additionalFields; private SearchProjectsRequest(RequestBuilder builder) { this.page = builder.page; this.pageSize = builder.pageSize; this.filter = builder.filter; this.facets = builder.facets; this.sort = builder.sort; this.asc = builder.asc; this.additionalFields = builder.additionalFields; } @CheckForNull public String getFilter() { return filter; } public List<String> getFacets() { return facets; } @CheckForNull public String getSort() { return sort; } public int getPageSize() { return pageSize; } public int getPage() { return page; } @CheckForNull public Boolean getAsc() { return asc; } public List<String> getAdditionalFields() { return additionalFields; } public static RequestBuilder builder() { return new RequestBuilder(); } } static class RequestBuilder { private Integer page; private Integer pageSize; private String filter; private List<String> facets = new ArrayList<>(); private String sort; private Boolean asc; private List<String> additionalFields = new ArrayList<>(); private RequestBuilder() { // enforce static factory method } public RequestBuilder setFilter(@Nullable String filter) { this.filter = filter; return this; } public RequestBuilder setFacets(List<String> facets) { this.facets = requireNonNull(facets); return this; } public RequestBuilder setPage(int page) { this.page = page; return this; } public RequestBuilder setPageSize(int pageSize) { this.pageSize = pageSize; return this; } public RequestBuilder setSort(@Nullable String sort) { this.sort = sort; return this; } public RequestBuilder setAsc(boolean asc) { this.asc = asc; return this; } public RequestBuilder setAdditionalFields(List<String> additionalFields) { this.additionalFields = requireNonNull(additionalFields, "additional fields cannot be null"); return this; } public SearchProjectsRequest build() { if (page == null) { page = 1; } if (pageSize == null) { pageSize = DEFAULT_PAGE_SIZE; } checkArgument(pageSize <= MAX_PAGE_SIZE, "Page size must not be greater than %s", MAX_PAGE_SIZE); return new SearchProjectsRequest(this); } } }
30,056
40.457931
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/ShowAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.IntStream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Components; import org.sonarqube.ws.Components.ShowWsResponse; import static org.sonar.server.component.ws.ComponentDtoToWsComponent.componentDtoToWsComponent; import static org.sonar.server.component.ws.ComponentDtoToWsComponent.projectOrAppToWsComponent; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_BRANCH; import static org.sonar.server.component.ws.MeasuresWsParameters.PARAM_PULL_REQUEST; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.component.ComponentsWsParameters.ACTION_SHOW; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_COMPONENT; public class ShowAction implements ComponentsWsAction { private static final Set<String> PROJECT_OR_APP_QUALIFIERS = Set.of(Qualifiers.PROJECT, Qualifiers.APP); private static final Set<String> APP_VIEW_OR_SUBVIEW_QUALIFIERS = Set.of(Qualifiers.APP, Qualifiers.VIEW, Qualifiers.SUBVIEW); private final UserSession userSession; private final DbClient dbClient; private final ComponentFinder componentFinder; private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker; public ShowAction(UserSession userSession, DbClient dbClient, ComponentFinder componentFinder, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) { this.userSession = userSession; this.dbClient = dbClient; this.componentFinder = componentFinder; this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_SHOW) .setDescription("Returns a component (file, directory, project, portfolio…) and its ancestors. " + "The ancestors are ordered from the parent to the root project. " + "Requires the following permission: 'Browse' on the project of the specified component.") .setResponseExample(getClass().getResource("show-example.json")) .setSince("5.4") .setChangelog( new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("7.6", String.format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT))) .setHandler(this); action.createParam(PARAM_COMPONENT) .setDescription("Component key") .setRequired(true) .setExampleValue(KEY_PROJECT_EXAMPLE_001); action.createParam(PARAM_BRANCH) .setDescription("Branch key. Not available in the community edition.") .setExampleValue(KEY_BRANCH_EXAMPLE_001) .setSince("6.6"); action.createParam(PARAM_PULL_REQUEST) .setDescription("Pull request id. Not available in the community edition.") .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001) .setSince("7.1"); } @Override public void handle(org.sonar.api.server.ws.Request request, Response response) throws Exception { Request showRequest = toShowWsRequest(request); ShowWsResponse showWsResponse = doHandle(showRequest); writeProtobuf(showWsResponse, request, response); } private ShowWsResponse doHandle(Request request) { try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto component = loadComponent(dbSession, request); userSession.checkComponentPermission(UserRole.USER, component); Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByComponentUuid(dbSession, component.branchUuid()); List<ComponentDto> ancestors = dbClient.componentDao().selectAncestors(dbSession, component); return buildResponse(dbSession, component, ancestors, lastAnalysis.orElse(null), request); } } private ComponentDto loadComponent(DbSession dbSession, Request request) { String componentKey = request.getComponentKey(); String branch = request.getBranch(); String pullRequest = request.getPullRequest(); return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest); } private ShowWsResponse buildResponse(DbSession dbSession, ComponentDto component, List<ComponentDto> orderedAncestors, @Nullable SnapshotDto lastAnalysis, Request request) { ShowWsResponse.Builder response = ShowWsResponse.newBuilder(); response.setComponent(toWsComponent(dbSession, component, lastAnalysis, request)); addAncestorsToResponse(dbSession, response, orderedAncestors, lastAnalysis, request); return response.build(); } private void addAncestorsToResponse(DbSession dbSession, ShowWsResponse.Builder response, List<ComponentDto> orderedAncestors, @Nullable SnapshotDto lastAnalysis, Request request) { // ancestors are ordered from root to leaf, whereas it's the opposite in WS response int size = orderedAncestors.size() - 1; IntStream.rangeClosed(0, size).forEach( index -> response.addAncestors(toWsComponent(dbSession, orderedAncestors.get(size - index), lastAnalysis, request))); } private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component, @Nullable SnapshotDto lastAnalysis, Request request) { // project or application if (isMainBranchOfProjectOrApp(component, dbSession)) { ProjectDto project = dbClient.projectDao().selectProjectOrAppByKey(dbSession, component.getKey()) .orElseThrow(() -> new IllegalStateException("Project is in invalid state.")); boolean needIssueSync = needIssueSync(dbSession, component, project); return projectOrAppToWsComponent(project, lastAnalysis).setNeedIssueSync(needIssueSync); } // parent project can an application. For components in portfolios, it will be null ProjectDto parentProject = dbClient.projectDao().selectByBranchUuid(dbSession, component.branchUuid()).orElse(null); boolean needIssueSync = needIssueSync(dbSession, component, parentProject); // if this is a project calculated in a portfolio or app, we need to include the original branch name (if any) if (component.getCopyComponentUuid() != null) { String branch = dbClient.branchDao().selectByUuid(dbSession, component.getCopyComponentUuid()) .filter(b -> !b.isMain()) .map(BranchDto::getKey) .orElse(null); return componentDtoToWsComponent(component, parentProject, lastAnalysis, true, branch, null) .setNeedIssueSync(needIssueSync); } // branch won't exist for portfolios Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, component.branchUuid()); if (branchDto.isPresent() && !branchDto.get().isMain()) { return componentDtoToWsComponent(component, parentProject, lastAnalysis, false, request.branch, request.pullRequest) .setNeedIssueSync(needIssueSync); } else { return componentDtoToWsComponent(component, parentProject, lastAnalysis, true, null, null) .setNeedIssueSync(needIssueSync); } } private boolean isMainBranchOfProjectOrApp(ComponentDto component, DbSession dbSession) { if (!PROJECT_OR_APP_QUALIFIERS.contains(component.qualifier()) || !Scopes.PROJECT.equals(component.scope())) { return false; } Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, component.branchUuid()); return branchDto.isPresent() && branchDto.get().isMain(); } private boolean needIssueSync(DbSession dbSession, ComponentDto component, @Nullable ProjectDto projectDto) { if (projectDto == null || APP_VIEW_OR_SUBVIEW_QUALIFIERS.contains(component.qualifier())) { return issueIndexSyncProgressChecker.isIssueSyncInProgress(dbSession); } return issueIndexSyncProgressChecker.doProjectNeedIssueSync(dbSession, projectDto.getUuid()); } private static Request toShowWsRequest(org.sonar.api.server.ws.Request request) { return new Request() .setComponentKey(request.mandatoryParam(PARAM_COMPONENT)) .setBranch(request.param(PARAM_BRANCH)) .setPullRequest(request.param(PARAM_PULL_REQUEST)); } private static class Request { private String componentKey; private String branch; private String pullRequest; public String getComponentKey() { return componentKey; } public Request setComponentKey(String componentKey) { this.componentKey = componentKey; return this; } @CheckForNull public String getBranch() { return branch; } public Request setBranch(@Nullable String branch) { this.branch = branch; return this; } @CheckForNull public String getPullRequest() { return pullRequest; } public Request setPullRequest(@Nullable String pullRequest) { this.pullRequest = pullRequest; return this; } } }
10,701
44.156118
135
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SuggestionCategory.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import org.sonar.api.resources.Qualifiers; import static java.util.Arrays.stream; public enum SuggestionCategory { VIEW(Qualifiers.VIEW), SUBVIEW(Qualifiers.SUBVIEW), APP(Qualifiers.APP), PROJECT(Qualifiers.PROJECT); private final String qualifier; SuggestionCategory(String qualifier) { this.qualifier = qualifier; } public String getName() { return qualifier; } public String getQualifier() { return qualifier; } public static SuggestionCategory getByName(String name) { return stream(values()).filter(c -> c.getName().equals(name)).findAny() .orElseThrow(() -> new IllegalStateException(String.format("Cannot find category for name '%s'.", name))); } }
1,594
30.27451
112
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/SuggestionsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.common.collect.ListMultimap; import com.google.common.html.HtmlEscapers; import com.google.common.io.Resources; import java.util.Arrays; import java.util.Collection; import java.util.Comparator; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.entity.EntityDto; import org.sonar.server.component.index.ComponentHit; import org.sonar.server.component.index.ComponentHitsPerQualifier; import org.sonar.server.component.index.ComponentIndex; import org.sonar.server.component.index.ComponentIndexResults; import org.sonar.server.component.index.SuggestionQuery; import org.sonar.server.es.newindex.DefaultIndexSettings; import org.sonar.server.favorite.FavoriteFinder; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Components.SuggestionsWsResponse; import org.sonarqube.ws.Components.SuggestionsWsResponse.Category; import org.sonarqube.ws.Components.SuggestionsWsResponse.Suggestion; import static java.util.Arrays.stream; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.sonar.api.web.UserRole.USER; import static org.sonar.server.component.index.SuggestionQuery.DEFAULT_LIMIT; import static org.sonar.server.es.newindex.DefaultIndexSettings.MINIMUM_NGRAM_LENGTH; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.Components.SuggestionsWsResponse.newBuilder; import static org.sonarqube.ws.client.component.ComponentsWsParameters.ACTION_SUGGESTIONS; public class SuggestionsAction implements ComponentsWsAction { static final String PARAM_QUERY = "s"; static final String PARAM_MORE = "more"; static final String PARAM_RECENTLY_BROWSED = "recentlyBrowsed"; static final String SHORT_INPUT_WARNING = "short_input"; private static final int MAXIMUM_RECENTLY_BROWSED = 50; private static final int EXTENDED_LIMIT = 20; private final ComponentIndex index; private final FavoriteFinder favoriteFinder; private final UserSession userSession; private final ResourceTypes resourceTypes; private final DbClient dbClient; public SuggestionsAction(DbClient dbClient, ComponentIndex index, FavoriteFinder favoriteFinder, UserSession userSession, ResourceTypes resourceTypes) { this.dbClient = dbClient; this.index = index; this.favoriteFinder = favoriteFinder; this.userSession = userSession; this.resourceTypes = resourceTypes; } @Override public void define(WebService.NewController context) { NewAction action = context.createAction(ACTION_SUGGESTIONS) .setDescription( "Internal WS for the top-right search engine. The result will contain component search results, grouped by their qualifiers.<p>" + "Each result contains:" + "<ul>" + "<li>the component key</li>" + "<li>the component's name (unescaped)</li>" + "<li>optionally a display name, which puts emphasis to matching characters (this text contains html tags and parts of the html-escaped name)</li>" + "</ul>") .setSince("4.2") .setInternal(true) .setHandler(this) .setResponseExample(Resources.getResource(this.getClass(), "suggestions-example.json")) .setChangelog( new Change("10.0", String.format("The use of 'BRC' as value for parameter '%s' is no longer supported", PARAM_MORE)), new Change("8.4", String.format("The use of 'DIR', 'FIL','UTS' as values for parameter '%s' is no longer supported", PARAM_MORE)), new Change("7.6", String.format("The use of 'BRC' as value for parameter '%s' is deprecated", PARAM_MORE))); action.createParam(PARAM_QUERY) .setRequired(false) .setMinimumLength(2) .setDescription("Search query: can contain several search tokens separated by spaces.") .setExampleValue("sonar"); action.createParam(PARAM_MORE) .setDescription("Category, for which to display the next " + EXTENDED_LIMIT + " results (skipping the first " + DEFAULT_LIMIT + " results)") .setPossibleValues(stream(SuggestionCategory.values()).map(SuggestionCategory::getName).toArray(String[]::new)) .setSince("6.4"); action.createParam(PARAM_RECENTLY_BROWSED) .setDescription("Comma separated list of component keys, that have recently been browsed by the user. Only the first " + MAXIMUM_RECENTLY_BROWSED + " items will be used. Order is not taken into account.") .setSince("6.4") .setExampleValue("org.sonarsource:sonarqube,some.other:project") .setRequired(false) .setMaxValuesAllowed(MAXIMUM_RECENTLY_BROWSED); } @Override public void handle(Request wsRequest, Response wsResponse) throws Exception { String query = wsRequest.param(PARAM_QUERY); String more = wsRequest.param(PARAM_MORE); Set<String> recentlyBrowsedKeys = getRecentlyBrowsedKeys(wsRequest); List<String> qualifiers = getQualifiers(more); int skip = more == null ? 0 : DEFAULT_LIMIT; int limit = more == null ? DEFAULT_LIMIT : EXTENDED_LIMIT; SuggestionsWsResponse searchWsResponse = loadSuggestions(query, skip, limit, recentlyBrowsedKeys, qualifiers); writeProtobuf(searchWsResponse, wsRequest, wsResponse); } private static Set<String> getRecentlyBrowsedKeys(Request wsRequest) { List<String> recentlyBrowsedParam = wsRequest.paramAsStrings(PARAM_RECENTLY_BROWSED); if (recentlyBrowsedParam == null) { return emptySet(); } return new HashSet<>(recentlyBrowsedParam); } private SuggestionsWsResponse loadSuggestions(@Nullable String query, int skip, int limit, Set<String> recentlyBrowsedKeys, List<String> qualifiers) { if (query == null) { return loadSuggestionsWithoutSearch(skip, limit, recentlyBrowsedKeys, qualifiers); } return loadSuggestionsWithSearch(query, skip, limit, recentlyBrowsedKeys, qualifiers); } /** * we are generating suggestions, by using (1) favorites and (2) recently browsed components (without searching in Elasticsearch) */ private SuggestionsWsResponse loadSuggestionsWithoutSearch(int skip, int limit, Set<String> recentlyBrowsedKeys, List<String> qualifiers) { List<EntityDto> favorites = favoriteFinder.list(); if (favorites.isEmpty() && recentlyBrowsedKeys.isEmpty()) { return newBuilder().build(); } try (DbSession dbSession = dbClient.openSession(false)) { Set<EntityDto> entities = new HashSet<>(favorites); if (!recentlyBrowsedKeys.isEmpty()) { entities.addAll(dbClient.entityDao().selectByKeys(dbSession, recentlyBrowsedKeys)); } List<EntityDto> authorizedEntities = userSession.keepAuthorizedEntities(USER, entities); ListMultimap<String, EntityDto> entityPerQualifier = authorizedEntities.stream() .collect(MoreCollectors.index(EntityDto::getQualifier)); if (entityPerQualifier.isEmpty()) { return newBuilder().build(); } Set<String> favoriteUuids = favorites.stream().map(EntityDto::getUuid).collect(Collectors.toSet()); Comparator<EntityDto> favoriteComparator = Comparator.comparing(c -> favoriteUuids.contains(c.getUuid()) ? -1 : +1); Comparator<EntityDto> comparator = favoriteComparator.thenComparing(EntityDto::getName); ComponentIndexResults componentsPerQualifiers = ComponentIndexResults.newBuilder().setQualifiers( qualifiers.stream().map(q -> { List<EntityDto> componentsOfThisQualifier = entityPerQualifier.get(q); List<ComponentHit> hits = componentsOfThisQualifier .stream() .sorted(comparator) .skip(skip) .limit(limit) .map(EntityDto::getUuid) .map(ComponentHit::new) .toList(); int totalHits = componentsOfThisQualifier.size(); return new ComponentHitsPerQualifier(q, hits, totalHits); })).build(); return buildResponse(recentlyBrowsedKeys, favoriteUuids, componentsPerQualifiers, authorizedEntities, skip + limit).build(); } } private SuggestionsWsResponse loadSuggestionsWithSearch(String query, int skip, int limit, Set<String> recentlyBrowsedKeys, List<String> qualifiers) { if (split(query).noneMatch(token -> token.length() >= MINIMUM_NGRAM_LENGTH)) { SuggestionsWsResponse.Builder queryBuilder = newBuilder(); getWarning(query).ifPresent(queryBuilder::setWarning); return queryBuilder.build(); } List<EntityDto> favorites = favoriteFinder.list(); Set<String> favoriteKeys = favorites.stream().map(EntityDto::getKey).collect(Collectors.toSet()); SuggestionQuery.Builder queryBuilder = SuggestionQuery.builder() .setQuery(query) .setRecentlyBrowsedKeys(recentlyBrowsedKeys) .setFavoriteKeys(favoriteKeys) .setQualifiers(qualifiers) .setSkip(skip) .setLimit(limit); ComponentIndexResults componentsPerQualifiers = searchInIndex(queryBuilder.build()); if (componentsPerQualifiers.isEmpty()) { return newBuilder().build(); } try (DbSession dbSession = dbClient.openSession(false)) { Set<String> entityUuids = componentsPerQualifiers.getQualifiers() .map(ComponentHitsPerQualifier::getHits) .flatMap(Collection::stream) .map(ComponentHit::getUuid) .collect(Collectors.toSet()); List<EntityDto> entities = dbClient.entityDao().selectByUuids(dbSession, entityUuids); Set<String> favoriteUuids = favorites.stream().map(EntityDto::getUuid).collect(Collectors.toSet()); SuggestionsWsResponse.Builder searchWsResponse = buildResponse(recentlyBrowsedKeys, favoriteUuids, componentsPerQualifiers, entities, skip + limit); getWarning(query).ifPresent(searchWsResponse::setWarning); return searchWsResponse.build(); } } private static Optional<String> getWarning(String query) { return split(query) .filter(token -> token.length() < MINIMUM_NGRAM_LENGTH) .findAny() .map(x -> SHORT_INPUT_WARNING); } private static Stream<String> split(String query) { return Arrays.stream(query.split(DefaultIndexSettings.SEARCH_TERM_TOKENIZER_PATTERN)); } private List<String> getQualifiers(@Nullable String more) { Set<String> availableQualifiers = resourceTypes.getAll().stream() .map(ResourceType::getQualifier) .collect(Collectors.toSet()); if (more == null) { return stream(SuggestionCategory.values()) .map(SuggestionCategory::getQualifier) .filter(availableQualifiers::contains) .toList(); } String qualifier = SuggestionCategory.getByName(more).getQualifier(); return availableQualifiers.contains(qualifier) ? singletonList(qualifier) : emptyList(); } private SuggestionsWsResponse.Builder buildResponse(Set<String> recentlyBrowsedKeys, Set<String> favoriteUuids, ComponentIndexResults componentsPerQualifiers, List<EntityDto> entities, int coveredItems) { Map<String, EntityDto> entitiesByUuids = entities.stream().collect(Collectors.toMap(EntityDto::getUuid, Function.identity())); return toResponse(componentsPerQualifiers, recentlyBrowsedKeys, favoriteUuids, entitiesByUuids, coveredItems); } private ComponentIndexResults searchInIndex(SuggestionQuery suggestionQuery) { return index.searchSuggestions(suggestionQuery); } private static SuggestionsWsResponse.Builder toResponse(ComponentIndexResults componentsPerQualifiers, Set<String> recentlyBrowsedKeys, Set<String> favoriteUuids, Map<String, EntityDto> entitiesByUuids, int coveredItems) { if (componentsPerQualifiers.isEmpty()) { return newBuilder(); } return newBuilder() .addAllResults(toCategories(componentsPerQualifiers, recentlyBrowsedKeys, favoriteUuids, entitiesByUuids, coveredItems)); } private static List<Category> toCategories(ComponentIndexResults componentsPerQualifiers, Set<String> recentlyBrowsedKeys, Set<String> favoriteUuids, Map<String, EntityDto> entitiesByUuids, int coveredItems) { return componentsPerQualifiers.getQualifiers().map(qualifier -> { List<Suggestion> suggestions = qualifier.getHits().stream() .map(hit -> toSuggestion(hit, recentlyBrowsedKeys, favoriteUuids, entitiesByUuids)) .filter(Optional::isPresent) .map(Optional::get) .toList(); return Category.newBuilder() .setQ(qualifier.getQualifier()) .setMore(Math.max(0, qualifier.getTotalHits() - coveredItems)) .addAllItems(suggestions) .build(); }).toList(); } /** * @return null when the component exists in Elasticsearch but not in database. That * occurs when failed indexing requests are been recovering. */ private static Optional<Suggestion> toSuggestion(ComponentHit hit, Set<String> recentlyBrowsedKeys, Set<String> favoriteUuids, Map<String, EntityDto> entitiesByUuids) { return Optional.ofNullable(entitiesByUuids.get(hit.getUuid())) .map(result -> Suggestion.newBuilder() .setKey(result.getKey()) .setName(result.getName()) .setMatch(hit.getHighlightedText().orElse(HtmlEscapers.htmlEscaper().escape(result.getName()))) .setIsRecentlyBrowsed(recentlyBrowsedKeys.contains(result.getKey())) .setIsFavorite(favoriteUuids.contains(result.getUuid())) .build()); } }
14,864
46.041139
170
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/TreeAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import com.google.common.base.Function; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.Paging; import org.sonar.api.web.UserRole; import org.sonar.core.i18n.I18n; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTreeQuery; import org.sonar.db.component.ComponentTreeQuery.Strategy; import org.sonar.db.project.ProjectDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Components; import org.sonarqube.ws.Components.TreeWsResponse; import static java.lang.String.CASE_INSENSITIVE_ORDER; import static java.lang.String.format; import static java.util.Collections.emptyMap; import static org.sonar.api.utils.Paging.offset; import static org.sonar.db.component.ComponentTreeQuery.Strategy.CHILDREN; import static org.sonar.db.component.ComponentTreeQuery.Strategy.LEAVES; import static org.sonar.server.component.ws.ComponentDtoToWsComponent.componentDtoToWsComponent; import static org.sonar.server.component.ws.ComponentDtoToWsComponent.projectOrAppToWsComponent; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; import static org.sonar.server.ws.WsParameterBuilder.createQualifiersParameter; import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext; import static org.sonar.server.ws.WsUtils.writeProtobuf; import static org.sonarqube.ws.client.component.ComponentsWsParameters.ACTION_TREE; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_BRANCH; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_COMPONENT; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_PULL_REQUEST; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_QUALIFIERS; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_STRATEGY; public class TreeAction implements ComponentsWsAction { private static final int MAX_SIZE = 500; private static final int QUERY_MINIMUM_LENGTH = 3; private static final String ALL_STRATEGY = "all"; private static final String CHILDREN_STRATEGY = "children"; private static final String LEAVES_STRATEGY = "leaves"; private static final Map<String, Strategy> STRATEGIES = ImmutableMap.of( ALL_STRATEGY, LEAVES, CHILDREN_STRATEGY, CHILDREN, LEAVES_STRATEGY, LEAVES); private static final String NAME_SORT = "name"; private static final String PATH_SORT = "path"; private static final String QUALIFIER_SORT = "qualifier"; private static final Set<String> SORTS = ImmutableSortedSet.of(NAME_SORT, PATH_SORT, QUALIFIER_SORT); private static final Set<String> PROJECT_OR_APP_QUALIFIERS = ImmutableSortedSet.of(Qualifiers.PROJECT, Qualifiers.APP); private final DbClient dbClient; private final ComponentFinder componentFinder; private final ResourceTypes resourceTypes; private final UserSession userSession; private final I18n i18n; public TreeAction(DbClient dbClient, ComponentFinder componentFinder, ResourceTypes resourceTypes, UserSession userSession, I18n i18n) { this.dbClient = dbClient; this.componentFinder = componentFinder; this.resourceTypes = resourceTypes; this.userSession = userSession; this.i18n = i18n; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_TREE) .setDescription(format("Navigate through components based on the chosen strategy.<br>" + "Requires the following permission: 'Browse' on the specified project.<br>" + "When limiting search with the %s parameter, directories are not returned.", Param.TEXT_QUERY)) .setSince("5.4") .setResponseExample(getClass().getResource("tree-example.json")) .setChangelog( new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("10.1", String.format("The use of 'BRC' as value for parameter '%s' is removed", PARAM_QUALIFIERS)), new Change("7.6", String.format("The use of 'BRC' as value for parameter '%s' is deprecated", PARAM_QUALIFIERS)), new Change("7.6", String.format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT))) .setHandler(this) .addPagingParams(100, MAX_SIZE); action.createParam(PARAM_COMPONENT) .setDescription("Base component key. The search is based on this component.") .setRequired(true) .setExampleValue(KEY_PROJECT_EXAMPLE_001); action.createParam(PARAM_BRANCH) .setDescription("Branch key. Not available in the community edition.") .setExampleValue(KEY_BRANCH_EXAMPLE_001) .setSince("6.6"); action.createParam(PARAM_PULL_REQUEST) .setDescription("Pull request id. Not available in the community edition.") .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001) .setSince("7.1"); action.createSortParams(SORTS, NAME_SORT, true) .setDescription("Comma-separated list of sort fields") .setExampleValue(NAME_SORT + ", " + PATH_SORT); action.createParam(Param.TEXT_QUERY) .setDescription("Limit search to: <ul>" + "<li>component names that contain the supplied string</li>" + "<li>component keys that are exactly the same as the supplied string</li>" + "</ul>") .setMinimumLength(QUERY_MINIMUM_LENGTH) .setExampleValue("FILE_NAM"); createQualifiersParameter(action, newQualifierParameterContext(i18n, resourceTypes)); action.createParam(PARAM_STRATEGY) .setDescription("Strategy to search for base component descendants:" + "<ul>" + "<li>children: return the children components of the base component. Grandchildren components are not returned</li>" + "<li>all: return all the descendants components of the base component. Grandchildren are returned.</li>" + "<li>leaves: return all the descendant components (files, in general) which don't have other children. They are the leaves of the component tree.</li>" + "</ul>") .setPossibleValues(STRATEGIES.keySet()) .setDefaultValue(ALL_STRATEGY); } @Override public void handle(org.sonar.api.server.ws.Request request, Response response) throws Exception { TreeWsResponse treeWsResponse = doHandle(toTreeWsRequest(request)); writeProtobuf(treeWsResponse, request, response); } private TreeWsResponse doHandle(Request treeRequest) { try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto baseComponent = loadComponent(dbSession, treeRequest); checkPermissions(baseComponent); ComponentTreeQuery query = toComponentTreeQuery(treeRequest, baseComponent); List<ComponentDto> components = dbClient.componentDao().selectDescendants(dbSession, query); components = filterAuthorizedComponents(components); int total = components.size(); components = sortComponents(components, treeRequest); components = paginateComponents(components, treeRequest); Map<String, ComponentDto> referenceComponentsByUuid = searchReferenceComponentsByUuid(dbSession, components); Paging paging = Paging.forPageIndex(treeRequest.getPage()).withPageSize(treeRequest.getPageSize()).andTotal(total); return buildResponse(dbSession, baseComponent, components, referenceComponentsByUuid, paging, treeRequest); } } private List<ComponentDto> filterAuthorizedComponents(List<ComponentDto> components) { return userSession.keepAuthorizedComponents(UserRole.USER, components); } private ComponentDto loadComponent(DbSession dbSession, Request request) { String componentKey = request.getComponent(); String branch = request.getBranch(); String pullRequest = request.getPullRequest(); return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, componentKey, branch, pullRequest); } private Map<String, ComponentDto> searchReferenceComponentsByUuid(DbSession dbSession, List<ComponentDto> components) { List<String> referenceComponentIds = components.stream() .map(ComponentDto::getCopyComponentUuid) .filter(Objects::nonNull) .toList(); if (referenceComponentIds.isEmpty()) { return emptyMap(); } return dbClient.componentDao().selectByUuids(dbSession, referenceComponentIds).stream() .collect(Collectors.toMap(ComponentDto::uuid, java.util.function.Function.identity())); } private void checkPermissions(ComponentDto baseComponent) { userSession.checkComponentPermission(UserRole.USER, baseComponent); } private TreeWsResponse buildResponse(DbSession dbSession, ComponentDto baseComponent, List<ComponentDto> components, Map<String, ComponentDto> referenceComponentsByUuid, Paging paging, Request request) { TreeWsResponse.Builder response = TreeWsResponse.newBuilder(); response.getPagingBuilder() .setPageIndex(paging.pageIndex()) .setPageSize(paging.pageSize()) .setTotal(paging.total()) .build(); Map<String, String> branchKeyByReferenceUuid = dbClient.branchDao().selectByUuids(dbSession, referenceComponentsByUuid.keySet()) .stream() .filter(b -> !b.isMain()) .collect(Collectors.toMap(BranchDto::getUuid, BranchDto::getBranchKey)); boolean isMainBranch = dbClient.branchDao().selectByUuid(dbSession, baseComponent.branchUuid()).map(BranchDto::isMain).orElse(true); response.setBaseComponent(toWsComponent(dbSession, baseComponent, isMainBranch, referenceComponentsByUuid, branchKeyByReferenceUuid, request)); for (ComponentDto dto : components) { response.addComponents(toWsComponent(dbSession, dto, isMainBranch, referenceComponentsByUuid, branchKeyByReferenceUuid, request)); } return response.build(); } private Components.Component.Builder toWsComponent(DbSession dbSession, ComponentDto component, boolean isMainBranch, Map<String, ComponentDto> referenceComponentsByUuid, Map<String, String> branchKeyByReferenceUuid, Request request) { ComponentDto referenceComponent = referenceComponentsByUuid.get(component.getCopyComponentUuid()); Components.Component.Builder wsComponent; if (isMainBranch && component.isRootProject() && PROJECT_OR_APP_QUALIFIERS.contains(component.qualifier())) { ProjectDto projectDto = componentFinder.getProjectOrApplicationByKey(dbSession, component.getKey()); wsComponent = projectOrAppToWsComponent(projectDto, null); } else { ProjectDto parentProject = dbClient.projectDao().selectByBranchUuid(dbSession, component.branchUuid()).orElse(null); if (referenceComponent != null) { wsComponent = componentDtoToWsComponent(component, parentProject, null, false, branchKeyByReferenceUuid.get(referenceComponent.uuid()), null); } else if (!isMainBranch) { wsComponent = componentDtoToWsComponent(component, parentProject, null, false, request.branch, request.pullRequest); } else { wsComponent = componentDtoToWsComponent(component, parentProject, null, true, null, null); } } if (referenceComponent != null) { wsComponent.setRefId(referenceComponent.uuid()); wsComponent.setRefKey(referenceComponent.getKey()); } return wsComponent; } private ComponentTreeQuery toComponentTreeQuery(Request request, ComponentDto baseComponent) { List<String> childrenQualifiers = childrenQualifiers(request, baseComponent.qualifier()); ComponentTreeQuery.Builder query = ComponentTreeQuery.builder() .setBaseUuid(baseComponent.uuid()) .setStrategy(STRATEGIES.get(request.getStrategy())); if (request.getQuery() != null) { query.setNameOrKeyQuery(request.getQuery()); } if (childrenQualifiers != null) { query.setQualifiers(childrenQualifiers); } return query.build(); } @CheckForNull private List<String> childrenQualifiers(Request request, String baseQualifier) { List<String> requestQualifiers = request.getQualifiers(); List<String> childrenQualifiers = null; if (LEAVES_STRATEGY.equals(request.getStrategy())) { childrenQualifiers = resourceTypes.getLeavesQualifiers(baseQualifier); } if (requestQualifiers == null) { return childrenQualifiers; } if (childrenQualifiers == null) { return requestQualifiers; } Sets.SetView<String> qualifiersIntersection = Sets.intersection(new HashSet<>(childrenQualifiers), new HashSet<>(requestQualifiers)); return new ArrayList<>(qualifiersIntersection); } private static Request toTreeWsRequest(org.sonar.api.server.ws.Request request) { return new Request() .setComponent(request.mandatoryParam(PARAM_COMPONENT)) .setBranch(request.param(PARAM_BRANCH)) .setPullRequest(request.param(PARAM_PULL_REQUEST)) .setStrategy(request.mandatoryParam(PARAM_STRATEGY)) .setQuery(request.param(Param.TEXT_QUERY)) .setQualifiers(request.paramAsStrings(PARAM_QUALIFIERS)) .setSort(request.mandatoryParamAsStrings(Param.SORT)) .setAsc(request.mandatoryParamAsBoolean(Param.ASCENDING)) .setPage(request.mandatoryParamAsInt(Param.PAGE)) .setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE)); } private static List<ComponentDto> paginateComponents(List<ComponentDto> components, Request wsRequest) { return components.stream().skip(offset(wsRequest.getPage(), wsRequest.getPageSize())) .limit(wsRequest.getPageSize()).toList(); } private static List<ComponentDto> sortComponents(List<ComponentDto> components, Request wsRequest) { List<String> sortParameters = wsRequest.getSort(); if (sortParameters == null || sortParameters.isEmpty()) { return components; } boolean isAscending = wsRequest.getAsc(); Map<String, Ordering<ComponentDto>> orderingsBySortField = ImmutableMap.<String, Ordering<ComponentDto>>builder() .put(NAME_SORT, stringOrdering(isAscending, ComponentDto::name)) .put(QUALIFIER_SORT, stringOrdering(isAscending, ComponentDto::qualifier)) .put(PATH_SORT, stringOrdering(isAscending, ComponentDto::path)) .build(); String firstSortParameter = sortParameters.get(0); Ordering<ComponentDto> primaryOrdering = orderingsBySortField.get(firstSortParameter); if (sortParameters.size() > 1) { for (int i = 1; i < sortParameters.size(); i++) { String secondarySortParameter = sortParameters.get(i); Ordering<ComponentDto> secondaryOrdering = orderingsBySortField.get(secondarySortParameter); primaryOrdering = primaryOrdering.compound(secondaryOrdering); } } return primaryOrdering.immutableSortedCopy(components); } private static Ordering<ComponentDto> stringOrdering(boolean isAscending, Function<ComponentDto, String> function) { Ordering<String> ordering = Ordering.from(CASE_INSENSITIVE_ORDER); if (!isAscending) { ordering = ordering.reverse(); } return ordering.nullsLast().onResultOf(function); } private static class Request { private String component; private String branch; private String pullRequest; private String strategy; private List<String> qualifiers; private String query; private List<String> sort; private Boolean asc; private Integer page; private Integer pageSize; public Request setComponent(String component) { this.component = component; return this; } @CheckForNull private String getComponent() { return component; } @CheckForNull private String getBranch() { return branch; } private Request setBranch(@Nullable String branch) { this.branch = branch; return this; } @CheckForNull public String getPullRequest() { return pullRequest; } public Request setPullRequest(@Nullable String pullRequest) { this.pullRequest = pullRequest; return this; } @CheckForNull private String getStrategy() { return strategy; } private Request setStrategy(@Nullable String strategy) { this.strategy = strategy; return this; } @CheckForNull private List<String> getQualifiers() { return qualifiers; } private Request setQualifiers(@Nullable List<String> qualifiers) { this.qualifiers = qualifiers; return this; } @CheckForNull private String getQuery() { return query; } private Request setQuery(@Nullable String query) { this.query = query; return this; } @CheckForNull private List<String> getSort() { return sort; } private Request setSort(@Nullable List<String> sort) { this.sort = sort; return this; } private Boolean getAsc() { return asc; } private Request setAsc(@Nullable Boolean asc) { this.asc = asc; return this; } @CheckForNull private Integer getPage() { return page; } private Request setPage(@Nullable Integer page) { this.page = page; return this; } @CheckForNull private Integer getPageSize() { return pageSize; } private Request setPageSize(@Nullable Integer pageSize) { this.pageSize = pageSize; return this; } } }
19,172
39.534884
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/component/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.component.ws; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/DevelopersWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.developers.ws; import java.util.Arrays; import java.util.List; import org.sonar.api.server.ws.WebService; public class DevelopersWs implements WebService { private final List<DevelopersWsAction> actions; public DevelopersWs(DevelopersWsAction... actions) { this.actions = Arrays.asList(actions); } @Override public void define(Context context) { NewController controller = context.createController("api/developers") .setDescription("Return data needed by SonarLint.") .setSince("1.0"); actions.forEach(action -> action.define(controller)); controller.done(); } }
1,478
31.866667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/DevelopersWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.developers.ws; import org.sonar.server.ws.WsAction; interface DevelopersWsAction extends WsAction { // marker interface }
994
35.851852
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/DevelopersWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.developers.ws; import org.sonar.core.platform.Module; public class DevelopersWsModule extends Module { @Override protected void configureModule() { add( DevelopersWs.class, SearchEventsAction.class ); } }
1,101
32.393939
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/SearchEventsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.developers.ws; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.sonar.api.platform.Server; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.event.EventDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.issue.index.IssueIndex; import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.issue.index.ProjectStatistics; import org.sonar.server.projectanalysis.ws.EventCategory; import org.sonar.server.user.UserSession; import org.sonar.server.ws.KeyExamples; import org.sonarqube.ws.Developers.SearchEventsWsResponse; import org.sonarqube.ws.Developers.SearchEventsWsResponse.Event; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static java.lang.String.join; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Comparator.comparing; import static org.sonar.api.utils.DateUtils.formatDateTime; import static org.sonar.api.utils.DateUtils.parseDateTimeQuietly; import static org.sonar.db.component.BranchType.BRANCH; import static org.sonar.db.component.BranchType.PULL_REQUEST; import static org.sonar.server.developers.ws.UuidFromPairs.fromDates; import static org.sonar.server.developers.ws.UuidFromPairs.projectUuids; import static org.sonar.server.exceptions.BadRequestException.checkRequest; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class SearchEventsAction implements DevelopersWsAction { public static final String PARAM_PROJECTS = "projects"; public static final String PARAM_FROM = "from"; private final DbClient dbClient; private final UserSession userSession; private final Server server; private final IssueIndex issueIndex; private final IssueIndexSyncProgressChecker issueIndexSyncProgressChecker; public SearchEventsAction(DbClient dbClient, UserSession userSession, Server server, IssueIndex issueIndex, IssueIndexSyncProgressChecker issueIndexSyncProgressChecker) { this.dbClient = dbClient; this.userSession = userSession; this.server = server; this.issueIndex = issueIndex; this.issueIndexSyncProgressChecker = issueIndexSyncProgressChecker; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("search_events") .setDescription("Search for events.<br/>" + "Requires authentication." + "<br/>When issue indexation is in progress returns 503 service unavailable HTTP code.") .setSince("1.0") .setInternal(true) .setHandler(this) .setResponseExample(SearchEventsAction.class.getResource("search_events-example.json")); action.createParam(PARAM_PROJECTS) .setRequired(true) .setDescription("Comma-separated list of project keys to search notifications for") .setExampleValue(join(",", KeyExamples.KEY_PROJECT_EXAMPLE_001, KeyExamples.KEY_PROJECT_EXAMPLE_002)); action.createParam(PARAM_FROM) .setRequired(true) .setDescription("Comma-separated list of datetimes. Filter events created after the given date (exclusive).") .setExampleValue("2017-10-19T13:00:00+0200"); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkLoggedIn(); checkIfNeedIssueSync(request.mandatoryParamAsStrings(PARAM_PROJECTS)); SearchEventsWsResponse.Builder message = SearchEventsWsResponse.newBuilder(); computeEvents(request).forEach(message::addEvents); writeProtobuf(message.build(), request, response); } private void checkIfNeedIssueSync(List<String> projectKeys) { try (DbSession dbSession = dbClient.openSession(false)) { issueIndexSyncProgressChecker.checkIfAnyComponentsNeedIssueSync(dbSession, projectKeys); } } private Stream<Event> computeEvents(Request request) { List<String> projectKeys = request.mandatoryParamAsStrings(PARAM_PROJECTS); List<Long> fromDates = mandatoryParamAsDateTimes(request, PARAM_FROM); if (projectKeys.isEmpty()) { return Stream.empty(); } try (DbSession dbSession = dbClient.openSession(false)) { List<ProjectDto> authorizedProjects = searchProjects(dbSession, projectKeys); Map<String, ProjectDto> projectsByUuid = authorizedProjects.stream().collect(Collectors.toMap(ProjectDto::getUuid, Function.identity())); List<UuidFromPair> uuidFromPairs = buildUuidFromPairs(fromDates, projectKeys, authorizedProjects); List<SnapshotDto> analyses = dbClient.snapshotDao().selectFinishedByProjectUuidsAndFromDates(dbSession, projectUuids(uuidFromPairs), fromDates(uuidFromPairs)); if (analyses.isEmpty()) { return Stream.empty(); } List<String> branchUuids = analyses.stream().map(SnapshotDto::getRootComponentUuid).toList(); Map<String, BranchDto> branchesByUuids = dbClient.branchDao().selectByUuids(dbSession, branchUuids) .stream().collect(Collectors.toMap(BranchDto::getUuid, Function.identity())); return Stream.concat( computeQualityGateChangeEvents(dbSession, projectsByUuid, branchesByUuids, analyses), computeNewIssuesEvents(projectsByUuid, branchesByUuids, uuidFromPairs)); } } private Stream<Event> computeQualityGateChangeEvents(DbSession dbSession, Map<String, ProjectDto> projectsByUuid, Map<String, BranchDto> branchesByUuids, List<SnapshotDto> analyses) { Map<String, EventDto> eventsByComponentUuid = new HashMap<>(); dbClient.eventDao().selectByAnalysisUuids(dbSession, analyses.stream().map(SnapshotDto::getUuid).toList()) .stream() .sorted(comparing(EventDto::getDate)) .filter(e -> EventCategory.QUALITY_GATE.getLabel().equals(e.getCategory())) .forEach(e -> eventsByComponentUuid.put(e.getComponentUuid(), e)); Predicate<EventDto> branchPredicate = e -> branchesByUuids.get(e.getComponentUuid()).getBranchType() == BRANCH; return eventsByComponentUuid.values() .stream() .sorted(comparing(EventDto::getDate)) .filter(branchPredicate) .map(e -> { BranchDto branch = branchesByUuids.get(e.getComponentUuid()); ProjectDto project = projectsByUuid.get(branch.getProjectUuid()); checkState(project != null, "Found event '%s', for a component that we did not search for", e.getUuid()); return Event.newBuilder() .setCategory(EventCategory.fromLabel(e.getCategory()).name()) .setProject(project.getKey()) .setMessage(branch.isMain() ? format("Quality Gate status of project '%s' changed to '%s'", project.getName(), e.getName()) : format("Quality Gate status of project '%s' on branch '%s' changed to '%s'", project.getName(), branch.getKey(), e.getName())) .setLink(computeDashboardLink(project, branch)) .setDate(formatDateTime(e.getDate())) .build(); }); } private Stream<Event> computeNewIssuesEvents(Map<String, ProjectDto> projectsByUuid, Map<String, BranchDto> branchesByUuids, List<UuidFromPair> uuidFromPairs) { Map<String, Long> fromsByProjectUuid = uuidFromPairs.stream().collect(Collectors.toMap( UuidFromPair::getProjectUuid, UuidFromPair::getFrom)); List<ProjectStatistics> projectStatistics = issueIndex.searchProjectStatistics(projectUuids(uuidFromPairs), fromDates(uuidFromPairs), userSession.getUuid()); return projectStatistics .stream() .map(e -> { BranchDto branch = branchesByUuids.get(e.getProjectUuid()); ProjectDto project = projectsByUuid.get(branch.getProjectUuid()); long issueCount = e.getIssueCount(); long lastIssueDate = e.getLastIssueDate(); String branchType = branch.getBranchType().equals(PULL_REQUEST) ? "pull request" : "branch"; return Event.newBuilder() .setCategory("NEW_ISSUES") .setMessage(format("You have %s new %s on project '%s'", issueCount, issueCount == 1 ? "issue" : "issues", project.getName()) + (branch.isMain() ? "" : format(" on %s '%s'", branchType, branch.getKey()))) .setLink(computeIssuesSearchLink(project, branch, fromsByProjectUuid.get(project.getUuid()), userSession.getLogin())) .setProject(project.getKey()) .setDate(formatDateTime(lastIssueDate)) .build(); }); } private List<ProjectDto> searchProjects(DbSession dbSession, List<String> projectKeys) { List<ProjectDto> projects = dbClient.projectDao().selectProjectsByKeys(dbSession, new HashSet<>(projectKeys)); return userSession.keepAuthorizedEntities(UserRole.USER, projects); } private String computeIssuesSearchLink(ProjectDto project, BranchDto branch, long functionalFromDate, String login) { String branchParam = branch.getBranchType().equals(PULL_REQUEST) ? "pullRequest" : "branch"; String link = format("%s/project/issues?id=%s&createdAfter=%s&assignees=%s&resolved=false", server.getPublicRootUrl(), encode(project.getKey()), encode(formatDateTime(functionalFromDate)), encode(login)); link += branch.isMain() ? "" : format("&%s=%s", branchParam, encode(branch.getKey())); return link; } private String computeDashboardLink(ProjectDto project, BranchDto branch) { String link = server.getPublicRootUrl() + "/dashboard?id=" + encode(project.getKey()); link += branch.isMain() ? "" : format("&branch=%s", encode(branch.getKey())); return link; } private static List<UuidFromPair> buildUuidFromPairs(List<Long> fromDates, List<String> projectKeys, List<ProjectDto> authorizedProjects) { checkRequest(projectKeys.size() == fromDates.size(), "The number of components (%s) and from dates (%s) must be the same.", projectKeys.size(), fromDates.size()); Map<String, Long> fromDatesByProjectKey = IntStream.range(0, projectKeys.size()).boxed() .collect(Collectors.toMap(projectKeys::get, fromDates::get)); return authorizedProjects.stream() .map(dto -> new UuidFromPair(dto.getUuid(), fromDatesByProjectKey.get(dto.getKey()))) .toList(); } private static List<Long> mandatoryParamAsDateTimes(Request request, String param) { return request.mandatoryParamAsStrings(param).stream() .map(stringDate -> { Date date = parseDateTimeQuietly(stringDate); checkArgument(date != null, "'%s' cannot be parsed as either a date or date+time", stringDate); return date.getTime() + 1_000L; }) .toList(); } private static String encode(String text) { try { return URLEncoder.encode(text, UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(format("Cannot encode %s", text), e); } } }
12,236
47.177165
172
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/UuidFromPair.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.developers.ws; class UuidFromPair { private final String projectUuid; private final long from; public UuidFromPair(String projectUuid, long from) { this.projectUuid = projectUuid; this.from = from; } public String getProjectUuid() { return projectUuid; } public long getFrom() { return from; } }
1,200
29.794872
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/UuidFromPairs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.developers.ws; import java.util.List; public class UuidFromPairs { private UuidFromPairs() { // prevent instantiation } public static List<String> projectUuids(List<UuidFromPair> pairs) { return pairs.stream().map(UuidFromPair::getProjectUuid).toList(); } public static List<Long> fromDates(List<UuidFromPair> pairs) { return pairs.stream().map(UuidFromPair::getFrom).toList(); } }
1,278
33.567568
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/developers/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.developers.ws; import javax.annotation.ParametersAreNonnullByDefault;
971
37.88
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/Duplication.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.duplication.ws; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.db.component.ComponentDto; public class Duplication { private final ComponentDto componentDto; private final String componentDbKey; private final Integer from; private final Integer size; private final boolean removed; private Duplication(@Nullable ComponentDto componentDto, String componentDbKey, Integer from, Integer size, boolean removed) { this.componentDto = componentDto; this.componentDbKey = componentDbKey; this.from = from; this.size = size; this.removed = removed; } static Duplication newRemovedComponent(String componentDbKey, Integer from, Integer size) { return new Duplication(null, componentDbKey, from, size, true); } static Duplication newTextComponent(String componentDbKey, Integer from, Integer size) { return new Duplication(null, componentDbKey, from, size, false); } static Duplication newComponent(ComponentDto componentDto, Integer from, Integer size) { return new Duplication(componentDto, componentDto.getKey(), from, size, false); } String componentDbKey() { return componentDbKey; } Integer from() { return from; } Integer size() { return size; } public boolean removed() { return removed; } /** * can be null if the file wasn't found in DB. This can happen if the target was removed (cross-project duplications) or * if the target refers to an unchanged file in PRs. */ @CheckForNull public ComponentDto componentDto() { return componentDto; } }
2,475
30.74359
128
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/DuplicationsParser.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.duplication.ws; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; import java.io.StringReader; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import org.apache.commons.lang.StringUtils; import org.codehaus.staxmate.SMInputFactory; import org.codehaus.staxmate.in.SMHierarchicCursor; import org.codehaus.staxmate.in.SMInputCursor; import org.sonar.api.server.ServerSide; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDto; import org.sonar.server.component.ComponentFinder; @ServerSide public class DuplicationsParser { private static final BlockComparator BLOCK_COMPARATOR = new BlockComparator(); private final ComponentFinder componentFinder; public DuplicationsParser(ComponentFinder componentFinder) { this.componentFinder = componentFinder; } public List<Block> parse(DbSession session, ComponentDto component, @Nullable String branch, @Nullable String pullRequest, @Nullable String duplicationsData) { Map<String, ComponentDto> componentsByKey = new LinkedHashMap<>(); List<Block> blocks = new ArrayList<>(); if (duplicationsData == null) { return blocks; } DuplicationComparator duplicationComparator = new DuplicationComparator(component.uuid(), component.branchUuid()); try { SMInputFactory inputFactory = initStax(); SMHierarchicCursor root = inputFactory.rootElementCursor(new StringReader(duplicationsData)); root.advance(); // <duplications> SMInputCursor cursor = root.childElementCursor("g"); while (cursor.getNext() != null) { List<Duplication> duplications = new ArrayList<>(); SMInputCursor bCursor = cursor.childElementCursor("b"); while (bCursor.getNext() != null) { String from = bCursor.getAttrValue("s"); String size = bCursor.getAttrValue("l"); boolean disableLink = Boolean.parseBoolean(bCursor.getAttrValue("t")); String componentDbKey = bCursor.getAttrValue("r"); if (from != null && size != null && componentDbKey != null) { if (disableLink) { // flag means that the target refers to an unchanged file in PRs that doesn't exist in DB. // Display as text without a link or other details. duplications.add(Duplication.newTextComponent(componentDbKey, Integer.valueOf(from), Integer.valueOf(size))); } else { duplications.add(createDuplication(componentsByKey, branch, pullRequest, from, size, componentDbKey, session)); } } } duplications.sort(duplicationComparator); blocks.add(new Block(duplications)); } blocks.sort(BLOCK_COMPARATOR); return blocks; } catch (XMLStreamException e) { throw new IllegalStateException("XML is not valid", e); } } private Duplication createDuplication(Map<String, ComponentDto> componentsByKey, @Nullable String branch, @Nullable String pullRequest, String from, String size, String componentDbKey, DbSession session) { String componentKey = convertToKey(componentDbKey); ComponentDto component; if (componentsByKey.containsKey(componentKey)) { component = componentsByKey.get(componentKey); } else { component = loadComponent(session, componentKey, branch, pullRequest); componentsByKey.put(componentKey, component); } if (component != null) { return Duplication.newComponent(component, Integer.valueOf(from), Integer.valueOf(size)); } else { //This can happen if the target was removed (cross-project duplications) return Duplication.newRemovedComponent(componentKey, Integer.valueOf(from), Integer.valueOf(size)); } } @CheckForNull private ComponentDto loadComponent(DbSession session, String componentKey, @Nullable String branch, @Nullable String pullRequest) { return componentFinder.getOptionalByKeyAndOptionalBranchOrPullRequest(session, componentKey, branch, pullRequest).orElse(null); } private static String convertToKey(String dbKey) { return new ComponentDto().setKey(dbKey).getKey(); } private static SMInputFactory initStax() { XMLInputFactory xmlFactory = XMLInputFactory.newInstance(); xmlFactory.setProperty(XMLInputFactory.IS_COALESCING, Boolean.TRUE); xmlFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.FALSE); // just so it won't try to load DTD in if there's DOCTYPE xmlFactory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE); xmlFactory.setProperty(XMLInputFactory.IS_VALIDATING, Boolean.FALSE); return new SMInputFactory(xmlFactory); } /** * Sorts the duplications with the following criteria: * - Duplications in the same file by starting line * - Duplications in the same project * - Cross project duplications */ @VisibleForTesting static class DuplicationComparator implements Comparator<Duplication>, Serializable { private static final long serialVersionUID = 1; private final String fileUuid; private final String projectUuid; DuplicationComparator(String fileUuid, String projectUuid) { this.fileUuid = fileUuid; this.projectUuid = projectUuid; } @Override public int compare(@Nullable Duplication d1, @Nullable Duplication d2) { if (d1 == null || d2 == null) { return -1; } ComponentDto file1 = d1.componentDto(); ComponentDto file2 = d2.componentDto(); if (file1 != null && file1.equals(file2)) { // if duplication on same file => order by starting line return d1.from().compareTo(d2.from()); } if (sameFile(file1) && !sameFile(file2)) { // the current resource must be displayed first return -1; } if (sameFile(file2) && !sameFile(file1)) { // the current resource must be displayed first return 1; } if (sameProject(file1) && !sameProject(file2)) { // if resource is in the same project, this it must be displayed first return -1; } if (sameProject(file2) && !sameProject(file1)) { // if resource is in the same project, this it must be displayed first return 1; } return d1.from().compareTo(d2.from()); } private boolean sameFile(@Nullable ComponentDto otherDto) { return otherDto != null && StringUtils.equals(otherDto.uuid(), fileUuid); } private boolean sameProject(@Nullable ComponentDto otherDto) { return otherDto == null || StringUtils.equals(otherDto.branchUuid(), projectUuid); } } private static class BlockComparator implements Comparator<Block>, Serializable { private static final long serialVersionUID = 1; @Override public int compare(@Nullable Block b1, @Nullable Block b2) { if (b1 == null || b2 == null) { return -1; } List<Duplication> duplications1 = b1.getDuplications(); List<Duplication> duplications2 = b2.getDuplications(); if (duplications1.isEmpty() || duplications2.isEmpty()) { return -1; } return duplications1.get(0).from().compareTo(duplications2.get(0).from()); } } static class Block { private final List<Duplication> duplications; public Block(List<Duplication> duplications) { this.duplications = duplications; } public List<Duplication> getDuplications() { return duplications; } } }
8,557
37.54955
161
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/DuplicationsWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.duplication.ws; import org.sonar.api.server.ws.WebService; public class DuplicationsWs implements WebService { private final ShowAction showAction; public DuplicationsWs(ShowAction showAction) { this.showAction = showAction; } @Override public void define(Context context) { NewController controller = context.createController("api/duplications") .setSince("4.4") .setDescription("Get duplication information for a project."); showAction.define(controller); controller.done(); } }
1,394
33.02439
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/DuplicationsWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.duplication.ws; import org.sonar.server.ws.WsAction; public interface DuplicationsWsAction extends WsAction { // marker interface }
1,004
36.222222
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/ShowAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.duplication.ws; import java.util.List; import java.util.Optional; import javax.annotation.CheckForNull; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.UserRole; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.server.component.ComponentFinder; import org.sonar.server.user.UserSession; import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001; import static org.sonar.server.ws.KeyExamples.KEY_PULL_REQUEST_EXAMPLE_001; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class ShowAction implements DuplicationsWsAction { private static final String PARAM_KEY = "key"; private static final String PARAM_BRANCH = "branch"; private static final String PARAM_PULL_REQUEST = "pullRequest"; private final DbClient dbClient; private final DuplicationsParser parser; private final ShowResponseBuilder responseBuilder; private final UserSession userSession; private final ComponentFinder componentFinder; public ShowAction(DbClient dbClient, DuplicationsParser parser, ShowResponseBuilder responseBuilder, UserSession userSession, ComponentFinder componentFinder) { this.dbClient = dbClient; this.parser = parser; this.responseBuilder = responseBuilder; this.userSession = userSession; this.componentFinder = componentFinder; } @Override public void define(WebService.NewController controller) { WebService.NewAction action = controller.createAction("show") .setDescription("Get duplications. Require Browse permission on file's project") .setSince("4.4") .setHandler(this) .setResponseExample(getClass().getResource("show-example.json")); action.setChangelog( new Change("9.6", "The fields 'subProject', 'subProjectName' were removed from the response."), new Change("8.8", "Deprecated parameter 'uuid' was removed."), new Change("8.8", "The fields 'uuid', 'projectUuid', 'subProjectUuid' were removed from the response."), new Change("6.5", "Parameter 'uuid' is now deprecated."), new Change("6.5", "The fields 'uuid', 'projectUuid', 'subProjectUuid' are now deprecated in the response.")); action .createParam(PARAM_KEY) .setDescription("File key") .setRequired(true) .setExampleValue("my_project:/src/foo/Bar.php"); action .createParam(PARAM_BRANCH) .setDescription("Branch key") .setInternal(true) .setExampleValue(KEY_BRANCH_EXAMPLE_001); action .createParam(PARAM_PULL_REQUEST) .setDescription("Pull request id") .setInternal(true) .setSince("7.1") .setExampleValue(KEY_PULL_REQUEST_EXAMPLE_001); } @Override public void handle(Request request, Response response) { try (DbSession dbSession = dbClient.openSession(false)) { ComponentDto component = loadComponent(dbSession, request); BranchDto branchDto = loadBranch(dbSession, component); String branch = branchDto.isMain() ? null : branchDto.getBranchKey(); String pullRequest = branchDto.getPullRequestKey(); userSession.checkComponentPermission(UserRole.CODEVIEWER, component); String duplications = findDataFromComponent(dbSession, component); List<DuplicationsParser.Block> blocks = parser.parse(dbSession, component, branch, pullRequest, duplications); writeProtobuf(responseBuilder.build(dbSession, blocks, branch, pullRequest), request, response); } } private BranchDto loadBranch(DbSession dbSession, ComponentDto component) { Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, component.branchUuid()); if (branchDto.isEmpty()) { throw new IllegalStateException("Could not find a branch for component with " + component.uuid()); } return branchDto.get(); } private ComponentDto loadComponent(DbSession dbSession, Request request) { String key = request.mandatoryParam(PARAM_KEY); String branch = request.param(PARAM_BRANCH); String pullRequest = request.param(PARAM_PULL_REQUEST); if (branch == null && pullRequest == null) { return componentFinder.getByKey(dbSession, key); } return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, key, branch, pullRequest); } @CheckForNull private String findDataFromComponent(DbSession dbSession, ComponentDto component) { return dbClient.liveMeasureDao().selectMeasure(dbSession, component.uuid(), CoreMetrics.DUPLICATIONS_DATA_KEY) .map(LiveMeasureDto::getDataAsString) .orElse(null); } }
5,721
41.073529
162
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/ShowResponseBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.duplication.ws; import com.google.common.annotations.VisibleForTesting; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.inject.Inject; import org.apache.commons.lang.StringUtils; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDao; import org.sonar.db.component.ComponentDto; import org.sonarqube.ws.Duplications; import org.sonarqube.ws.Duplications.Block; import org.sonarqube.ws.Duplications.ShowResponse; import static java.util.Optional.ofNullable; public class ShowResponseBuilder { private final ComponentDao componentDao; @Inject public ShowResponseBuilder(DbClient dbClient) { this.componentDao = dbClient.componentDao(); } @VisibleForTesting ShowResponseBuilder(ComponentDao componentDao) { this.componentDao = componentDao; } ShowResponse build(DbSession session, List<DuplicationsParser.Block> blocks, @Nullable String branch, @Nullable String pullRequest) { Map<String, Reference> refByComponentKey = new LinkedHashMap<>(); ShowResponse.Builder response = ShowResponse.newBuilder(); blocks.stream() .map(block -> toWsDuplication(block, refByComponentKey)) .forEach(response::addDuplications); writeFileRefs(session, refByComponentKey, response, branch, pullRequest); return response.build(); } private static Duplications.Duplication.Builder toWsDuplication(DuplicationsParser.Block block, Map<String, Reference> refByComponentKey) { Duplications.Duplication.Builder wsDuplication = Duplications.Duplication.newBuilder(); block.getDuplications().stream() .map(duplication -> toWsBlock(duplication, refByComponentKey)) .forEach(wsDuplication::addBlocks); return wsDuplication; } private static Block.Builder toWsBlock(Duplication duplication, Map<String, Reference> refByComponentKey) { Block.Builder block = Block.newBuilder(); if (!duplication.removed()) { Reference ref = refByComponentKey.computeIfAbsent(duplication.componentDbKey(), k -> new Reference( Integer.toString(refByComponentKey.size() + 1), duplication.componentDto(), duplication.componentDbKey())); block.setRef(ref.getId()); } block.setFrom(duplication.from()); block.setSize(duplication.size()); return block; } private void writeFileRefs(DbSession session, Map<String, Reference> refByComponentKey, ShowResponse.Builder response, @Nullable String branch, @Nullable String pullRequest) { Map<String, ComponentDto> projectsByUuid = new HashMap<>(); for (Map.Entry<String, Reference> entry : refByComponentKey.entrySet()) { Reference ref = entry.getValue(); ComponentDto file = ref.getDto(); if (file != null) { ComponentDto project = getProject(file.branchUuid(), projectsByUuid, session); response.putFiles(ref.getId(), toWsFile(file, project, branch, pullRequest)); } else { response.putFiles(ref.getId(), toWsFile(ref.getComponentKey(), branch, pullRequest)); } } } private static Duplications.File toWsFile(String componentKey, @Nullable String branch, @Nullable String pullRequest) { Duplications.File.Builder wsFile = Duplications.File.newBuilder(); wsFile.setKey(componentKey); wsFile.setName(StringUtils.substringAfterLast(componentKey, ":")); ofNullable(branch).ifPresent(wsFile::setBranch); ofNullable(pullRequest).ifPresent(wsFile::setPullRequest); return wsFile.build(); } private static Duplications.File toWsFile(ComponentDto file, @Nullable ComponentDto project, @Nullable String branch, @Nullable String pullRequest) { Duplications.File.Builder wsFile = Duplications.File.newBuilder(); wsFile.setKey(file.getKey()); wsFile.setUuid(file.uuid()); wsFile.setName(file.longName()); ofNullable(project).ifPresent(p -> { wsFile.setProject(p.getKey()); wsFile.setProjectUuid(p.uuid()); wsFile.setProjectName(p.longName()); ofNullable(branch).ifPresent(wsFile::setBranch); ofNullable(pullRequest).ifPresent(wsFile::setPullRequest); }); return wsFile.build(); } private ComponentDto getProject(String projectUuid, Map<String, ComponentDto> projectsByUuid, DbSession session) { ComponentDto project = projectsByUuid.get(projectUuid); if (project == null) { Optional<ComponentDto> projectOptional = componentDao.selectByUuid(session, projectUuid); if (projectOptional.isPresent()) { project = projectOptional.get(); projectsByUuid.put(project.uuid(), project); } } return project; } private static class Reference { private final String id; private final ComponentDto dto; private final String componentKey; public Reference(String id, @Nullable ComponentDto dto, String componentKey) { this.id = id; this.dto = dto; this.componentKey = componentKey; } public String getId() { return id; } @CheckForNull public ComponentDto getDto() { return dto; } public String getComponentKey() { return componentKey; } } }
6,166
34.647399
177
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/duplication/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.duplication.ws; import javax.annotation.ParametersAreNonnullByDefault;
971
39.5
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/email/ws/EmailsWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.email.ws; import org.sonar.api.server.ws.WebService; public class EmailsWs implements WebService { private final EmailsWsAction[] actions; public EmailsWs(EmailsWsAction... actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController("api/emails") .setDescription("Manage emails") .setSince("6.1"); for (EmailsWsAction action : actions) { action.define(controller); } controller.done(); } }
1,390
31.348837
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/email/ws/EmailsWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.email.ws; import org.sonar.server.ws.WsAction; public interface EmailsWsAction extends WsAction { // marker interface }
992
35.777778
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/email/ws/EmailsWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.email.ws; import org.sonar.core.platform.Module; public class EmailsWsModule extends Module { @Override protected void configureModule() { add( EmailsWs.class, SendAction.class); } }
1,075
32.625
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/email/ws/SendAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.email.ws; import org.apache.commons.mail.EmailException; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.user.UserSession; public class SendAction implements EmailsWsAction { private static final String PARAM_TO = "to"; private static final String PARAM_SUBJECT = "subject"; private static final String PARAM_MESSAGE = "message"; private final UserSession userSession; private final EmailNotificationChannel emailNotificationChannel; public SendAction(UserSession userSession, EmailNotificationChannel emailNotificationChannel) { this.userSession = userSession; this.emailNotificationChannel = emailNotificationChannel; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("send") .setDescription("Test email configuration by sending an email<br>" + "Requires 'Administer System' permission.") .setSince("6.1") .setInternal(true) .setPost(true) .setHandler(this); action.createParam(PARAM_TO) .setDescription("Email address") .setExampleValue("john@doo.com") .setRequired(true); action.createParam(PARAM_SUBJECT) .setDescription("Subject of the email") .setExampleValue("Test Message from SonarQube"); action.createParam(PARAM_MESSAGE) .setDescription("Content of the email") .setRequired(true); } @Override public void handle(Request request, Response response) throws Exception { userSession.checkIsSystemAdministrator(); try { emailNotificationChannel.sendTestEmail(request.mandatoryParam(PARAM_TO), request.param(PARAM_SUBJECT), request.mandatoryParam(PARAM_MESSAGE)); } catch (EmailException emailException) { throw BadRequestException.create("Configuration invalid: please double check SMTP host, port, login and password."); } response.noContent(); } }
2,990
36.860759
148
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/email/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.email.ws; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/FavoriteFinder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite; import java.util.Comparator; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.entity.EntityDto; import org.sonar.db.property.PropertyDto; import org.sonar.db.property.PropertyQuery; import org.sonar.server.user.UserSession; import static java.util.Collections.emptyList; import static org.sonar.server.favorite.FavoriteUpdater.PROP_FAVORITE_KEY; public class FavoriteFinder { private final DbClient dbClient; private final UserSession userSession; public FavoriteFinder(DbClient dbClient, UserSession userSession) { this.dbClient = dbClient; this.userSession = userSession; } /** * @return the list of favorite components of the authenticated user. Empty list if the user is not authenticated */ public List<EntityDto> list() { if (!userSession.isLoggedIn()) { return emptyList(); } try (DbSession dbSession = dbClient.openSession(false)) { PropertyQuery dbQuery = PropertyQuery.builder() .setKey(PROP_FAVORITE_KEY) .setUserUuid(userSession.getUuid()) .build(); Set<String> entitiesUuids = dbClient.propertiesDao().selectByQuery(dbQuery, dbSession).stream().map(PropertyDto::getEntityUuid).collect(Collectors.toSet()); List<EntityDto> entities = dbClient.entityDao().selectByUuids(dbSession, entitiesUuids); return entities.stream() .sorted(Comparator.comparing(EntityDto::getName)) .toList(); } } }
2,413
34.5
162
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/FavoriteModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite; import org.sonar.core.platform.Module; public class FavoriteModule extends Module { @Override protected void configureModule() { add( FavoriteFinder.class, FavoriteUpdater.class ); } }
1,093
30.257143
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite; import javax.annotation.ParametersAreNonnullByDefault;
966
37.68
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/ws/AddAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite.ws; import java.util.List; import java.util.function.Consumer; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.entity.EntityDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.favorite.FavoriteUpdater; import org.sonar.server.user.UserSession; import org.sonar.server.ws.KeyExamples; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.lang.String.join; import static java.util.Arrays.asList; import static org.sonar.api.resources.Qualifiers.APP; import static org.sonar.api.resources.Qualifiers.PROJECT; import static org.sonar.api.resources.Qualifiers.SUBVIEW; import static org.sonar.api.resources.Qualifiers.VIEW; import static org.sonar.api.web.UserRole.USER; import static org.sonar.server.favorite.ws.FavoritesWsParameters.PARAM_COMPONENT; public class AddAction implements FavoritesWsAction { private static final List<String> SUPPORTED_QUALIFIERS = asList(PROJECT, VIEW, SUBVIEW, APP); private static final String SUPPORTED_QUALIFIERS_AS_STRING = join(", ", SUPPORTED_QUALIFIERS); private final UserSession userSession; private final DbClient dbClient; private final FavoriteUpdater favoriteUpdater; public AddAction(UserSession userSession, DbClient dbClient, FavoriteUpdater favoriteUpdater) { this.userSession = userSession; this.dbClient = dbClient; this.favoriteUpdater = favoriteUpdater; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("add") .setDescription("Add a component (project, portfolio, etc.) as favorite for the authenticated user.<br>" + "Only 100 components by qualifier can be added as favorite.<br>" + "Requires authentication and the following permission: 'Browse' on the component.") .setSince("6.3") .setChangelog( new Change("10.1", String.format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("8.4", "It's no longer possible to set a file as favorite"), new Change("7.7", "It's no longer possible to have more than 100 favorites by qualifier"), new Change("7.7", "It's no longer possible to set a directory as favorite"), new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT))) .setPost(true) .setHandler(this); action.createParam(PARAM_COMPONENT) .setDescription(format("Component key. Only components with qualifiers %s are supported", SUPPORTED_QUALIFIERS_AS_STRING)) .setRequired(true) .setExampleValue(KeyExamples.KEY_FILE_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { addFavorite().accept(request); response.noContent(); } private Consumer<Request> addFavorite() { return request -> { try (DbSession dbSession = dbClient.openSession(false)) { EntityDto entity = dbClient.entityDao().selectByKey(dbSession, request.mandatoryParam(PARAM_COMPONENT)) .orElseThrow(() -> new NotFoundException(format("Entity with key '%s' not found", request.mandatoryParam(PARAM_COMPONENT)))); checkArgument(SUPPORTED_QUALIFIERS.contains(entity.getQualifier()), "Only components with qualifiers %s are supported", SUPPORTED_QUALIFIERS_AS_STRING); userSession .checkLoggedIn() .checkEntityPermission(USER, entity); String userUuid = userSession.isLoggedIn() ? userSession.getUuid() : null; String userLogin = userSession.isLoggedIn() ? userSession.getLogin() : null; favoriteUpdater.add(dbSession, entity, userUuid, userLogin, true); dbSession.commit(); } }; } }
4,845
43.87037
160
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/ws/FavoriteWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite.ws; import org.sonar.core.platform.Module; public class FavoriteWsModule extends Module { @Override protected void configureModule() { add( FavoritesWs.class, AddAction.class, RemoveAction.class, SearchAction.class ); } }
1,140
30.694444
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/ws/FavoritesWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite.ws; import org.sonar.api.server.ws.WebService; public class FavoritesWs implements WebService { private final FavoritesWsAction[] actions; public FavoritesWs(FavoritesWsAction[] actions) { this.actions = actions; } @Override public void define(Context context) { NewController controller = context.createController("api/favorites") .setDescription("Manage user favorites") .setSince("6.3"); for (FavoritesWsAction action : actions) { action.define(controller); } controller.done(); } }
1,419
31.272727
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/ws/FavoritesWsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite.ws; import org.sonar.server.ws.WsAction; public interface FavoritesWsAction extends WsAction { // marker interface }
998
36
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/ws/FavoritesWsParameters.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite.ws; public class FavoritesWsParameters { public static final String CONTROLLER_FAVORITES = "api/favorites"; public static final String ACTION_ADD = "add"; public static final String ACTION_REMOVE = "remove"; public static final String ACTION_SEARCH = "search"; public static final String PARAM_COMPONENT = "component"; private FavoritesWsParameters() { // prevent instantiation } }
1,281
35.628571
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/ws/RemoveAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite.ws; import java.util.function.Consumer; import org.sonar.api.server.ws.Change; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.entity.EntityDto; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.favorite.FavoriteUpdater; import org.sonar.server.user.UserSession; import org.sonar.server.ws.KeyExamples; import static java.lang.String.format; import static org.sonar.server.favorite.ws.FavoritesWsParameters.PARAM_COMPONENT; public class RemoveAction implements FavoritesWsAction { private final UserSession userSession; private final DbClient dbClient; private final FavoriteUpdater favoriteUpdater; public RemoveAction(UserSession userSession, DbClient dbClient, FavoriteUpdater favoriteUpdater) { this.userSession = userSession; this.dbClient = dbClient; this.favoriteUpdater = favoriteUpdater; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction("remove") .setDescription("Remove a component (project, portfolio, application etc.) as favorite for the authenticated user.<br>" + "Requires authentication.") .setSince("6.3") .setChangelog( new Change("10.1", format("The use of module keys in parameter '%s' is removed", PARAM_COMPONENT)), new Change("7.6", format("The use of module keys in parameter '%s' is deprecated", PARAM_COMPONENT))) .setPost(true) .setHandler(this); action.createParam(PARAM_COMPONENT) .setDescription("Component key") .setRequired(true) .setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001); } @Override public void handle(Request request, Response response) throws Exception { removeFavorite().accept(request); response.noContent(); } private Consumer<Request> removeFavorite() { return request -> { try (DbSession dbSession = dbClient.openSession(false)) { String key = request.mandatoryParam(PARAM_COMPONENT); EntityDto entity = dbClient.entityDao().selectByKey(dbSession, key) .orElseThrow(() -> new NotFoundException(format("Component with key '%s' not found", key))); userSession.checkLoggedIn(); favoriteUpdater.remove(dbSession, entity, userSession.isLoggedIn() ? userSession.getUuid() : null, userSession.isLoggedIn() ? userSession.getLogin() : null); dbSession.commit(); } }; } }
3,470
38.443182
127
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/ws/SearchAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite.ws; import java.util.List; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.server.ws.WebService.Param; import org.sonar.api.utils.Paging; import org.sonar.api.web.UserRole; import org.sonar.db.entity.EntityDto; import org.sonar.server.favorite.FavoriteFinder; import org.sonar.server.user.UserSession; import org.sonarqube.ws.Common; import org.sonarqube.ws.Favorites.Favorite; import org.sonarqube.ws.Favorites.SearchResponse; import static java.util.Optional.ofNullable; import static org.sonar.server.favorite.ws.FavoritesWsParameters.ACTION_SEARCH; import static org.sonar.server.ws.WsUtils.writeProtobuf; public class SearchAction implements FavoritesWsAction { private static final int MAX_PAGE_SIZE = 500; private final FavoriteFinder favoriteFinder; private final UserSession userSession; public SearchAction(FavoriteFinder favoriteFinder, UserSession userSession) { this.favoriteFinder = favoriteFinder; this.userSession = userSession; } @Override public void define(WebService.NewController context) { WebService.NewAction action = context.createAction(ACTION_SEARCH) .setDescription("Search for the authenticated user favorites.<br>" + "Requires authentication.") .setSince("6.3") .setResponseExample(getClass().getResource("search-example.json")) .setHandler(this); action.addPagingParams(100, MAX_PAGE_SIZE); } @Override public void handle(Request request, Response response) throws Exception { SearchRequest searchRequest = toWsRequest(request); SearchResults searchResults = toSearchResults(searchRequest); SearchResponse wsResponse = toSearchResponse(searchResults); writeProtobuf(wsResponse, request, response); } private static SearchRequest toWsRequest(Request request) { return new SearchRequest() .setP(request.mandatoryParam(Param.PAGE)) .setPs(request.mandatoryParam(Param.PAGE_SIZE)); } private SearchResults toSearchResults(SearchRequest request) { userSession.checkLoggedIn(); List<EntityDto> authorizedFavorites = getAuthorizedFavorites(); Paging paging = Paging.forPageIndex(Integer.parseInt(request.getP())).withPageSize(Integer.parseInt(request.getPs())).andTotal(authorizedFavorites.size()); List<EntityDto> displayedFavorites = authorizedFavorites.stream() .skip(paging.offset()) .limit(paging.pageSize()) .toList(); return new SearchResults(paging, displayedFavorites); } private List<EntityDto> getAuthorizedFavorites() { List<EntityDto> entities = favoriteFinder.list(); return userSession.keepAuthorizedEntities(UserRole.USER, entities); } private static class SearchResults { private final List<EntityDto> favorites; private final Paging paging; private SearchResults(Paging paging, List<EntityDto> favorites) { this.paging = paging; this.favorites = favorites; } } private static SearchResponse toSearchResponse(SearchResults searchResults) { SearchResponse.Builder builder = SearchResponse.newBuilder(); addPaging(builder, searchResults); addFavorites(builder, searchResults); return builder.build(); } private static void addPaging(SearchResponse.Builder builder, SearchResults results) { builder .setPaging(Common.Paging.newBuilder() .setPageIndex(results.paging.pageIndex()) .setPageSize(results.paging.pageSize()) .setTotal(results.paging.total())); } private static void addFavorites(SearchResponse.Builder builder, SearchResults results) { Favorite.Builder favoriteBuilder = Favorite.newBuilder(); results.favorites.stream() .map(componentDto -> toWsFavorite(favoriteBuilder, componentDto)) .forEach(builder::addFavorites); } private static Favorite toWsFavorite(Favorite.Builder builder, EntityDto entity) { builder .clear() .setKey(entity.getKey()); ofNullable(entity.getName()).ifPresent(builder::setName); ofNullable(entity.getQualifier()).ifPresent(builder::setQualifier); return builder.build(); } private static class SearchRequest { private String p; private String ps; public SearchRequest setP(String p) { this.p = p; return this; } public String getP() { return p; } public SearchRequest setPs(String ps) { this.ps = ps; return this; } public String getPs() { return ps; } } }
5,417
33.075472
159
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/favorite/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.favorite.ws; import javax.annotation.ParametersAreNonnullByDefault;
969
37.8
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/feature/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.feature;
925
41.090909
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/feature/ws/FeatureWs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.feature.ws; import org.sonar.api.server.ws.WebService; public class FeatureWs implements WebService { private final ListAction list; public FeatureWs(ListAction list) { this.list = list; } @Override public void define(Context context) { NewController features = context.createController("api/features") .setDescription("Provides information about features available in SonarQube") .setSince("9.6"); list.define(features); features.done(); } }
1,358
30.604651
83
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/feature/ws/FeatureWsModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.feature.ws; import org.sonar.core.platform.Module; public class FeatureWsModule extends Module { @Override protected void configureModule() { add(ListAction.class, FeatureWs.class); } }
1,067
33.451613
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/feature/ws/ListAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.feature.ws; import com.google.common.io.Resources; import java.util.List; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.text.JsonWriter; import org.sonar.server.feature.SonarQubeFeature; import org.sonar.server.ws.WsAction; public class ListAction implements WsAction { private final List<SonarQubeFeature> sonarQubeFeatures; public ListAction(List<SonarQubeFeature> sonarQubeFeatures) { this.sonarQubeFeatures = sonarQubeFeatures; } @Override public void define(WebService.NewController controller) { controller.createAction("list") .setDescription("List supported features") .setSince("9.6") .setInternal(true) .setHandler(this) .setResponseExample(Resources.getResource(getClass(), "example-list.json")); } @Override public void handle(Request request, Response response) throws Exception { try (JsonWriter json = response.newJsonWriter()) { json.beginArray(); sonarQubeFeatures.stream() .filter(SonarQubeFeature::isAvailable) .forEach(f -> json.value(f.getName())); json.endArray(); } } }
2,070
33.516667
82
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/feature/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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. */ @javax.annotation.ParametersAreNonnullByDefault package org.sonar.server.feature.ws;
928
41.227273
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/AppNodeClusterCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import java.util.Arrays; import java.util.Set; import java.util.stream.Collectors; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import static org.sonar.process.cluster.health.NodeHealth.Status.GREEN; import static org.sonar.process.cluster.health.NodeHealth.Status.RED; import static org.sonar.process.cluster.health.NodeHealth.Status.YELLOW; public class AppNodeClusterCheck implements ClusterHealthCheck { @Override public Health check(Set<NodeHealth> nodeHealths) { Set<NodeHealth> appNodes = nodeHealths.stream() .filter(s -> s.getDetails().getType() == NodeDetails.Type.APPLICATION) .collect(Collectors.toSet()); return Arrays.stream(AppNodeClusterHealthSubChecks.values()) .map(s -> s.check(appNodes)) .reduce(Health.GREEN, HealthReducer::merge); } private enum AppNodeClusterHealthSubChecks implements ClusterHealthSubCheck { NO_APPLICATION_NODE() { @Override public Health check(Set<NodeHealth> appNodes) { int appNodeCount = appNodes.size(); if (appNodeCount == 0) { return Health.builder() .setStatus(Health.Status.RED) .addCause("No application node") .build(); } return Health.GREEN; } }, MIN_APPLICATION_NODE_COUNT() { @Override public Health check(Set<NodeHealth> appNodes) { int appNodeCount = appNodes.size(); if (appNodeCount == 1) { return Health.builder() .setStatus(Health.Status.YELLOW) .addCause("There should be at least two application nodes") .build(); } return Health.GREEN; } }, REPORT_RED_OR_YELLOW_NODES() { @Override public Health check(Set<NodeHealth> appNodes) { int appNodeCount = appNodes.size(); if (appNodeCount == 0) { // skipping this check return Health.GREEN; } long redNodesCount = withStatus(appNodes, RED).count(); long yellowNodesCount = withStatus(appNodes, YELLOW).count(); if (redNodesCount == 0 && yellowNodesCount == 0) { return Health.GREEN; } Health.Builder builder = Health.builder(); if (redNodesCount == appNodeCount) { return builder .setStatus(Health.Status.RED) .addCause("Status of all application nodes is RED") .build(); } else if (redNodesCount > 0) { builder.addCause("At least one application node is RED"); } if (yellowNodesCount == appNodeCount) { return builder .setStatus(Health.Status.YELLOW) .addCause("Status of all application nodes is YELLOW") .build(); } else if (yellowNodesCount > 0) { builder.addCause("At least one application node is YELLOW"); } long greenNodesCount = withStatus(appNodes, GREEN).count(); builder.setStatus(greenNodesCount > 0 || yellowNodesCount > 0 ? Health.Status.YELLOW : Health.Status.RED); return builder.build(); } } } }
4,022
34.919643
114
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/CeStatusNodeCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import org.sonar.server.app.ProcessCommandWrapper; public class CeStatusNodeCheck implements NodeHealthCheck { private static final Health RED_HEALTH = Health.builder() .setStatus(Health.Status.RED) .addCause("Compute Engine is not operational") .build(); private final ProcessCommandWrapper processCommandWrapper; public CeStatusNodeCheck(ProcessCommandWrapper processCommandWrapper) { this.processCommandWrapper = processCommandWrapper; } @Override public Health check() { if (processCommandWrapper.isCeOperational()) { return Health.GREEN; } return RED_HEALTH; } }
1,498
32.311111
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/ClusterHealthCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import java.util.Set; import org.sonar.process.cluster.health.NodeHealth; public interface ClusterHealthCheck { Health check(Set<NodeHealth> nodeHealths); }
1,037
36.071429
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/ClusterHealthSubCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import java.util.Set; import java.util.stream.Stream; import org.sonar.process.cluster.health.NodeHealth; interface ClusterHealthSubCheck extends ClusterHealthCheck { default Stream<NodeHealth> withStatus(Set<NodeHealth> searchNodes, NodeHealth.Status... statuses) { return searchNodes.stream() .filter(t -> { for (NodeHealth.Status status : statuses) { if (status == t.getStatus()) { return true; } } return false; }); } }
1,395
33.9
101
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/DbConnectionNodeCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.IsAliveMapper; /** * Checks Web Server can connect to the Database. */ public class DbConnectionNodeCheck implements NodeHealthCheck { private static final Logger LOGGER = LoggerFactory.getLogger(DbConnectionNodeCheck.class); private static final Health RED_HEALTH = Health.builder().setStatus(Health.Status.RED).addCause("Can't connect to DB").build(); private final DbClient dbClient; public DbConnectionNodeCheck(DbClient dbClient) { this.dbClient = dbClient; } @Override public Health check() { if (isConnectedToDB()) { return Health.GREEN; } return RED_HEALTH; } private boolean isConnectedToDB() { try (DbSession dbSession = dbClient.openSession(false)) { return dbSession.getMapper(IsAliveMapper.class).isAlive() == IsAliveMapper.IS_ALIVE_RETURNED_VALUE; } catch (RuntimeException e) { LOGGER.trace("DB connection is down: {}", e.getMessage(), e); return false; } } }
1,969
32.965517
129
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/EsStatusCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.cluster.health.ClusterHealthStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.server.es.EsClient; abstract class EsStatusCheck { private static final Logger LOG = LoggerFactory.getLogger(EsStatusCheck.class); private static final Health YELLOW_HEALTH = Health.builder() .setStatus(Health.Status.YELLOW) .addCause("Elasticsearch status is YELLOW") .build(); private static final Health RED_HEALTH = Health.builder() .setStatus(Health.Status.RED) .addCause("Elasticsearch status is RED") .build(); protected static final Health RED_HEALTH_UNAVAILABLE = Health.builder() .setStatus(Health.Status.RED) .addCause("Elasticsearch status is RED (unavailable)") .build(); private final EsClient esClient; EsStatusCheck(EsClient esClient) { this.esClient = esClient; } protected ClusterHealthResponse getEsClusterHealth() { try { return esClient.clusterHealth(new ClusterHealthRequest()); } catch (Exception e) { LOG.error("Failed to query ES status", e); return null; } } protected static Health extractStatusHealth(ClusterHealthResponse healthResponse) { ClusterHealthStatus esStatus = healthResponse.getStatus(); if (esStatus == null) { return RED_HEALTH_UNAVAILABLE; } switch (esStatus) { case GREEN: return Health.GREEN; case YELLOW: return YELLOW_HEALTH; case RED: return RED_HEALTH; default: throw new IllegalArgumentException("Unsupported Elasticsearch status " + esStatus); } } }
2,645
32.923077
91
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/EsStatusClusterCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import java.util.Set; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.sonar.process.cluster.health.NodeHealth; import org.sonar.server.es.EsClient; public class EsStatusClusterCheck extends EsStatusCheck implements ClusterHealthCheck { private static final String MINIMUM_NODE_MESSAGE = "There should be at least three search nodes"; private static final int RECOMMENDED_MIN_NUMBER_OF_ES_NODES = 3; public EsStatusClusterCheck(EsClient esClient) { super(esClient); } @Override public Health check(Set<NodeHealth> nodeHealths) { ClusterHealthResponse esClusterHealth = this.getEsClusterHealth(); if (esClusterHealth != null) { Health minimumNodes = checkMinimumNodes(esClusterHealth); Health clusterStatus = extractStatusHealth(esClusterHealth); return HealthReducer.merge(minimumNodes, clusterStatus); } return RED_HEALTH_UNAVAILABLE; } private static Health checkMinimumNodes(ClusterHealthResponse esClusterHealth) { int nodeCount = esClusterHealth.getNumberOfNodes(); if (nodeCount < RECOMMENDED_MIN_NUMBER_OF_ES_NODES) { return Health.builder() .setStatus(Health.Status.YELLOW) .addCause(MINIMUM_NODE_MESSAGE) .build(); } return Health.GREEN; } }
2,173
36.482759
99
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/EsStatusNodeCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.sonar.server.es.EsClient; /** * Checks the ElasticSearch cluster status. */ public class EsStatusNodeCheck extends EsStatusCheck implements NodeHealthCheck { public EsStatusNodeCheck(EsClient esClient) { super(esClient); } @Override public Health check() { ClusterHealthResponse healthResponse = getEsClusterHealth(); return healthResponse != null ? extractStatusHealth(healthResponse) : RED_HEALTH_UNAVAILABLE; } }
1,407
34.2
97
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/HealthCheckerImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.process.cluster.health.NodeHealth; import org.sonar.process.cluster.health.SharedHealthState; import org.sonar.server.platform.NodeInformation; import org.springframework.beans.factory.annotation.Autowired; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.ImmutableList.copyOf; /** * Implementation of {@link HealthChecker} based on {@link NodeHealthCheck} and {@link ClusterHealthCheck} instances * available in the container. */ public class HealthCheckerImpl implements HealthChecker { private final NodeInformation nodeInformation; private final List<NodeHealthCheck> nodeHealthChecks; private final List<ClusterHealthCheck> clusterHealthChecks; @CheckForNull private final SharedHealthState sharedHealthState; /** * Constructor used by the ioc container in standalone mode and in safe mode. */ @Autowired(required = false) public HealthCheckerImpl(NodeInformation nodeInformation, NodeHealthCheck[] nodeHealthChecks) { this(nodeInformation, nodeHealthChecks, new ClusterHealthCheck[0], null); } /** * Constructor used by the ioc container in cluster mode. */ @Autowired(required = false) public HealthCheckerImpl(NodeInformation nodeInformation, NodeHealthCheck[] nodeHealthChecks, ClusterHealthCheck[] clusterHealthChecks, @Nullable SharedHealthState sharedHealthState) { this.nodeInformation = nodeInformation; this.nodeHealthChecks = copyOf(nodeHealthChecks); this.clusterHealthChecks = copyOf(clusterHealthChecks); this.sharedHealthState = sharedHealthState; } @Override public Health checkNode() { return nodeHealthChecks.stream() .map(NodeHealthCheck::check) .reduce(Health.GREEN, HealthReducer::merge); } @Override public ClusterHealth checkCluster() { checkState(!nodeInformation.isStandalone(), "Clustering is not enabled"); checkState(sharedHealthState != null, "HealthState instance can't be null when clustering is enabled"); Set<NodeHealth> nodeHealths = sharedHealthState.readAll(); Health health = clusterHealthChecks.stream() .map(clusterHealthCheck -> clusterHealthCheck.check(nodeHealths)) .reduce(Health.GREEN, HealthReducer::merge); return new ClusterHealth(health, nodeHealths); } }
3,307
37.917647
137
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/HealthReducer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; public class HealthReducer { private HealthReducer() { // no public constructor } public static Health merge(Health left, Health right) { Health.Builder builder = Health.builder() .setStatus(worseOf(left.getStatus(), right.getStatus())); left.getCauses().forEach(builder::addCause); right.getCauses().forEach(builder::addCause); return builder.build(); } private static Health.Status worseOf(Health.Status left, Health.Status right) { if (left == right) { return left; } if (left.ordinal() > right.ordinal()) { return left; } return right; } }
1,495
30.829787
81
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/HealthStateRefresherExecutorServiceImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import com.google.common.util.concurrent.ThreadFactoryBuilder; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import org.sonar.process.cluster.health.HealthStateRefresherExecutorService; import org.sonar.server.util.AbstractStoppableScheduledExecutorServiceImpl; public class HealthStateRefresherExecutorServiceImpl extends AbstractStoppableScheduledExecutorServiceImpl<ScheduledExecutorService> implements HealthStateRefresherExecutorService { public HealthStateRefresherExecutorServiceImpl() { super(Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setDaemon(false) .setNameFormat("health_state_refresh-%d") .build())); } }
1,615
40.435897
81
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/NodeHealthCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; public interface NodeHealthCheck { Health check(); }
932
36.32
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/NodeHealthModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import org.sonar.core.platform.Module; import org.sonar.process.cluster.health.HealthStateRefresher; import org.sonar.process.cluster.health.SharedHealthStateImpl; public class NodeHealthModule extends Module { @Override protected void configureModule() { add( NodeHealthProviderImpl.class, HealthStateRefresherExecutorServiceImpl.class, HealthStateRefresher.class, SharedHealthStateImpl.class); } }
1,312
35.472222
75
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/NodeHealthProviderImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; import java.util.function.Supplier; import org.sonar.api.config.Configuration; import org.sonar.api.platform.Server; import org.sonar.process.NetworkUtils; import org.sonar.process.cluster.health.NodeDetails; import org.sonar.process.cluster.health.NodeHealth; import org.sonar.process.cluster.health.NodeHealthProvider; import static java.lang.String.format; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HOST; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_HZ_PORT; import static org.sonar.process.cluster.health.NodeDetails.newNodeDetailsBuilder; import static org.sonar.process.cluster.health.NodeHealth.newNodeHealthBuilder; public class NodeHealthProviderImpl implements NodeHealthProvider { private final HealthChecker healthChecker; private final NodeHealth.Builder nodeHealthBuilder; private final NodeDetails nodeDetails; public NodeHealthProviderImpl(Configuration configuration, HealthChecker healthChecker, Server server, NetworkUtils networkUtils) { this.healthChecker = healthChecker; this.nodeHealthBuilder = newNodeHealthBuilder(); this.nodeDetails = newNodeDetailsBuilder() .setName(computeName(configuration)) .setType(NodeDetails.Type.APPLICATION) .setHost(computeHost(configuration, networkUtils)) .setPort(computePort(configuration)) .setStartedAt(server.getStartedAt().getTime()) .build(); } private static String computeName(Configuration configuration) { return configuration.get(CLUSTER_NODE_NAME.getKey()) .orElseThrow(missingPropertyISE(CLUSTER_NODE_NAME.getKey())); } private static String computeHost(Configuration configuration, NetworkUtils networkUtils) { return configuration.get(CLUSTER_NODE_HOST.getKey()) .filter(s -> !s.isEmpty()) .orElseGet(networkUtils::getHostname); } private static int computePort(Configuration configuration) { return configuration.getInt(CLUSTER_NODE_HZ_PORT.getKey()) .orElseThrow(missingPropertyISE(CLUSTER_NODE_HZ_PORT.getKey())); } private static Supplier<IllegalStateException> missingPropertyISE(String propertyName) { return () -> new IllegalStateException(format("Property %s is not defined", propertyName)); } @Override public NodeHealth get() { Health nodeHealth = healthChecker.checkNode(); this.nodeHealthBuilder .clearCauses() .setStatus(NodeHealth.Status.valueOf(nodeHealth.getStatus().name())); nodeHealth.getCauses().forEach(this.nodeHealthBuilder::addCause); return this.nodeHealthBuilder .setDetails(nodeDetails) .build(); } }
3,582
40.183908
133
java
sonarqube
sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/health/WebServerSafemodeNodeCheck.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program 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. * * This program 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.server.health; /** * Checks the running status of the WebServer when the WebServer is in safemode. * Obviously, it statically returns a red health status. */ public class WebServerSafemodeNodeCheck implements NodeHealthCheck { private static final Health RED_HEALTH = Health.builder() .setStatus(Health.Status.RED) .addCause("SonarQube webserver is not up") .build(); @Override public Health check() { return RED_HEALTH; } }
1,316
33.657895
80
java