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/permission/ws/template/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.permission.ws.template;
import javax.annotation.ParametersAreNonnullByDefault;
| 979 | 39.833333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/ChangeLogLevelAction.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.platform.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.api.utils.log.LoggerLevel;
import org.sonar.server.user.UserSession;
import static org.sonar.process.logging.LogbackHelper.allowedLogLevels;
public class ChangeLogLevelAction implements SystemWsAction {
private static final String PARAM_LEVEL = "level";
private final UserSession userSession;
private final ChangeLogLevelService service;
public ChangeLogLevelAction(UserSession userSession, ChangeLogLevelService service) {
this.userSession = userSession;
this.service = service;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction newAction = controller.createAction("change_log_level")
.setDescription("Temporarily changes level of logs. New level is not persistent and is lost " +
"when restarting server. Requires system administration permission.")
.setSince("5.2")
.setPost(true)
.setHandler(this);
newAction.createParam(PARAM_LEVEL)
.setDescription("The new level. Be cautious: DEBUG, and even more TRACE, may have performance impacts.")
.setPossibleValues(allowedLogLevels())
.setRequired(true);
}
@Override
public void handle(Request wsRequest, Response wsResponse) throws InterruptedException {
userSession.checkIsSystemAdministrator();
LoggerLevel level = LoggerLevel.valueOf(wsRequest.mandatoryParam(PARAM_LEVEL));
service.changeLogLevel(level);
wsResponse.noContent();
}
}
| 2,461 | 36.30303 | 110 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/ChangeLogLevelClusterService.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.platform.ws;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.sonar.api.utils.log.LoggerLevel;
import org.slf4j.LoggerFactory;
import org.sonar.process.ProcessId;
import org.sonar.process.cluster.hz.DistributedCall;
import org.sonar.process.cluster.hz.HazelcastMember;
import org.sonar.process.cluster.hz.HazelcastMemberSelectors;
import org.sonar.server.log.ServerLogging;
public class ChangeLogLevelClusterService implements ChangeLogLevelService {
private static final long CLUSTER_TIMEOUT_MILLIS = 5000;
private static final Logger LOGGER = LoggerFactory.getLogger(ChangeLogLevelClusterService.class);
private final HazelcastMember member;
public ChangeLogLevelClusterService(@Nullable HazelcastMember member) {
this.member = member;
}
public void changeLogLevel(LoggerLevel level) throws InterruptedException {
member.call(setLogLevelForNode(level), HazelcastMemberSelectors.selectorForProcessIds(ProcessId.WEB_SERVER, ProcessId.COMPUTE_ENGINE), CLUSTER_TIMEOUT_MILLIS)
.propagateExceptions();
}
private static DistributedCall<Object> setLogLevelForNode(LoggerLevel level) {
return () -> {
try {
ServerLogging.changeLevelFromHazelcastDistributedQuery(level);
} catch (Exception e) {
LOGGER.error("Setting log level to '" + level.name() + "' in this cluster node failed", e);
throw new IllegalStateException("Setting log level to '" + level.name() + "' in this cluster node failed", e);
}
return null;
};
}
}
| 2,397 | 38.966667 | 162 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/ChangeLogLevelService.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.platform.ws;
import org.sonar.api.utils.log.LoggerLevel;
public interface ChangeLogLevelService {
void changeLogLevel(LoggerLevel level) throws InterruptedException;
}
| 1,042 | 34.965517 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/ChangeLogLevelServiceModule.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.platform.ws;
import org.sonar.core.platform.Module;
import org.sonar.server.platform.NodeInformation;
public class ChangeLogLevelServiceModule extends Module {
private final NodeInformation nodeInformation;
public ChangeLogLevelServiceModule(NodeInformation nodeInformation) {
this.nodeInformation = nodeInformation;
}
@Override
protected void configureModule() {
if (nodeInformation.isStandalone()) {
add(ChangeLogLevelStandaloneService.class);
} else {
add(ChangeLogLevelClusterService.class);
}
}
}
| 1,414 | 33.512195 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/ChangeLogLevelStandaloneService.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.platform.ws;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.server.ce.http.CeHttpClient;
import org.sonar.server.log.ServerLogging;
public class ChangeLogLevelStandaloneService implements ChangeLogLevelService {
private final ServerLogging logging;
private final CeHttpClient ceHttpClient;
public ChangeLogLevelStandaloneService(ServerLogging logging, CeHttpClient ceHttpClient) {
this.logging = logging;
this.ceHttpClient = ceHttpClient;
}
public void changeLogLevel(LoggerLevel level) {
logging.changeLevel(level);
ceHttpClient.changeLogLevel(level);
}
}
| 1,472 | 34.926829 | 92 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/DbMigrationJsonWriter.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.platform.ws;
import org.sonar.api.utils.text.JsonWriter;
import org.sonar.server.platform.db.migration.DatabaseMigrationState;
import static org.sonar.server.platform.db.migration.DatabaseMigrationState.Status.RUNNING;
public class DbMigrationJsonWriter {
static final String FIELD_STATE = "state";
static final String FIELD_MESSAGE = "message";
static final String FIELD_STARTED_AT = "startedAt";
static final String STATUS_NO_MIGRATION = "NO_MIGRATION";
static final String STATUS_NOT_SUPPORTED = "NOT_SUPPORTED";
static final String STATUS_MIGRATION_RUNNING = "MIGRATION_RUNNING";
static final String STATUS_MIGRATION_FAILED = "MIGRATION_FAILED";
static final String STATUS_MIGRATION_SUCCEEDED = "MIGRATION_SUCCEEDED";
static final String STATUS_MIGRATION_REQUIRED = "MIGRATION_REQUIRED";
static final String NO_CONNECTION_TO_DB = "Cannot connect to Database.";
static final String UNSUPPORTED_DATABASE_MIGRATION_STATUS = "Unsupported DatabaseMigration status";
static final String MESSAGE_NO_MIGRATION_ON_EMBEDDED_DATABASE = "Upgrade is not supported on embedded database.";
static final String MESSAGE_MIGRATION_REQUIRED = "Database migration is required. DB migration can be started using WS /api/system/migrate_db.";
static final String MESSAGE_STATUS_NONE = "Database is up-to-date, no migration needed.";
static final String MESSAGE_STATUS_RUNNING = "Database migration is running.";
static final String MESSAGE_STATUS_SUCCEEDED = "Migration succeeded.";
static final String MESSAGE_STATUS_FAILED = "Migration failed: %s.<br/> Please check logs.";
private DbMigrationJsonWriter() {
// static methods only
}
static void write(JsonWriter json, DatabaseMigrationState databaseMigrationState) {
json.beginObject()
.prop(FIELD_STATE, statusToJson(databaseMigrationState.getStatus()))
.prop(FIELD_MESSAGE, buildMessage(databaseMigrationState))
.propDateTime(FIELD_STARTED_AT, databaseMigrationState.getStartedAt())
.endObject();
}
static void writeNotSupportedResponse(JsonWriter json) {
json.beginObject()
.prop(FIELD_STATE, STATUS_NOT_SUPPORTED)
.prop(FIELD_MESSAGE, MESSAGE_NO_MIGRATION_ON_EMBEDDED_DATABASE)
.endObject();
}
static void writeJustStartedResponse(JsonWriter json, DatabaseMigrationState databaseMigrationState) {
json.beginObject()
.prop(FIELD_STATE, statusToJson(RUNNING))
.prop(FIELD_MESSAGE, MESSAGE_STATUS_RUNNING)
.propDateTime(FIELD_STARTED_AT, databaseMigrationState.getStartedAt())
.endObject();
}
static void writeMigrationRequiredResponse(JsonWriter json) {
json.beginObject()
.prop(FIELD_STATE, STATUS_MIGRATION_REQUIRED)
.prop(FIELD_MESSAGE, MESSAGE_MIGRATION_REQUIRED)
.endObject();
}
private static String statusToJson(DatabaseMigrationState.Status status) {
switch (status) {
case NONE:
return STATUS_NO_MIGRATION;
case RUNNING:
return STATUS_MIGRATION_RUNNING;
case FAILED:
return STATUS_MIGRATION_FAILED;
case SUCCEEDED:
return STATUS_MIGRATION_SUCCEEDED;
default:
throw new IllegalArgumentException(
"Unsupported DatabaseMigration.Status " + status + " can not be converted to JSON value");
}
}
private static String buildMessage(DatabaseMigrationState databaseMigrationState) {
switch (databaseMigrationState.getStatus()) {
case NONE:
return MESSAGE_STATUS_NONE;
case RUNNING:
return MESSAGE_STATUS_RUNNING;
case SUCCEEDED:
return MESSAGE_STATUS_SUCCEEDED;
case FAILED:
return String.format(MESSAGE_STATUS_FAILED, failureMessage(databaseMigrationState));
default:
return UNSUPPORTED_DATABASE_MIGRATION_STATUS;
}
}
private static String failureMessage(DatabaseMigrationState databaseMigrationState) {
Throwable failureError = databaseMigrationState.getError();
if (failureError == null) {
return "No failure error";
}
return failureError.getMessage();
}
static String statusDescription() {
return "State values are:" +
"<ul>" +
"<li>NO_MIGRATION: DB is up to date with current version of SonarQube.</li>" +
"<li>NOT_SUPPORTED: Migration is not supported on embedded databases.</li>" +
"<li>MIGRATION_RUNNING: DB migration is under go.</li>" +
"<li>MIGRATION_SUCCEEDED: DB migration has run and has been successful.</li>" +
"<li>MIGRATION_FAILED: DB migration has run and failed. SonarQube must be restarted in order to retry a " +
"DB migration (optionally after DB has been restored from backup).</li>" +
"<li>MIGRATION_REQUIRED: DB migration is required.</li>" +
"</ul>";
}
}
| 5,619 | 40.940299 | 146 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/DbMigrationStatusAction.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.platform.ws;
import com.google.common.io.Resources;
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.utils.text.JsonWriter;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.DatabaseMigrationState;
import org.sonar.server.platform.db.migration.version.DatabaseVersion;
import static com.google.common.base.Preconditions.checkState;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.NO_CONNECTION_TO_DB;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.UNSUPPORTED_DATABASE_MIGRATION_STATUS;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.statusDescription;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.write;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.writeMigrationRequiredResponse;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.writeNotSupportedResponse;
/**
* Implementation of the {@code db_migration_status} action for the System WebService.
*/
public class DbMigrationStatusAction implements SystemWsAction {
private final DatabaseVersion databaseVersion;
private final DatabaseMigrationState databaseMigrationState;
private final Database database;
public DbMigrationStatusAction(DatabaseVersion databaseVersion, Database database, DatabaseMigrationState databaseMigrationState) {
this.databaseVersion = databaseVersion;
this.database = database;
this.databaseMigrationState = databaseMigrationState;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("db_migration_status")
.setDescription("Display the database migration status of SonarQube." +
"<br/>" +
statusDescription())
.setSince("5.2")
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "example-migrate_db.json"));
}
@Override
public void handle(Request request, Response response) throws Exception {
Optional<Long> currentVersion = databaseVersion.getVersion();
checkState(currentVersion.isPresent(), NO_CONNECTION_TO_DB);
try (JsonWriter json = response.newJsonWriter()) {
DatabaseVersion.Status status = databaseVersion.getStatus();
if (status == DatabaseVersion.Status.UP_TO_DATE || status == DatabaseVersion.Status.REQUIRES_DOWNGRADE) {
write(json, databaseMigrationState);
} else if (!database.getDialect().supportsMigration()) {
writeNotSupportedResponse(json);
} else {
switch (databaseMigrationState.getStatus()) {
case RUNNING, FAILED, SUCCEEDED:
write(json, databaseMigrationState);
break;
case NONE:
writeMigrationRequiredResponse(json);
break;
default:
throw new IllegalArgumentException(UNSUPPORTED_DATABASE_MIGRATION_STATUS);
}
}
}
}
}
| 3,870 | 41.076087 | 133 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/HealthAction.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.platform.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.server.exceptions.ForbiddenException;
import org.sonar.server.platform.NodeInformation;
import org.sonar.server.user.SystemPasscode;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.WsUtils;
public class HealthAction implements SystemWsAction {
private final NodeInformation nodeInformation;
private final HealthActionSupport support;
private final SystemPasscode systemPasscode;
private final UserSession userSession;
public HealthAction(NodeInformation nodeInformation, HealthActionSupport support, SystemPasscode systemPasscode, UserSession userSession) {
this.nodeInformation = nodeInformation;
this.support = support;
this.systemPasscode = systemPasscode;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController controller) {
support.define(controller, this);
}
@Override
public void handle(Request request, Response response) throws Exception {
if (!systemPasscode.isValid(request) && !isSystemAdmin()) {
throw new ForbiddenException("Insufficient privileges");
}
if (nodeInformation.isStandalone()) {
WsUtils.writeProtobuf(support.checkNodeHealth(), request, response);
} else {
WsUtils.writeProtobuf(support.checkClusterHealth(), request, response);
}
}
private boolean isSystemAdmin() {
return userSession.isSystemAdministrator();
}
}
| 2,416 | 35.074627 | 141 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/HealthActionSupport.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.platform.ws;
import com.google.common.io.Resources;
import java.util.Comparator;
import org.sonar.api.server.ws.WebService;
import org.sonar.process.ProcessProperties;
import org.sonar.process.cluster.health.NodeDetails;
import org.sonar.process.cluster.health.NodeHealth;
import org.sonar.server.health.ClusterHealth;
import org.sonar.server.health.Health;
import org.sonar.server.health.HealthChecker;
import org.sonarqube.ws.System;
import static org.sonar.api.utils.DateUtils.formatDateTime;
public class HealthActionSupport {
private static final Comparator<NodeHealth> NODE_HEALTH_COMPARATOR = Comparator.<NodeHealth>comparingInt(s -> s.getDetails().getType().ordinal())
.thenComparing(a -> a.getDetails().getName())
.thenComparing(a -> a.getDetails().getHost())
.thenComparing(a -> a.getDetails().getPort());
private final HealthChecker healthChecker;
public HealthActionSupport(HealthChecker healthChecker) {
this.healthChecker = healthChecker;
}
void define(WebService.NewController controller, SystemWsAction handler) {
controller.createAction("health")
.setDescription("Provide health status of SonarQube." +
"<p>Although global health is calculated based on both application and search nodes, detailed information is returned only for application nodes.</p>" +
"<p> " +
" <ul>" +
" <li>GREEN: SonarQube is fully operational</li>" +
" <li>YELLOW: SonarQube is usable, but it needs attention in order to be fully operational</li>" +
" <li>RED: SonarQube is not operational</li>" +
" </ul>" +
"</p><br>" +
"Requires the 'Administer System' permission or " +
"system passcode (see " + ProcessProperties.Property.WEB_SYSTEM_PASS_CODE + " in sonar.properties).<br>" +
"When SonarQube is in safe mode (waiting or running a database upgrade), only the authentication with a system passcode is supported.")
.setSince("6.6")
.setResponseExample(Resources.getResource(this.getClass(), "example-health.json"))
.setHandler(handler);
}
System.HealthResponse checkNodeHealth() {
Health check = healthChecker.checkNode();
System.HealthResponse.Builder responseBuilder = System.HealthResponse.newBuilder()
.setHealth(System.Health.valueOf(check.getStatus().name()));
System.Cause.Builder causeBuilder = System.Cause.newBuilder();
check.getCauses().forEach(str -> responseBuilder.addCauses(causeBuilder.clear().setMessage(str).build()));
return responseBuilder.build();
}
System.HealthResponse checkClusterHealth() {
ClusterHealth check = healthChecker.checkCluster();
return toResponse(check);
}
private static System.HealthResponse toResponse(ClusterHealth check) {
System.HealthResponse.Builder responseBuilder = System.HealthResponse.newBuilder();
System.Node.Builder nodeBuilder = System.Node.newBuilder();
System.Cause.Builder causeBuilder = System.Cause.newBuilder();
Health health = check.getHealth();
responseBuilder.setHealth(System.Health.valueOf(health.getStatus().name()));
health.getCauses().forEach(str -> responseBuilder.addCauses(toCause(str, causeBuilder)));
System.Nodes.Builder nodesBuilder = System.Nodes.newBuilder();
check.getNodes().stream()
.sorted(NODE_HEALTH_COMPARATOR)
.map(node -> toNode(node, nodeBuilder, causeBuilder))
.forEach(nodesBuilder::addNodes);
responseBuilder.setNodes(nodesBuilder.build());
return responseBuilder.build();
}
private static System.Node toNode(NodeHealth nodeHealth, System.Node.Builder nodeBuilder, System.Cause.Builder causeBuilder) {
nodeBuilder.clear();
nodeBuilder.setHealth(System.Health.valueOf(nodeHealth.getStatus().name()));
nodeHealth.getCauses().forEach(str -> nodeBuilder.addCauses(toCause(str, causeBuilder)));
NodeDetails details = nodeHealth.getDetails();
nodeBuilder
.setType(System.NodeType.valueOf(details.getType().name()))
.setName(details.getName())
.setHost(details.getHost())
.setPort(details.getPort())
.setStartedAt(formatDateTime(details.getStartedAt()));
return nodeBuilder.build();
}
private static System.Cause toCause(String str, System.Cause.Builder causeBuilder) {
return causeBuilder.clear().setMessage(str).build();
}
}
| 5,203 | 43.478632 | 160 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/HealthCheckerModule.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.platform.ws;
import org.sonar.core.platform.Module;
import org.sonar.server.health.AppNodeClusterCheck;
import org.sonar.server.health.CeStatusNodeCheck;
import org.sonar.server.health.DbConnectionNodeCheck;
import org.sonar.server.health.EsStatusClusterCheck;
import org.sonar.server.health.EsStatusNodeCheck;
import org.sonar.server.health.HealthCheckerImpl;
import org.sonar.server.health.WebServerStatusNodeCheck;
import org.sonar.server.platform.NodeInformation;
public class HealthCheckerModule extends Module {
private final NodeInformation nodeInformation;
public HealthCheckerModule(NodeInformation nodeInformation) {
this.nodeInformation = nodeInformation;
}
@Override
protected void configureModule() {
// NodeHealthCheck implementations
add(WebServerStatusNodeCheck.class,
DbConnectionNodeCheck.class,
CeStatusNodeCheck.class);
if (nodeInformation.isStandalone()) {
add(EsStatusNodeCheck.class);
} else {
// ClusterHealthCheck implementations
add(EsStatusClusterCheck.class,
AppNodeClusterCheck.class);
}
add(HealthCheckerImpl.class);
}
}
| 2,002 | 34.767857 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/IndexAction.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.platform.ws;
import java.util.Date;
import java.util.Locale;
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.utils.text.JsonWriter;
import org.sonar.core.i18n.DefaultI18n;
import org.sonar.server.ws.WsAction;
import static com.google.common.base.Preconditions.checkArgument;
import static java.net.HttpURLConnection.HTTP_NOT_MODIFIED;
import static java.util.Locale.ENGLISH;
public class IndexAction implements WsAction {
private static final String LOCALE_PARAM = "locale";
private static final String TS_PARAM = "ts";
private final DefaultI18n i18n;
private final Server server;
public IndexAction(DefaultI18n i18n, Server server) {
this.i18n = i18n;
this.server = server;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction indexAction = context.createAction("index")
.setInternal(true)
.setDescription("Get all localization messages for a given locale")
.setResponseExample(getClass().getResource("l10n-index-example.json"))
.setSince("4.4")
.setHandler(this);
indexAction.createParam(LOCALE_PARAM)
.setDescription("BCP47 language tag, used to override the browser Accept-Language header")
.setExampleValue("fr-CH")
.setDefaultValue(ENGLISH.toLanguageTag());
indexAction.createParam(TS_PARAM)
.setDescription("Date of the last cache update.")
.setExampleValue("2014-06-04T09:31:42+0000");
}
@Override
public void handle(Request request, Response response) throws Exception {
Date timestamp = request.paramAsDateTime(TS_PARAM);
if (timestamp != null && timestamp.after(server.getStartedAt())) {
response.stream().setStatus(HTTP_NOT_MODIFIED).output().close();
return;
}
String localeParam = request.mandatoryParam(LOCALE_PARAM);
Locale locale = Locale.forLanguageTag(localeParam);
checkArgument(!locale.getISO3Language().isEmpty(), "Locale cannot be parsed as a BCP47 language tag");
try (JsonWriter json = response.newJsonWriter()) {
json.beginObject();
json.prop("effectiveLocale", i18n.getEffectiveLocale(locale).toLanguageTag());
json.name("messages");
json.beginObject();
i18n.getPropertyKeys().forEach(messageKey -> json.prop(messageKey, i18n.message(locale, messageKey, messageKey)));
json.endObject();
json.endObject();
}
}
}
| 3,374 | 37.793103 | 120 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/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.platform.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.server.platform.SystemInfoWriter;
import org.sonar.server.user.UserSession;
/**
* Implementation of the {@code info} action for the System WebService.
*/
public class InfoAction implements SystemWsAction {
private final SystemInfoWriter systemInfoWriter;
private final UserSession userSession;
public InfoAction(UserSession userSession, SystemInfoWriter systemInfoWriter) {
this.userSession = userSession;
this.systemInfoWriter = systemInfoWriter;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("info")
.setDescription("Get detailed information about system configuration.<br/>" +
"Requires 'Administer' permissions.")
.setSince("5.1")
.setResponseExample(getClass().getResource("info-example.json"))
.setHandler(this);
action.setChangelog(
new Change("5.5", "Becomes internal to easily update result"),
new Change("8.3", "Becomes public"),
new Change("9.7", "'Statistics' field has been removed from response"),
new Change("9.8", "'Edition' field added to the response under the 'System' section")
);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkIsSystemAdministrator();
JsonWriter json = response.newJsonWriter();
json.beginObject();
systemInfoWriter.write(json);
json.endObject();
json.close();
}
}
| 2,571 | 35.742857 | 91 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/L10nWs.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.platform.ws;
import org.sonar.api.server.ws.WebService;
public class L10nWs implements WebService {
private final IndexAction indexAction;
public L10nWs(IndexAction indexAction) {
this.indexAction = indexAction;
}
@Override
public void define(Context context) {
NewController l10n = context.createController("api/l10n");
l10n.setDescription("Manage localization.")
.setSince("4.4");
indexAction.define(l10n);
l10n.done();
}
}
| 1,337 | 31.634146 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/LivenessAction.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.platform.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.server.exceptions.ForbiddenException;
import org.sonar.server.user.SystemPasscode;
import org.sonar.server.user.UserSession;
public class LivenessAction implements SystemWsAction {
private final LivenessActionSupport livenessActionSupport;
private final SystemPasscode systemPasscode;
private final UserSession userSession;
public LivenessAction(LivenessActionSupport livenessActionSupport, SystemPasscode systemPasscode, UserSession userSession) {
this.livenessActionSupport = livenessActionSupport;
this.systemPasscode = systemPasscode;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController controller) {
livenessActionSupport.define(controller, this);
}
@Override
public void handle(Request request, Response response) throws Exception {
if (!systemPasscode.isValid(request) && !isSystemAdmin()) {
throw new ForbiddenException("Insufficient privileges");
}
livenessActionSupport.checkliveness(response);
}
private boolean isSystemAdmin() {
return userSession.isSystemAdministrator();
}
}
| 2,119 | 34.932203 | 126 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/LivenessActionSupport.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.platform.ws;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
public class LivenessActionSupport {
private final LivenessChecker livenessChecker;
public LivenessActionSupport(LivenessChecker livenessChecker) {
this.livenessChecker = livenessChecker;
}
void define(WebService.NewController controller, SystemWsAction handler) {
controller.createAction("liveness")
.setDescription("Provide liveness of SonarQube, meant to be used for a liveness probe on Kubernetes" +
"<p>Require 'Administer System' permission or authentication with passcode</p>" +
"<p>When SonarQube is fully started, liveness check for database connectivity, Compute Engine status," +
" and, except for DataCenter Edition, if ElasticSearch is Green or Yellow</p>"+
"<p>When SonarQube is on Safe Mode (for example when a database migration is running), liveness check only for database connectivity</p>"+
"<p> " +
" <ul>" +
" <li>HTTP 204: this SonarQube node is alive</li>" +
" <li>Any other HTTP code: this SonarQube node is not alive, and should be reschedule</li>" +
" </ul>" +
"</p>")
.setSince("9.1")
.setInternal(true)
.setHandler(handler);
}
void checkliveness(Response response) {
if (livenessChecker.liveness()) {
response.noContent();
} else {
throw new IllegalStateException("Liveness check failed");
}
}
}
| 2,346 | 38.116667 | 146 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/LivenessChecker.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.platform.ws;
public interface LivenessChecker {
boolean liveness();
}
| 941 | 36.68 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/LivenessCheckerImpl.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.platform.ws;
import javax.annotation.Nullable;
import org.sonar.server.health.CeStatusNodeCheck;
import org.sonar.server.health.DbConnectionNodeCheck;
import org.sonar.server.health.EsStatusNodeCheck;
import org.sonar.server.health.Health;
import org.sonar.server.health.WebServerStatusNodeCheck;
public class LivenessCheckerImpl implements LivenessChecker {
private final DbConnectionNodeCheck dbConnectionNodeCheck;
private final CeStatusNodeCheck ceStatusNodeCheck;
@Nullable
private final EsStatusNodeCheck esStatusNodeCheck;
private final WebServerStatusNodeCheck webServerStatusNodeCheck;
public LivenessCheckerImpl(DbConnectionNodeCheck dbConnectionNodeCheck,
WebServerStatusNodeCheck webServerStatusNodeCheck, CeStatusNodeCheck ceStatusNodeCheck, @Nullable EsStatusNodeCheck esStatusNodeCheck) {
this.dbConnectionNodeCheck = dbConnectionNodeCheck;
this.webServerStatusNodeCheck = webServerStatusNodeCheck;
this.ceStatusNodeCheck = ceStatusNodeCheck;
this.esStatusNodeCheck = esStatusNodeCheck;
}
public boolean liveness() {
if (!Health.Status.GREEN.equals(dbConnectionNodeCheck.check().getStatus())) {
return false;
}
if (!Health.Status.GREEN.equals(webServerStatusNodeCheck.check().getStatus())) {
return false;
}
if (!Health.Status.GREEN.equals(ceStatusNodeCheck.check().getStatus())) {
return false;
}
if (esStatusNodeCheck != null && Health.Status.RED.equals(esStatusNodeCheck.check().getStatus())) {
return false;
}
return true;
}
}
| 2,422 | 35.712121 | 140 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/LogsAction.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.platform.ws;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.commons.io.FileUtils;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.process.ProcessId;
import org.sonar.server.log.ServerLogging;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.MediaTypes;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.toList;
public class LogsAction implements SystemWsAction {
private static final String PROCESS_PROPERTY = "process";
private static final String ACCESS_LOG = "access";
private final UserSession userSession;
private final ServerLogging serverLogging;
public LogsAction(UserSession userSession, ServerLogging serverLogging) {
this.userSession = userSession;
this.serverLogging = serverLogging;
}
@Override
public void define(WebService.NewController controller) {
var values = stream(ProcessId.values()).map(ProcessId::getKey).collect(toList());
values.add(ACCESS_LOG);
values.sort(String::compareTo);
WebService.NewAction action = controller.createAction("logs")
.setDescription("Get system logs in plain-text format. Requires system administration permission.")
.setResponseExample(getClass().getResource("logs-example.log"))
.setSince("5.2")
.setHandler(this);
action
.createParam(PROCESS_PROPERTY)
.setPossibleValues(values)
.setDefaultValue(ProcessId.APP.getKey())
.setSince("6.2")
.setDescription("Process to get logs from");
}
@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
userSession.checkIsSystemAdministrator();
String processKey = wsRequest.mandatoryParam(PROCESS_PROPERTY);
String filePrefix = ACCESS_LOG.equals(processKey) ? ACCESS_LOG : ProcessId.fromKey(processKey).getLogFilenamePrefix();
File logsDir = serverLogging.getLogsDir();
try (Stream<Path> stream = Files.list(Paths.get(logsDir.getPath()))) {
Optional<Path> path = stream
.filter(p -> p.getFileName().toString().contains(filePrefix)
&& p.getFileName().toString().endsWith(".log"))
.max(Comparator.comparing(Path::toString));
if (!path.isPresent()) {
wsResponse.stream().setStatus(HttpURLConnection.HTTP_NOT_FOUND);
return;
}
File file = new File(logsDir, path.get().getFileName().toString());
// filenames are defined in the enum LogProcess. Still to prevent any vulnerability,
// path is double-checked to prevent returning any file present on the file system.
if (file.exists() && file.getParentFile().equals(logsDir)) {
wsResponse.stream().setMediaType(MediaTypes.TXT);
FileUtils.copyFile(file, wsResponse.stream().output());
} else {
wsResponse.stream().setStatus(HttpURLConnection.HTTP_NOT_FOUND);
}
} catch (IOException e) {
throw new RuntimeException("Could not fetch logs", e);
}
}
}
| 4,123 | 36.153153 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/MigrateDbAction.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.platform.ws;
import com.google.common.io.Resources;
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.utils.text.JsonWriter;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.version.DatabaseVersion;
import org.sonar.server.platform.db.migration.DatabaseMigration;
import org.sonar.server.platform.db.migration.DatabaseMigrationState;
import static com.google.common.base.Preconditions.checkState;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.NO_CONNECTION_TO_DB;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.UNSUPPORTED_DATABASE_MIGRATION_STATUS;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.statusDescription;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.write;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.writeJustStartedResponse;
import static org.sonar.server.platform.ws.DbMigrationJsonWriter.writeNotSupportedResponse;
/**
* Implementation of the {@code migrate_db} action for the System WebService.
*/
public class MigrateDbAction implements SystemWsAction {
private final DatabaseVersion databaseVersion;
private final DatabaseMigrationState migrationState;
private final DatabaseMigration databaseMigration;
private final Database database;
public MigrateDbAction(DatabaseVersion databaseVersion, Database database,
DatabaseMigrationState migrationState, DatabaseMigration databaseMigration) {
this.databaseVersion = databaseVersion;
this.database = database;
this.migrationState = migrationState;
this.databaseMigration = databaseMigration;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("migrate_db")
.setDescription("Migrate the database to match the current version of SonarQube." +
"<br/>" +
"Sending a POST request to this URL starts the DB migration. " +
"It is strongly advised to <strong>make a database backup</strong> before invoking this WS." +
"<br/>" +
statusDescription())
.setSince("5.2")
.setPost(true)
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "example-migrate_db.json"));
}
@Override
public void handle(Request request, Response response) throws Exception {
Optional<Long> currentVersion = databaseVersion.getVersion();
checkState(currentVersion.isPresent(), NO_CONNECTION_TO_DB);
try (JsonWriter json = response.newJsonWriter()) {
DatabaseVersion.Status status = databaseVersion.getStatus();
if (status == DatabaseVersion.Status.UP_TO_DATE || status == DatabaseVersion.Status.REQUIRES_DOWNGRADE) {
write(json, migrationState);
} else if (!database.getDialect().supportsMigration()) {
writeNotSupportedResponse(json);
} else {
switch (migrationState.getStatus()) {
case RUNNING, FAILED, SUCCEEDED:
write(json, migrationState);
break;
case NONE:
databaseMigration.startIt();
writeJustStartedResponse(json, migrationState);
break;
default:
throw new IllegalArgumentException(UNSUPPORTED_DATABASE_MIGRATION_STATUS);
}
}
}
}
}
| 4,259 | 41.178218 | 111 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/PingAction.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.platform.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.apache.commons.io.IOUtils.write;
public class PingAction implements SystemWsAction {
@Override
public void define(WebService.NewController controller) {
controller.createAction("ping")
.setDescription("Answers \"pong\" as plain-text")
.setSince("6.3")
.setResponseExample(getClass().getResource("ping-example.txt"))
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
response.stream().setMediaType("text/plain");
write("pong", response.stream().output(), UTF_8);
}
}
| 1,651 | 35.711111 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/RestartAction.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.platform.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.server.app.ProcessCommandWrapper;
import org.sonar.server.app.RestartFlagHolder;
import org.sonar.server.platform.NodeInformation;
import org.sonar.server.user.UserSession;
/**
* Implementation of the {@code restart} action for the System WebService.
*/
public class RestartAction implements SystemWsAction {
private static final Logger LOGGER = LoggerFactory.getLogger(RestartAction.class);
private final UserSession userSession;
private final ProcessCommandWrapper processCommandWrapper;
private final RestartFlagHolder restartFlagHolder;
private final NodeInformation nodeInformation;
public RestartAction(UserSession userSession, ProcessCommandWrapper processCommandWrapper, RestartFlagHolder restartFlagHolder,
NodeInformation nodeInformation) {
this.userSession = userSession;
this.processCommandWrapper = processCommandWrapper;
this.restartFlagHolder = restartFlagHolder;
this.nodeInformation = nodeInformation;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("restart")
.setDescription("Restarts server. Requires 'Administer System' permission. Performs a full restart of the Web, Search and Compute Engine Servers processes."
+ " Does not reload sonar.properties.")
.setSince("4.3")
.setPost(true)
.setHandler(this);
}
@Override
public void handle(Request request, Response response) {
if (!nodeInformation.isStandalone()) {
throw new IllegalArgumentException("Restart not allowed for cluster nodes");
}
userSession.checkIsSystemAdministrator();
LOGGER.info("SonarQube restart requested by {}", userSession.getLogin());
restartFlagHolder.set();
processCommandWrapper.requestSQRestart();
}
}
| 2,850 | 36.513158 | 162 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SafeModeHealthAction.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.platform.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.server.exceptions.ForbiddenException;
import org.sonar.server.user.SystemPasscode;
import org.sonar.server.ws.WsUtils;
public class SafeModeHealthAction implements SystemWsAction {
private final HealthActionSupport support;
private final SystemPasscode systemPasscode;
public SafeModeHealthAction(HealthActionSupport support, SystemPasscode systemPasscode) {
this.support = support;
this.systemPasscode = systemPasscode;
}
@Override
public void define(WebService.NewController controller) {
support.define(controller, this);
}
@Override
public void handle(Request request, Response response) throws Exception {
if (!systemPasscode.isValid(request)) {
throw new ForbiddenException("Insufficient privileges");
}
WsUtils.writeProtobuf(support.checkNodeHealth(), request, response);
}
}
| 1,861 | 34.807692 | 91 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SafeModeHealthCheckerModule.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.platform.ws;
import org.sonar.core.platform.Module;
import org.sonar.server.health.DbConnectionNodeCheck;
import org.sonar.server.health.EsStatusNodeCheck;
import org.sonar.server.health.HealthCheckerImpl;
import org.sonar.server.health.WebServerSafemodeNodeCheck;
public class SafeModeHealthCheckerModule extends Module {
@Override
protected void configureModule() {
add(
// NodeHealthCheck implementations
WebServerSafemodeNodeCheck.class,
DbConnectionNodeCheck.class,
EsStatusNodeCheck.class,
HealthCheckerImpl.class);
}
}
| 1,437 | 34.95 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SafeModeLivenessAction.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.platform.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.server.exceptions.ForbiddenException;
import org.sonar.server.user.SystemPasscode;
public class SafeModeLivenessAction implements SystemWsAction {
private final LivenessActionSupport livenessActionSupport;
private final SystemPasscode systemPasscode;
public SafeModeLivenessAction(LivenessActionSupport livenessActionSupport, SystemPasscode systemPasscode) {
this.livenessActionSupport = livenessActionSupport;
this.systemPasscode = systemPasscode;
}
@Override
public void define(WebService.NewController controller) {
livenessActionSupport.define(controller, this);
}
@Override
public void handle(Request request, Response response) throws Exception {
if (!systemPasscode.isValid(request)) {
throw new ForbiddenException("Insufficient privileges");
}
livenessActionSupport.checkliveness(response);
}
}
| 1,881 | 35.901961 | 109 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SafeModeLivenessCheckerImpl.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.platform.ws;
import org.sonar.server.health.DbConnectionNodeCheck;
import org.sonar.server.health.Health;
public class SafeModeLivenessCheckerImpl implements LivenessChecker {
private final DbConnectionNodeCheck dbConnectionNodeCheck;
public SafeModeLivenessCheckerImpl(DbConnectionNodeCheck dbConnectionNodeCheck) {
this.dbConnectionNodeCheck = dbConnectionNodeCheck;
}
public boolean liveness() {
return Health.Status.GREEN.equals(dbConnectionNodeCheck.check().getStatus());
}
}
| 1,372 | 36.108108 | 83 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SafeModeMonitoringMetricAction.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.platform.ws;
import com.google.common.net.HttpHeaders;
import io.prometheus.client.CollectorRegistry;
import io.prometheus.client.Gauge;
import io.prometheus.client.exporter.common.TextFormat;
import java.io.OutputStreamWriter;
import java.io.Writer;
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.ForbiddenException;
import org.sonar.server.monitoring.MonitoringWsAction;
import org.sonar.server.user.BearerPasscode;
import org.sonar.server.user.SystemPasscode;
import static java.nio.charset.StandardCharsets.UTF_8;
public class SafeModeMonitoringMetricAction implements MonitoringWsAction {
protected static final Gauge isWebUpGauge = Gauge.build().name("sonarqube_health_web_status")
.help("Tells whether Web process is up or down. 1 for up, 0 for down").register();
private final SystemPasscode systemPasscode;
private final BearerPasscode bearerPasscode;
public SafeModeMonitoringMetricAction(SystemPasscode systemPasscode, BearerPasscode bearerPasscode) {
this.systemPasscode = systemPasscode;
this.bearerPasscode = bearerPasscode;
}
@Override
public void define(WebService.NewController context) {
context.createAction("metrics").setHandler(this);
isWebUpGauge.set(1D);
}
@Override
public void handle(Request request, Response response) throws Exception {
if (!systemPasscode.isValid(request) && !isSystemAdmin() && !bearerPasscode.isValid(request)) {
throw new ForbiddenException("Insufficient privileges");
}
String requestContentType = request.getHeaders().get("accept");
String contentType = TextFormat.chooseContentType(requestContentType);
response.setHeader(HttpHeaders.CONTENT_TYPE, contentType);
response.stream().setStatus(200);
try (Writer writer = new OutputStreamWriter(response.stream().output(), UTF_8)) {
TextFormat.writeFormat(contentType, writer, CollectorRegistry.defaultRegistry.metricFamilySamples());
writer.flush();
}
}
public boolean isSystemAdmin() {
// No authenticated user in safe mode
return false;
}
}
| 3,038 | 36.060976 | 107 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SafemodeSystemWsModule.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.platform.ws;
import org.sonar.core.platform.Module;
import org.sonar.server.monitoring.MonitoringWs;
import org.sonar.server.user.BearerPasscode;
public class SafemodeSystemWsModule extends Module {
@Override
protected void configureModule() {
add(
StatusAction.class,
MigrateDbAction.class,
DbMigrationStatusAction.class,
HealthActionSupport.class,
SafeModeHealthAction.class,
SafeModeLivenessCheckerImpl.class,
LivenessActionSupport.class,
SafeModeLivenessAction.class,
MonitoringWs.class,
BearerPasscode.class,
SafeModeMonitoringMetricAction.class,
SystemWs.class);
}
}
| 1,528 | 31.531915 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/ServerWs.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.platform.ws;
import com.google.common.io.Resources;
import org.apache.commons.io.IOUtils;
import org.sonar.api.platform.Server;
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.sonarqube.ws.MediaTypes;
import static java.nio.charset.StandardCharsets.UTF_8;
public class ServerWs implements WebService, RequestHandler {
private final Server server;
public ServerWs(Server server) {
this.server = server;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/server");
controller.createAction("version")
.setDescription("Version of SonarQube in plain text")
.setSince("2.10")
.setResponseExample(Resources.getResource(this.getClass(), "example-server-version.txt"))
.setHandler(this);
controller.done();
}
@Override
public void handle(Request request, Response response) throws Exception {
response.stream().setMediaType(MediaTypes.TXT);
IOUtils.write(server.getVersion(), response.stream().output(), UTF_8);
}
}
| 2,040 | 33.016667 | 95 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/StatusAction.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.platform.ws;
import com.google.common.io.Resources;
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.server.app.RestartFlagHolder;
import org.sonar.server.platform.Platform;
import org.sonar.server.platform.db.migration.DatabaseMigrationState;
import org.sonar.server.ws.WsUtils;
import org.sonarqube.ws.System;
import static java.util.Optional.ofNullable;
/**
* Implementation of the {@code status} action for the System WebService.
*/
public class StatusAction implements SystemWsAction {
private final Server server;
private final DatabaseMigrationState migrationState;
private final Platform platform;
private final RestartFlagHolder restartFlagHolder;
public StatusAction(Server server, DatabaseMigrationState migrationState,
Platform platform, RestartFlagHolder restartFlagHolder) {
this.server = server;
this.migrationState = migrationState;
this.platform = platform;
this.restartFlagHolder = restartFlagHolder;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("status")
.setDescription("Get state information about SonarQube." +
"<p>status: the running status" +
" <ul>" +
" <li>STARTING: SonarQube Web Server is up and serving some Web Services (eg. api/system/status) " +
"but initialization is still ongoing</li>" +
" <li>UP: SonarQube instance is up and running</li>" +
" <li>DOWN: SonarQube instance is up but not running because " +
"migration has failed (refer to WS /api/system/migrate_db for details) or some other reason (check logs).</li>" +
" <li>RESTARTING: SonarQube instance is still up but a restart has been requested " +
"(refer to WS /api/system/restart for details).</li>" +
" <li>DB_MIGRATION_NEEDED: database migration is required. DB migration can be started using WS /api/system/migrate_db.</li>" +
" <li>DB_MIGRATION_RUNNING: DB migration is running (refer to WS /api/system/migrate_db for details)</li>" +
" </ul>" +
"</p>")
.setSince("5.2")
.setResponseExample(Resources.getResource(this.getClass(), "example-status.json"))
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
System.StatusResponse.Builder protobuf = System.StatusResponse.newBuilder();
ofNullable(server.getId()).ifPresent(protobuf::setId);
ofNullable(server.getVersion()).ifPresent(protobuf::setVersion);
protobuf.setStatus(computeStatus());
WsUtils.writeProtobuf(protobuf.build(), request, response);
}
private System.Status computeStatus() {
Platform.Status platformStatus = platform.status();
switch (platformStatus) {
case BOOTING:
// can not happen since there can not even exist an instance of the current class
// unless the Platform's status is UP/SAFEMODE/STARTING
return System.Status.DOWN;
case UP:
return restartFlagHolder.isRestarting() ? System.Status.RESTARTING : System.Status.UP;
case STARTING:
return computeStatusInStarting();
case SAFEMODE:
return computeStatusInSafemode();
default:
throw new IllegalArgumentException("Unsupported Platform.Status " + platformStatus);
}
}
private System.Status computeStatusInStarting() {
DatabaseMigrationState.Status databaseMigrationStatus = migrationState.getStatus();
switch (databaseMigrationStatus) {
case NONE:
return System.Status.STARTING;
case RUNNING:
return System.Status.DB_MIGRATION_RUNNING;
case FAILED:
return System.Status.DOWN;
case SUCCEEDED:
// DB migration can be finished while we haven't yet finished SQ's initialization
return System.Status.STARTING;
default:
throw new IllegalArgumentException("Unsupported DatabaseMigration.Status " + databaseMigrationStatus);
}
}
private System.Status computeStatusInSafemode() {
DatabaseMigrationState.Status databaseMigrationStatus = migrationState.getStatus();
switch (databaseMigrationStatus) {
case NONE:
return System.Status.DB_MIGRATION_NEEDED;
case RUNNING:
return System.Status.DB_MIGRATION_RUNNING;
case FAILED:
return System.Status.DOWN;
case SUCCEEDED:
return System.Status.STARTING;
default:
throw new IllegalArgumentException("Unsupported DatabaseMigration.Status " + databaseMigrationStatus);
}
}
}
| 5,538 | 39.727941 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SystemWs.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.platform.ws;
import org.sonar.api.server.ws.WebService;
public class SystemWs implements WebService {
private final SystemWsAction[] actions;
public SystemWs(SystemWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/system")
.setDescription("Get system details, and perform some management actions, such as restarting, and initiating a database migration (as part of a system upgrade).");
for (SystemWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,503 | 32.422222 | 169 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SystemWsAction.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.platform.ws;
import org.sonar.server.ws.WsAction;
public interface SystemWsAction extends WsAction {
// Marker interface
}
| 996 | 34.607143 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/SystemWsModule.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.platform.ws;
import org.sonar.core.platform.Module;
public class SystemWsModule extends Module {
@Override
protected void configureModule() {
add(
ChangeLogLevelAction.class,
DbMigrationStatusAction.class,
HealthActionSupport.class,
HealthAction.class,
LivenessCheckerImpl.class,
LivenessActionSupport.class,
LivenessAction.class,
InfoAction.class,
LogsAction.class,
MigrateDbAction.class,
PingAction.class,
RestartAction.class,
StatusAction.class,
UpgradesAction.class,
SystemWs.class
);
}
}
| 1,471 | 28.44 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/ws/UpgradesAction.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.platform.ws;
import com.google.common.io.Resources;
import java.util.List;
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.utils.text.JsonWriter;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.ui.VersionFormatter;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.Release;
import org.sonar.updatecenter.common.SonarUpdate;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonar.updatecenter.common.Version;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.sonar.server.plugins.edition.EditionBundledPlugins.isEditionBundled;
/**
* Implementation of the {@code upgrades} action for the System WebService.
*/
public class UpgradesAction implements SystemWsAction {
private static final boolean DO_NOT_FORCE_REFRESH = false;
private static final String ARRAY_UPGRADES = "upgrades";
private static final String PROPERTY_UPDATE_CENTER_LTS = "latestLTS";
private static final String PROPERTY_UPDATE_CENTER_REFRESH = "updateCenterRefresh";
private static final String PROPERTY_VERSION = "version";
private static final String PROPERTY_DESCRIPTION = "description";
private static final String PROPERTY_RELEASE_DATE = "releaseDate";
private static final String PROPERTY_CHANGE_LOG_URL = "changeLogUrl";
private static final String PROPERTY_COMMUNITY_DOWNLOAD_URL = "downloadUrl";
private static final String PROPERTY_DEVELOPER_DOWNLOAD_URL = "downloadDeveloperUrl";
private static final String PROPERTY_ENTERPRISE_DOWNLOAD_URL = "downloadEnterpriseUrl";
private static final String PROPERTY_DATACENTER_DOWNLOAD_URL = "downloadDatacenterUrl";
private static final String OBJECT_PLUGINS = "plugins";
private static final String ARRAY_REQUIRE_UPDATE = "requireUpdate";
private static final String ARRAY_INCOMPATIBLE = "incompatible";
private static final String PROPERTY_KEY = "key";
private static final String PROPERTY_NAME = "name";
private static final String PROPERTY_LICENSE = "license";
private static final String PROPERTY_CATEGORY = "category";
private static final String PROPERTY_ORGANIZATION_NAME = "organizationName";
private static final String PROPERTY_ORGANIZATION_URL = "organizationUrl";
private static final String PROPERTY_HOMEPAGE_URL = "homepageUrl";
private static final String PROPERTY_ISSUE_TRACKER_URL = "issueTrackerUrl";
private static final String PROPERTY_EDITION_BUNDLED = "editionBundled";
private static final String PROPERTY_TERMS_AND_CONDITIONS_URL = "termsAndConditionsUrl";
private final UpdateCenterMatrixFactory updateCenterFactory;
public UpgradesAction(UpdateCenterMatrixFactory updateCenterFactory) {
this.updateCenterFactory = updateCenterFactory;
}
private static void writeMetadata(JsonWriter jsonWriter, Release release) {
jsonWriter.prop(PROPERTY_VERSION, VersionFormatter.format(release.getVersion().getName()));
jsonWriter.prop(PROPERTY_DESCRIPTION, release.getDescription());
jsonWriter.propDate(PROPERTY_RELEASE_DATE, release.getDate());
jsonWriter.prop(PROPERTY_CHANGE_LOG_URL, release.getChangelogUrl());
jsonWriter.prop(PROPERTY_COMMUNITY_DOWNLOAD_URL, release.getDownloadUrl(Release.Edition.COMMUNITY));
jsonWriter.prop(PROPERTY_DEVELOPER_DOWNLOAD_URL, release.getDownloadUrl(Release.Edition.DEVELOPER));
jsonWriter.prop(PROPERTY_ENTERPRISE_DOWNLOAD_URL, release.getDownloadUrl(Release.Edition.ENTERPRISE));
jsonWriter.prop(PROPERTY_DATACENTER_DOWNLOAD_URL, release.getDownloadUrl(Release.Edition.DATACENTER));
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("upgrades")
.setDescription("Lists available upgrades for the SonarQube instance (if any) and for each one, " +
"lists incompatible plugins and plugins requiring upgrade." +
"<br/>" +
"Plugin information is retrieved from Update Center. Date and time at which Update Center was last refreshed " +
"is provided in the response.")
.setSince("5.2")
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "example-upgrades_plugins.json"));
}
@Override
public void handle(Request request, Response response) throws Exception {
try (JsonWriter jsonWriter = response.newJsonWriter()) {
jsonWriter.setSerializeEmptys(false);
writeResponse(jsonWriter);
}
}
private void writeResponse(JsonWriter jsonWriter) {
jsonWriter.beginObject();
Optional<UpdateCenter> updateCenter = updateCenterFactory.getUpdateCenter(DO_NOT_FORCE_REFRESH);
writeUpgrades(jsonWriter, updateCenter);
if (updateCenter.isPresent()) {
Release ltsRelease = updateCenter.get().getSonar().getLtsRelease();
if (ltsRelease != null) {
Version ltsVersion = ltsRelease.getVersion();
String latestLTS = String.format("%s.%s", ltsVersion.getMajor(), ltsVersion.getMinor());
jsonWriter.prop(PROPERTY_UPDATE_CENTER_LTS, latestLTS);
}
jsonWriter.propDateTime(PROPERTY_UPDATE_CENTER_REFRESH, updateCenter.get().getDate());
}
jsonWriter.endObject();
}
private static void writeUpgrades(JsonWriter jsonWriter, Optional<UpdateCenter> updateCenter) {
jsonWriter.name(ARRAY_UPGRADES).beginArray();
if (updateCenter.isPresent()) {
for (SonarUpdate sonarUpdate : updateCenter.get().findSonarUpdates()) {
writeUpgrade(jsonWriter, sonarUpdate);
}
}
jsonWriter.endArray();
}
private static void writeUpgrade(JsonWriter jsonWriter, SonarUpdate sonarUpdate) {
jsonWriter.beginObject();
writeMetadata(jsonWriter, sonarUpdate.getRelease());
writePlugins(jsonWriter, sonarUpdate);
jsonWriter.endObject();
}
private static void writePlugins(JsonWriter jsonWriter, SonarUpdate sonarUpdate) {
jsonWriter.name(OBJECT_PLUGINS).beginObject();
writePluginsToUpdate(jsonWriter, sonarUpdate.getPluginsToUpgrade());
writeIncompatiblePlugins(jsonWriter, sonarUpdate.getIncompatiblePlugins());
jsonWriter.endObject();
}
private static void writePluginsToUpdate(JsonWriter jsonWriter, List<Release> pluginsToUpgrade) {
jsonWriter.name(ARRAY_REQUIRE_UPDATE).beginArray();
for (Release release : pluginsToUpgrade) {
jsonWriter.beginObject();
writePlugin(jsonWriter, (Plugin) release.getArtifact());
String version = isNotBlank(release.getDisplayVersion()) ? release.getDisplayVersion() : release.getVersion().toString();
jsonWriter.prop(PROPERTY_VERSION, version);
jsonWriter.endObject();
}
jsonWriter.endArray();
}
private static void writeIncompatiblePlugins(JsonWriter jsonWriter, List<Plugin> incompatiblePlugins) {
jsonWriter.name(ARRAY_INCOMPATIBLE).beginArray();
for (Plugin incompatiblePlugin : incompatiblePlugins) {
jsonWriter.beginObject();
writePlugin(jsonWriter, incompatiblePlugin);
jsonWriter.endObject();
}
jsonWriter.endArray();
}
public static void writePlugin(JsonWriter jsonWriter, Plugin plugin) {
jsonWriter.prop(PROPERTY_KEY, plugin.getKey());
jsonWriter.prop(PROPERTY_NAME, plugin.getName());
jsonWriter.prop(PROPERTY_CATEGORY, plugin.getCategory());
jsonWriter.prop(PROPERTY_DESCRIPTION, plugin.getDescription());
jsonWriter.prop(PROPERTY_LICENSE, plugin.getLicense());
jsonWriter.prop(PROPERTY_TERMS_AND_CONDITIONS_URL, plugin.getTermsConditionsUrl());
jsonWriter.prop(PROPERTY_ORGANIZATION_NAME, plugin.getOrganization());
jsonWriter.prop(PROPERTY_ORGANIZATION_URL, plugin.getOrganizationUrl());
jsonWriter.prop(PROPERTY_HOMEPAGE_URL, plugin.getHomepageUrl());
jsonWriter.prop(PROPERTY_ISSUE_TRACKER_URL, plugin.getIssueTrackerUrl());
jsonWriter.prop(PROPERTY_EDITION_BUNDLED, isEditionBundled(plugin));
}
}
| 8,840 | 42.985075 | 127 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/platform/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.platform.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 39.375 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/AvailableAction.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.plugins.ws;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
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.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.user.UserSession;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonarqube.ws.Plugins.AvailablePlugin;
import org.sonarqube.ws.Plugins.AvailablePluginsWsResponse;
import org.sonarqube.ws.Plugins.AvailablePluginsWsResponse.Builder;
import org.sonarqube.ws.Plugins.Update;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.server.plugins.edition.EditionBundledPlugins.isEditionBundled;
import static org.sonar.server.plugins.ws.PluginWSCommons.NAME_KEY_PLUGIN_UPDATE_ORDERING;
import static org.sonar.server.plugins.ws.PluginWSCommons.buildRelease;
import static org.sonar.server.plugins.ws.PluginWSCommons.buildRequires;
import static org.sonar.server.plugins.ws.PluginWSCommons.convertUpdateCenterStatus;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class AvailableAction implements PluginsWsAction {
private static final boolean DO_NOT_FORCE_REFRESH = false;
private final UserSession userSession;
private final UpdateCenterMatrixFactory updateCenterFactory;
public AvailableAction(UserSession userSession, UpdateCenterMatrixFactory updateCenterFactory) {
this.userSession = userSession;
this.updateCenterFactory = updateCenterFactory;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("available")
.setDescription("Get the list of all the plugins available for installation on the SonarQube instance, sorted by plugin name." +
"<br/>" +
"Plugin information is retrieved from Update Center. Date and time at which Update Center was last refreshed is provided in the response." +
"<br/>" +
"Update status values are: " +
"<ul>" +
"<li>COMPATIBLE: plugin is compatible with current SonarQube instance.</li>" +
"<li>INCOMPATIBLE: plugin is not compatible with current SonarQube instance.</li>" +
"<li>REQUIRES_SYSTEM_UPGRADE: plugin requires SonarQube to be upgraded before being installed.</li>" +
"<li>DEPS_REQUIRE_SYSTEM_UPGRADE: at least one plugin on which the plugin is dependent requires SonarQube to be upgraded.</li>" +
"</ul>" +
"Require 'Administer System' permission.")
.setSince("5.2")
.setHandler(this)
.setResponseExample(this.getClass().getResource("example-available_plugins.json"));
}
@Override
public void handle(Request request, Response response) {
userSession.checkIsSystemAdministrator();
Optional<UpdateCenter> updateCenter = updateCenterFactory.getUpdateCenter(DO_NOT_FORCE_REFRESH);
Collection<AvailablePlugin> plugins = updateCenter.isPresent() ? getPlugins(updateCenter.get()) : Collections.emptyList();
Builder responseBuilder = AvailablePluginsWsResponse.newBuilder().addAllPlugins(plugins);
updateCenter.ifPresent(u -> responseBuilder.setUpdateCenterRefresh(formatDateTime(u.getDate().getTime())));
writeProtobuf(responseBuilder.build(), request, response);
}
private static List<AvailablePlugin> getPlugins(UpdateCenter updateCenter) {
return retrieveAvailablePlugins(updateCenter)
.stream()
.map(pluginUpdate -> {
Plugin plugin = pluginUpdate.getPlugin();
AvailablePlugin.Builder builder = AvailablePlugin.newBuilder()
.setKey(plugin.getKey())
.setEditionBundled(isEditionBundled(plugin))
.setRelease(buildRelease(pluginUpdate.getRelease()))
.setUpdate(buildUpdate(pluginUpdate));
ofNullable(plugin.getName()).ifPresent(builder::setName);
ofNullable(plugin.getCategory()).ifPresent(builder::setCategory);
ofNullable(plugin.getDescription()).ifPresent(builder::setDescription);
ofNullable(plugin.getLicense()).ifPresent(builder::setLicense);
ofNullable(plugin.getTermsConditionsUrl()).ifPresent(builder::setTermsAndConditionsUrl);
ofNullable(plugin.getOrganization()).ifPresent(builder::setOrganizationName);
ofNullable(plugin.getOrganizationUrl()).ifPresent(builder::setOrganizationUrl);
ofNullable(plugin.getIssueTrackerUrl()).ifPresent(builder::setIssueTrackerUrl);
ofNullable(plugin.getHomepageUrl()).ifPresent(builder::setHomepageUrl);
return builder.build();
}).toList();
}
private static Update buildUpdate(PluginUpdate pluginUpdate) {
return Update.newBuilder()
.setStatus(convertUpdateCenterStatus(pluginUpdate.getStatus()))
.addAllRequires(buildRequires(pluginUpdate))
.build();
}
private static Collection<PluginUpdate> retrieveAvailablePlugins(UpdateCenter updateCenter) {
return updateCenter.findAvailablePlugins().stream().sorted(NAME_KEY_PLUGIN_UPDATE_ORDERING).toList();
}
}
| 6,050 | 46.645669 | 148 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/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.plugins.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.server.plugins.PluginDownloader;
import org.sonar.server.plugins.PluginUninstaller;
import org.sonar.server.user.UserSession;
public class CancelAllAction implements PluginsWsAction {
private final PluginDownloader pluginDownloader;
private final PluginUninstaller pluginUninstaller;
private final UserSession userSession;
public CancelAllAction(PluginDownloader pluginDownloader, PluginUninstaller pluginUninstaller, UserSession userSession) {
this.pluginDownloader = pluginDownloader;
this.pluginUninstaller = pluginUninstaller;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("cancel_all")
.setPost(true)
.setSince("5.2")
.setDescription("Cancels any operation pending on any plugin (install, update or uninstall)" +
"<br/>" +
"Requires user to be authenticated with Administer System permissions")
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkIsSystemAdministrator();
pluginDownloader.cancelDownloads();
pluginUninstaller.cancelUninstalls();
response.noContent();
}
}
| 2,250 | 35.306452 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/DownloadAction.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.plugins.ws;
import java.io.InputStream;
import java.util.Optional;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
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.server.exceptions.NotFoundException;
import org.sonar.server.plugins.PluginFilesAndMd5.FileAndMd5;
import org.sonar.server.plugins.ServerPlugin;
import org.sonar.server.plugins.ServerPluginRepository;
public class DownloadAction implements PluginsWsAction {
private static final String PLUGIN_PARAM = "plugin";
private final ServerPluginRepository pluginRepository;
public DownloadAction(ServerPluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("download")
.setSince("7.2")
.setDescription("Download plugin JAR, for usage by scanner engine")
.setInternal(true)
.setResponseExample(getClass().getResource("example-download.json"))
.setHandler(this);
action.createParam(PLUGIN_PARAM)
.setRequired(true)
.setDescription("The key identifying the plugin to download")
.setExampleValue("cobol");
action.setChangelog(new Change("9.8", "Parameter 'acceptCompressions' removed"));
}
@Override
public void handle(Request request, Response response) throws Exception {
String pluginKey = request.mandatoryParam(PLUGIN_PARAM);
Optional<ServerPlugin> file = pluginRepository.findPlugin(pluginKey);
if (!file.isPresent()) {
throw new NotFoundException("Plugin " + pluginKey + " not found");
}
FileAndMd5 downloadedFile;
response.stream().setMediaType("application/java-archive");
downloadedFile = file.get().getJar();
response.setHeader("Sonar-MD5", downloadedFile.getMd5());
try (InputStream input = FileUtils.openInputStream(downloadedFile.getFile())) {
IOUtils.copyLarge(input, response.stream().output());
}
}
}
| 2,995 | 35.987654 | 85 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/InstallAction.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.plugins.ws;
import java.util.Objects;
import java.util.Optional;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.extension.PluginRiskConsent;
import org.sonar.core.platform.EditionProvider.Edition;
import org.sonar.core.platform.PlatformEditionProvider;
import org.sonar.server.plugins.PluginDownloader;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.user.UserSession;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.UpdateCenter;
import static java.lang.String.format;
import static org.sonar.core.config.CorePropertyDefinitions.PLUGINS_RISK_CONSENT;
import static org.sonar.server.plugins.edition.EditionBundledPlugins.isEditionBundled;
/**
* Implementation of the {@code install} action for the Plugins WebService.
*/
public class InstallAction implements PluginsWsAction {
private static final String BR_HTML_TAG = "<br/>";
private static final String PARAM_KEY = "key";
private final UpdateCenterMatrixFactory updateCenterFactory;
private final PluginDownloader pluginDownloader;
private final UserSession userSession;
private final Configuration configuration;
private final PlatformEditionProvider editionProvider;
public InstallAction(UpdateCenterMatrixFactory updateCenterFactory, PluginDownloader pluginDownloader,
UserSession userSession, Configuration configuration,
PlatformEditionProvider editionProvider) {
this.updateCenterFactory = updateCenterFactory;
this.pluginDownloader = pluginDownloader;
this.userSession = userSession;
this.configuration = configuration;
this.editionProvider = editionProvider;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("install")
.setPost(true)
.setSince("5.2")
.setDescription("Installs the latest version of a plugin specified by its key." +
BR_HTML_TAG +
"Plugin information is retrieved from Update Center." +
BR_HTML_TAG +
"Fails if used on commercial editions or plugin risk consent has not been accepted." +
BR_HTML_TAG +
"Requires user to be authenticated with Administer System permissions")
.setHandler(this);
action.createParam(PARAM_KEY).setRequired(true)
.setDescription("The key identifying the plugin to install");
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkIsSystemAdministrator();
checkEdition();
if (!hasPluginInstallConsent()) {
throw new IllegalArgumentException("Can't install plugin without accepting firstly plugins risk consent");
}
String key = request.mandatoryParam(PARAM_KEY);
PluginUpdate pluginUpdate = findAvailablePluginByKey(key);
pluginDownloader.download(key, pluginUpdate.getRelease().getVersion());
response.noContent();
}
private void checkEdition() {
Edition edition = editionProvider.get().orElse(Edition.COMMUNITY);
if (!Edition.COMMUNITY.equals(edition)) {
throw new IllegalArgumentException("This WS is unsupported in commercial edition. Please install plugin manually.");
}
}
private boolean hasPluginInstallConsent() {
Optional<String> pluginRiskConsent = configuration.get(PLUGINS_RISK_CONSENT);
return pluginRiskConsent.filter(s -> PluginRiskConsent.valueOf(s) == PluginRiskConsent.ACCEPTED).isPresent();
}
private PluginUpdate findAvailablePluginByKey(String key) {
PluginUpdate pluginUpdate = null;
Optional<UpdateCenter> updateCenter = updateCenterFactory.getUpdateCenter(false);
if (updateCenter.isPresent()) {
pluginUpdate = updateCenter.get().findAvailablePlugins()
.stream()
.filter(Objects::nonNull)
.filter(u -> key.equals(u.getPlugin().getKey()))
.findFirst()
.orElse(null);
}
if (pluginUpdate == null) {
throw new IllegalArgumentException(
format("No plugin with key '%s' or plugin '%s' is already installed in latest version", key, key));
}
if (isEditionBundled(pluginUpdate.getPlugin())) {
throw new IllegalArgumentException(format(
"SonarSource commercial plugin with key '%s' can only be installed as part of a SonarSource edition",
pluginUpdate.getPlugin().getKey()));
}
return pluginUpdate;
}
}
| 5,386 | 38.610294 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/InstalledAction.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.plugins.ws;
import com.google.common.io.Resources;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.SortedSet;
import java.util.function.Function;
import java.util.stream.Collectors;
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.core.platform.PluginInfo;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.plugin.PluginDto;
import org.sonar.db.plugin.PluginDto.Type;
import org.sonar.core.plugin.PluginType;
import org.sonar.server.plugins.ServerPlugin;
import org.sonar.server.plugins.ServerPluginRepository;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.user.UserSession;
import org.sonar.updatecenter.common.Plugin;
import org.sonarqube.ws.Plugins.InstalledPluginsWsResponse;
import org.sonarqube.ws.Plugins.PluginDetails;
import static com.google.common.collect.ImmutableSortedSet.copyOf;
import static java.lang.String.format;
import static java.util.Collections.emptyMap;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toMap;
import static org.sonar.server.plugins.ws.PluginWSCommons.NAME_KEY_COMPARATOR;
import static org.sonar.server.plugins.ws.PluginWSCommons.buildPluginDetails;
import static org.sonar.server.plugins.ws.PluginWSCommons.compatiblePluginsByKey;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
/**
* Implementation of the {@code installed} action for the Plugins WebService.
*/
public class InstalledAction implements PluginsWsAction {
private static final String FIELD_CATEGORY = "category";
private static final String PARAM_TYPE = "type";
private final UserSession userSession;
private final ServerPluginRepository serverPluginRepository;
private final UpdateCenterMatrixFactory updateCenterMatrixFactory;
private final DbClient dbClient;
public InstalledAction(ServerPluginRepository serverPluginRepository, UserSession userSession, UpdateCenterMatrixFactory updateCenterMatrixFactory, DbClient dbClient) {
this.userSession = userSession;
this.serverPluginRepository = serverPluginRepository;
this.updateCenterMatrixFactory = updateCenterMatrixFactory;
this.dbClient = dbClient;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("installed")
.setDescription("Get the list of all the plugins installed on the SonarQube instance, sorted by plugin name.<br/>" +
"Requires authentication.")
.setSince("5.2")
.setChangelog(
new Change("9.8", "The 'documentationPath' field is deprecated"),
new Change("9.7", "Authentication check added"),
new Change("8.0", "The 'documentationPath' field is added"),
new Change("7.0", "The fields 'compressedHash' and 'compressedFilename' are added"),
new Change("6.6", "The 'filename' field is added"),
new Change("6.6", "The 'fileHash' field is added"),
new Change("6.6", "The 'sonarLintSupported' field is added"),
new Change("6.6", "The 'updatedAt' field is added"))
.setHandler(this)
.setResponseExample(Resources.getResource(this.getClass(), "example-installed_plugins.json"));
action.createFieldsParam(singleton("category"))
.setDescription(format("Comma-separated list of the additional fields to be returned in response. No additional field is returned by default. Possible values are:" +
"<ul>" +
"<li>%s - category as defined in the Update Center. A connection to the Update Center is needed</li>" +
"</ul>", FIELD_CATEGORY))
.setSince("5.6");
action.createParam(PARAM_TYPE)
.setInternal(true)
.setSince("8.5")
.setPossibleValues(Type.values())
.setDescription("Allows to filter plugins by type");
}
@Override
public void handle(Request request, Response response) throws Exception {
if (!userSession.isLoggedIn() && !userSession.hasPermission(GlobalPermission.SCAN)) {
throw insufficientPrivilegesException();
}
String typeParam = request.param(PARAM_TYPE);
SortedSet<ServerPlugin> installedPlugins = loadInstalledPlugins(typeParam);
Map<String, PluginDto> dtosByKey;
try (DbSession dbSession = dbClient.openSession(false)) {
dtosByKey = dbClient.pluginDao().selectAll(dbSession).stream().collect(toMap(PluginDto::getKee, Function.identity()));
}
List<String> additionalFields = request.paramAsStrings(WebService.Param.FIELDS);
Map<String, Plugin> updateCenterPlugins = (additionalFields == null || additionalFields.isEmpty()) ? emptyMap() : compatiblePluginsByKey(updateCenterMatrixFactory);
List<PluginDetails> pluginList = new LinkedList<>();
for (ServerPlugin installedPlugin : installedPlugins) {
PluginInfo pluginInfo = installedPlugin.getPluginInfo();
PluginDto pluginDto = dtosByKey.get(pluginInfo.getKey());
Objects.requireNonNull(pluginDto, () -> format("Plugin %s is installed but not in DB", pluginInfo.getKey()));
Plugin updateCenterPlugin = updateCenterPlugins.get(pluginInfo.getKey());
pluginList.add(buildPluginDetails(installedPlugin, pluginInfo, pluginDto, updateCenterPlugin));
}
InstalledPluginsWsResponse wsResponse = InstalledPluginsWsResponse.newBuilder()
.addAllPlugins(pluginList)
.build();
writeProtobuf(wsResponse, request, response);
}
private SortedSet<ServerPlugin> loadInstalledPlugins(@Nullable String typeParam) {
if (typeParam != null) {
return copyOf(NAME_KEY_COMPARATOR, serverPluginRepository.getPlugins().stream()
.filter(serverPlugin -> serverPlugin.getType().equals(PluginType.valueOf(typeParam)))
.collect(Collectors.toSet()));
}
return copyOf(NAME_KEY_COMPARATOR, serverPluginRepository.getPlugins());
}
}
| 7,035 | 44.688312 | 171 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/PendingAction.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.plugins.ws;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
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.core.platform.PluginInfo;
import org.sonar.server.plugins.PluginDownloader;
import org.sonar.server.plugins.PluginUninstaller;
import org.sonar.server.plugins.ServerPluginRepository;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.user.UserSession;
import org.sonar.updatecenter.common.Plugin;
import org.sonarqube.ws.Plugins.PendingPluginsWsResponse;
import org.sonarqube.ws.Plugins.PluginDetails;
import static org.sonar.server.plugins.ws.PluginWSCommons.NAME_KEY_PLUGIN_METADATA_COMPARATOR;
import static org.sonar.server.plugins.ws.PluginWSCommons.buildPluginDetails;
import static org.sonar.server.plugins.ws.PluginWSCommons.compatiblePluginsByKey;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
/**
* Implementation of the {@code pending} action for the Plugins WebService.
*/
public class PendingAction implements PluginsWsAction {
private final UserSession userSession;
private final PluginDownloader pluginDownloader;
private final ServerPluginRepository serverPluginRepository;
private final UpdateCenterMatrixFactory updateCenterMatrixFactory;
private final PluginUninstaller pluginUninstaller;
public PendingAction(UserSession userSession, PluginDownloader pluginDownloader,
ServerPluginRepository serverPluginRepository, PluginUninstaller pluginUninstaller, UpdateCenterMatrixFactory updateCenterMatrixFactory) {
this.userSession = userSession;
this.pluginDownloader = pluginDownloader;
this.serverPluginRepository = serverPluginRepository;
this.pluginUninstaller = pluginUninstaller;
this.updateCenterMatrixFactory = updateCenterMatrixFactory;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("pending")
.setDescription("Get the list of plugins which will either be installed or removed at the next startup of the SonarQube instance, sorted by plugin name.<br/>" +
"Require 'Administer System' permission.")
.setSince("5.2")
.setChangelog(
new Change("9.8", "The 'documentationPath' field is deprecated"),
new Change("8.0", "The 'documentationPath' field is added")
)
.setHandler(this)
.setResponseExample(this.getClass().getResource("example-pending_plugins.json"));
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkIsSystemAdministrator();
ImmutableMap<String, Plugin> compatiblePluginsByKey = compatiblePluginsByKey(updateCenterMatrixFactory);
PendingPluginsWsResponse.Builder buildResponse = buildResponse(compatiblePluginsByKey);
writeProtobuf(buildResponse.build(), request, response);
}
private PendingPluginsWsResponse.Builder buildResponse(ImmutableMap<String, Plugin> compatiblePluginsByKey) {
Collection<PluginInfo> uninstalledPlugins = pluginUninstaller.getUninstalledPlugins();
Collection<PluginInfo> downloadedPlugins = pluginDownloader.getDownloadedPlugins();
Collection<PluginInfo> installedPlugins = serverPluginRepository.getPluginInfos();
Set<String> installedPluginKeys = installedPlugins.stream().map(PluginInfo::getKey).collect(Collectors.toSet());
Collection<PluginInfo> newPlugins = new ArrayList<>();
Collection<PluginInfo> updatedPlugins = new ArrayList<>();
for (PluginInfo pluginInfo : downloadedPlugins) {
if (installedPluginKeys.contains(pluginInfo.getKey())) {
updatedPlugins.add(pluginInfo);
} else {
newPlugins.add(pluginInfo);
}
}
PendingPluginsWsResponse.Builder builder = PendingPluginsWsResponse.newBuilder();
builder.addAllInstalling(getPlugins(newPlugins, compatiblePluginsByKey));
builder.addAllUpdating(getPlugins(updatedPlugins, compatiblePluginsByKey));
builder.addAllRemoving(getPlugins(uninstalledPlugins, compatiblePluginsByKey));
return builder;
}
private static List<PluginDetails> getPlugins(Collection<PluginInfo> plugins, Map<String, Plugin> compatiblePluginsByKey) {
return ImmutableSortedSet.copyOf(NAME_KEY_PLUGIN_METADATA_COMPARATOR, plugins)
.stream()
.map(pluginInfo -> {
Plugin plugin = compatiblePluginsByKey.get(pluginInfo.getKey());
return buildPluginDetails(null, pluginInfo, null, plugin);
})
.toList();
}
}
| 5,629 | 44.772358 | 166 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/PluginUpdateAggregator.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.plugins.ws;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Nullable;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.transform;
import static java.lang.String.format;
public class PluginUpdateAggregator {
public Collection<PluginUpdateAggregate> aggregate(@Nullable Collection<PluginUpdate> pluginUpdates) {
if (pluginUpdates == null || pluginUpdates.isEmpty()) {
return Collections.emptyList();
}
Map<Plugin, PluginUpdateAggregateBuilder> builders = new HashMap<>();
for (PluginUpdate pluginUpdate : pluginUpdates) {
Plugin plugin = pluginUpdate.getPlugin();
PluginUpdateAggregateBuilder builder = builders.get(plugin);
if (builder == null) {
builder = PluginUpdateAggregateBuilder.builderFor(plugin);
builders.put(plugin, builder);
}
builder.add(pluginUpdate);
}
return Lists.newArrayList(transform(builders.values(), PluginUpdateAggregateBuilder::build));
}
@VisibleForTesting
static class PluginUpdateAggregateBuilder {
private final Plugin plugin;
private final List<PluginUpdate> updates = Lists.newArrayListWithExpectedSize(1);
// use static method
private PluginUpdateAggregateBuilder(Plugin plugin) {
this.plugin = plugin;
}
public static PluginUpdateAggregateBuilder builderFor(Plugin plugin) {
return new PluginUpdateAggregateBuilder(checkNotNull(plugin));
}
public PluginUpdateAggregateBuilder add(PluginUpdate pluginUpdate) {
checkArgument(
this.plugin.equals(pluginUpdate.getPlugin()),
format("This builder only accepts PluginUpdate instances for plugin %s", plugin));
this.updates.add(pluginUpdate);
return this;
}
public PluginUpdateAggregate build() {
return new PluginUpdateAggregate(this);
}
}
public static class PluginUpdateAggregate {
private final Plugin plugin;
private final Collection<PluginUpdate> updates;
protected PluginUpdateAggregate(PluginUpdateAggregateBuilder builder) {
this.plugin = builder.plugin;
this.updates = ImmutableList.copyOf(builder.updates);
}
public Plugin getPlugin() {
return plugin;
}
public Collection<PluginUpdate> getUpdates() {
return updates;
}
}
}
| 3,614 | 32.472222 | 104 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/PluginWSCommons.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.plugins.ws;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Ordering;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.core.platform.PluginInfo;
import org.sonar.db.plugin.PluginDto;
import org.sonar.server.plugins.ServerPlugin;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.updatecenter.common.Artifact;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonarqube.ws.Plugins.PluginDetails;
import org.sonarqube.ws.Plugins.Release;
import org.sonarqube.ws.Plugins.Require;
import org.sonarqube.ws.Plugins.UpdateStatus;
import static java.lang.String.CASE_INSENSITIVE_ORDER;
import static java.util.Optional.ofNullable;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.sonar.api.utils.DateUtils.formatDate;
import static org.sonar.server.plugins.edition.EditionBundledPlugins.isEditionBundled;
import static org.sonarqube.ws.Plugins.UpdateStatus.COMPATIBLE;
import static org.sonarqube.ws.Plugins.UpdateStatus.DEPS_REQUIRE_SYSTEM_UPGRADE;
import static org.sonarqube.ws.Plugins.UpdateStatus.INCOMPATIBLE;
import static org.sonarqube.ws.Plugins.UpdateStatus.REQUIRES_SYSTEM_UPGRADE;
public class PluginWSCommons {
public static final Ordering<PluginInfo> NAME_KEY_PLUGIN_METADATA_COMPARATOR = Ordering.natural()
.onResultOf(PluginInfo::getName)
.compound(Ordering.natural().onResultOf(PluginInfo::getKey));
public static final Comparator<ServerPlugin> NAME_KEY_COMPARATOR = Comparator
.comparing((java.util.function.Function<ServerPlugin, String>) installedPluginFile -> installedPluginFile.getPluginInfo().getName())
.thenComparing(f -> f.getPluginInfo().getKey());
public static final Comparator<Plugin> NAME_KEY_PLUGIN_ORDERING = Ordering.from(CASE_INSENSITIVE_ORDER)
.onResultOf(Plugin::getName)
.compound(
Ordering.from(CASE_INSENSITIVE_ORDER).onResultOf(Artifact::getKey));
public static final Comparator<PluginUpdate> NAME_KEY_PLUGIN_UPDATE_ORDERING = Ordering.from(NAME_KEY_PLUGIN_ORDERING)
.onResultOf(PluginUpdate::getPlugin);
private PluginWSCommons() {
// prevent instantiation
}
public static PluginDetails buildPluginDetails(@Nullable ServerPlugin installedPlugin, PluginInfo pluginInfo,
@Nullable PluginDto pluginDto, @Nullable Plugin updateCenterPlugin) {
PluginDetails.Builder builder = PluginDetails.newBuilder()
.setKey(pluginInfo.getKey())
.setName(pluginInfo.getName())
.setEditionBundled(isEditionBundled(pluginInfo))
.setSonarLintSupported(pluginInfo.isSonarLintSupported());
ofNullable(installedPlugin).ifPresent(serverPlugin -> {
builder.setFilename(installedPlugin.getJar().getFile().getName());
builder.setHash(installedPlugin.getJar().getMd5());
builder.setType(installedPlugin.getType().name());
});
ofNullable(pluginInfo.getVersion()).ifPresent(v -> builder.setVersion(isNotBlank(pluginInfo.getDisplayVersion()) ? pluginInfo.getDisplayVersion() : v.getName()));
ofNullable(updateCenterPlugin).flatMap(p -> ofNullable(p.getCategory())).ifPresent(builder::setCategory);
ofNullable(pluginDto).ifPresent(p -> builder.setUpdatedAt(p.getUpdatedAt()));
ofNullable(pluginInfo.getDescription()).ifPresent(builder::setDescription);
ofNullable(pluginInfo.getLicense()).ifPresent(builder::setLicense);
ofNullable(pluginInfo.getOrganizationName()).ifPresent(builder::setOrganizationName);
ofNullable(pluginInfo.getOrganizationUrl()).ifPresent(builder::setOrganizationUrl);
ofNullable(pluginInfo.getHomepageUrl()).ifPresent(builder::setHomepageUrl);
ofNullable(pluginInfo.getIssueTrackerUrl()).ifPresent(builder::setIssueTrackerUrl);
ofNullable(pluginInfo.getImplementationBuild()).ifPresent(builder::setImplementationBuild);
ofNullable(pluginInfo.getDocumentationPath()).ifPresent(builder::setDocumentationPath);
return builder.build();
}
static Release buildRelease(org.sonar.updatecenter.common.Release release) {
String version = isNotBlank(release.getDisplayVersion()) ? release.getDisplayVersion() : release.getVersion().toString();
Release.Builder releaseBuilder = Release.newBuilder().setVersion(version);
ofNullable(release.getDate()).ifPresent(date -> releaseBuilder.setDate(formatDate(date)));
ofNullable(release.getChangelogUrl()).ifPresent(releaseBuilder::setChangeLogUrl);
ofNullable(release.getDescription()).ifPresent(releaseBuilder::setDescription);
return releaseBuilder.build();
}
static List<Require> buildRequires(PluginUpdate pluginUpdate) {
return pluginUpdate.getRelease().getOutgoingDependencies().stream().map(
org.sonar.updatecenter.common.Release::getArtifact)
.filter(release -> release instanceof Plugin)
.map(artifact -> (Plugin) artifact)
.map(artifact -> {
Require.Builder builder = Require.newBuilder()
.setKey(artifact.getKey());
ofNullable(artifact.getName()).ifPresent(builder::setName);
ofNullable(artifact.getDescription()).ifPresent(builder::setDescription);
return builder.build();
})
.toList();
}
static UpdateStatus convertUpdateCenterStatus(PluginUpdate.Status status) {
switch (status) {
case COMPATIBLE:
return COMPATIBLE;
case INCOMPATIBLE:
return INCOMPATIBLE;
case REQUIRE_SONAR_UPGRADE:
return REQUIRES_SYSTEM_UPGRADE;
case DEPENDENCIES_REQUIRE_SONAR_UPGRADE:
return DEPS_REQUIRE_SYSTEM_UPGRADE;
default:
throw new IllegalArgumentException("Unsupported value of PluginUpdate.Status " + status);
}
}
private static List<Plugin> compatiblePlugins(UpdateCenterMatrixFactory updateCenterMatrixFactory) {
Optional<UpdateCenter> updateCenter = updateCenterMatrixFactory.getUpdateCenter(false);
return updateCenter.isPresent() ? updateCenter.get().findAllCompatiblePlugins() : Collections.emptyList();
}
static ImmutableMap<String, Plugin> compatiblePluginsByKey(UpdateCenterMatrixFactory updateCenterMatrixFactory) {
List<Plugin> compatiblePlugins = compatiblePlugins(updateCenterMatrixFactory);
return Maps.uniqueIndex(compatiblePlugins, Artifact::getKey);
}
}
| 7,333 | 47.893333 | 166 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/PluginsWs.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.plugins.ws;
import org.sonar.api.server.ws.WebService;
/**
* WebService bound to URL {@code api/plugins}.
*/
public class PluginsWs implements WebService {
private final PluginsWsAction[] actions;
public PluginsWs(PluginsWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/plugins");
controller.setDescription("Manage the plugins on the server, including installing, uninstalling, and upgrading.")
.setSince("5.2");
for (PluginsWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,535 | 31.680851 | 117 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/PluginsWsAction.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.plugins.ws;
import org.sonar.server.ws.WsAction;
/**
* Marker interface for the action of the plugins WS implemented by {@link PluginsWs}.
*/
public interface PluginsWsAction extends WsAction {
}
| 1,068 | 35.862069 | 86 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/UninstallAction.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.plugins.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.server.plugins.PluginUninstaller;
import org.sonar.server.user.UserSession;
/**
* Implementation of the {@code uninstall} action for the Plugins WebService.
*/
public class UninstallAction implements PluginsWsAction {
private static final String PARAM_KEY = "key";
private final PluginUninstaller pluginUninstaller;
private final UserSession userSession;
public UninstallAction(PluginUninstaller pluginUninstaller, UserSession userSession) {
this.pluginUninstaller = pluginUninstaller;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("uninstall")
.setPost(true)
.setSince("5.2")
.setDescription("Uninstalls the plugin specified by its key." +
"<br/>" +
"Requires user to be authenticated with Administer System permissions.")
.setHandler(this);
action.createParam(PARAM_KEY)
.setDescription("The key identifying the plugin to uninstall")
.setRequired(true);
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkIsSystemAdministrator();
pluginUninstaller.uninstall(request.mandatoryParam(PARAM_KEY));
response.noContent();
}
}
| 2,316 | 35.203125 | 88 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/UpdateAction.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.plugins.ws;
import java.util.Optional;
import javax.annotation.Nonnull;
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.plugins.PluginDownloader;
import org.sonar.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.user.UserSession;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.UpdateCenter;
import static java.lang.String.format;
/**
* Implementation of the {@code update} action for the Plugins WebService.
*/
public class UpdateAction implements PluginsWsAction {
public static final String PARAM_KEY = "key";
public static final PluginUpdate MISSING_PLUGIN = null;
private final UpdateCenterMatrixFactory updateCenterFactory;
private final PluginDownloader pluginDownloader;
private final UserSession userSession;
public UpdateAction(UpdateCenterMatrixFactory updateCenterFactory, PluginDownloader pluginDownloader, UserSession userSession) {
this.updateCenterFactory = updateCenterFactory;
this.pluginDownloader = pluginDownloader;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("update")
.setPost(true)
.setSince("5.2")
.setDescription("Updates a plugin specified by its key to the latest version compatible with the SonarQube instance." +
"<br/>" +
"Plugin information is retrieved from Update Center." +
"<br/>" +
"Requires user to be authenticated with Administer System permissions")
.setHandler(this);
action.createParam(PARAM_KEY)
.setRequired(true)
.setDescription("The key identifying the plugin to update");
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkIsSystemAdministrator();
String key = request.mandatoryParam(PARAM_KEY);
PluginUpdate pluginUpdate = findPluginUpdateByKey(key);
pluginDownloader.download(key, pluginUpdate.getRelease().getVersion());
response.noContent();
}
@Nonnull
private PluginUpdate findPluginUpdateByKey(String key) {
Optional<UpdateCenter> updateCenter = updateCenterFactory.getUpdateCenter(false);
PluginUpdate pluginUpdate = MISSING_PLUGIN;
if (updateCenter.isPresent()) {
pluginUpdate = updateCenter.get().findPluginUpdates().stream()
.filter(update -> update != null && key.equals(update.getPlugin().getKey()))
.findFirst().orElse(MISSING_PLUGIN);
}
if (pluginUpdate == MISSING_PLUGIN) {
throw new IllegalArgumentException(
format("No plugin with key '%s' or plugin '%s' is already in latest compatible version", key, key));
}
return pluginUpdate;
}
}
| 3,709 | 36.857143 | 130 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/ws/UpdatesAction.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.plugins.ws;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Ordering;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
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.server.plugins.UpdateCenterMatrixFactory;
import org.sonar.server.plugins.ws.PluginUpdateAggregator.PluginUpdateAggregate;
import org.sonar.server.user.UserSession;
import org.sonar.updatecenter.common.Plugin;
import org.sonar.updatecenter.common.PluginUpdate;
import org.sonar.updatecenter.common.UpdateCenter;
import org.sonarqube.ws.Plugins.AvailableUpdate;
import org.sonarqube.ws.Plugins.UpdatablePlugin;
import org.sonarqube.ws.Plugins.UpdatesPluginsWsResponse;
import org.sonarqube.ws.Plugins.UpdatesPluginsWsResponse.Builder;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.server.plugins.edition.EditionBundledPlugins.isEditionBundled;
import static org.sonar.server.plugins.ws.PluginWSCommons.buildRelease;
import static org.sonar.server.plugins.ws.PluginWSCommons.buildRequires;
import static org.sonar.server.plugins.ws.PluginWSCommons.convertUpdateCenterStatus;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
/**
* Implementation of the {@code updates} action for the Plugins WebService.
*/
public class UpdatesAction implements PluginsWsAction {
private static final boolean DO_NOT_FORCE_REFRESH = false;
private static final String HTML_TAG_BR = "<br/>";
private static final Ordering<PluginUpdateAggregate> NAME_KEY_PLUGIN_UPGRADE_AGGREGATE_ORDERING = Ordering.from(PluginWSCommons.NAME_KEY_PLUGIN_ORDERING)
.onResultOf(PluginUpdateAggregate::getPlugin);
private static final Ordering<PluginUpdate> PLUGIN_UPDATE_BY_VERSION_ORDERING = Ordering.natural()
.onResultOf(input -> Objects.requireNonNull(input).getRelease().getVersion().toString());
private final UserSession userSession;
private final UpdateCenterMatrixFactory updateCenterMatrixFactory;
private final PluginUpdateAggregator aggregator;
public UpdatesAction(UserSession userSession, UpdateCenterMatrixFactory updateCenterMatrixFactory,
PluginUpdateAggregator aggregator) {
this.userSession = userSession;
this.updateCenterMatrixFactory = updateCenterMatrixFactory;
this.aggregator = aggregator;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("updates")
.setDescription("Lists plugins installed on the SonarQube instance for which at least one newer version is available, sorted by plugin name." +
HTML_TAG_BR +
"Each newer version is listed, ordered from the oldest to the newest, with its own update/compatibility status." +
HTML_TAG_BR +
"Plugin information is retrieved from Update Center. Date and time at which Update Center was last refreshed is provided in the response." +
HTML_TAG_BR +
"Update status values are: [COMPATIBLE, INCOMPATIBLE, REQUIRES_UPGRADE, DEPS_REQUIRE_UPGRADE]." +
HTML_TAG_BR +
"Require 'Administer System' permission.")
.setSince("5.2")
.setHandler(this)
.setResponseExample(this.getClass().getResource("example-updates_plugins.json"));
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkIsSystemAdministrator();
Optional<UpdateCenter> updateCenter = updateCenterMatrixFactory.getUpdateCenter(DO_NOT_FORCE_REFRESH);
Collection<UpdatablePlugin> plugins = updateCenter.isPresent() ? getPluginUpdates(updateCenter.get()) : Collections.emptyList();
Builder responseBuilder = UpdatesPluginsWsResponse.newBuilder().addAllPlugins(plugins);
updateCenter.ifPresent(u -> responseBuilder.setUpdateCenterRefresh(formatDateTime(u.getDate().getTime())));
writeProtobuf(responseBuilder.build(), request, response);
}
private List<UpdatablePlugin> getPluginUpdates(UpdateCenter updateCenter) {
return retrieveUpdatablePlugins(updateCenter)
.stream()
.map(pluginUpdateAggregate -> {
Plugin plugin = pluginUpdateAggregate.getPlugin();
UpdatablePlugin.Builder builder = UpdatablePlugin.newBuilder()
.setKey(plugin.getKey())
.setEditionBundled(isEditionBundled(plugin))
.addAllUpdates(buildUpdates(pluginUpdateAggregate));
ofNullable(plugin.getName()).ifPresent(builder::setName);
ofNullable(plugin.getCategory()).ifPresent(builder::setCategory);
ofNullable(plugin.getDescription()).ifPresent(builder::setDescription);
ofNullable(plugin.getLicense()).ifPresent(builder::setLicense);
ofNullable(plugin.getTermsConditionsUrl()).ifPresent(builder::setTermsAndConditionsUrl);
ofNullable(plugin.getOrganization()).ifPresent(builder::setOrganizationName);
ofNullable(plugin.getOrganizationUrl()).ifPresent(builder::setOrganizationUrl);
ofNullable(plugin.getIssueTrackerUrl()).ifPresent(builder::setIssueTrackerUrl);
ofNullable(plugin.getHomepageUrl()).ifPresent(builder::setHomepageUrl);
return builder.build();
}).toList();
}
private static Collection<AvailableUpdate> buildUpdates(PluginUpdateAggregate pluginUpdateAggregate) {
return ImmutableSortedSet.copyOf(PLUGIN_UPDATE_BY_VERSION_ORDERING, pluginUpdateAggregate.getUpdates()).stream()
.map(pluginUpdate -> AvailableUpdate.newBuilder()
.setRelease(buildRelease(pluginUpdate.getRelease()))
.setStatus(convertUpdateCenterStatus(pluginUpdate.getStatus()))
.addAllRequires(buildRequires(pluginUpdate))
.build())
.toList();
}
private Collection<PluginUpdateAggregate> retrieveUpdatablePlugins(UpdateCenter updateCenter) {
List<PluginUpdate> pluginUpdates = updateCenter.findPluginUpdates();
// aggregates updates of the same plugin to a single object and sort these objects by plugin name then key
return ImmutableSortedSet.copyOf(
NAME_KEY_PLUGIN_UPGRADE_AGGREGATE_ORDERING,
aggregator.aggregate(pluginUpdates));
}
}
| 7,113 | 48.062069 | 155 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/plugins/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.plugins.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 37.76 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/BulkDeleteAction.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.project.ws;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.lang.StringUtils;
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.api.utils.DateUtils;
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.ComponentQuery;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.server.component.ComponentCleanerService;
import org.sonar.server.project.DeletedProject;
import org.sonar.server.project.Project;
import org.sonar.server.project.ProjectLifeCycleListeners;
import org.sonar.server.project.Visibility;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static java.lang.Math.min;
import static java.lang.String.format;
import static java.util.stream.Collectors.toSet;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.resources.Qualifiers.VIEW;
import static org.sonar.server.project.ws.SearchAction.buildDbQuery;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
public class BulkDeleteAction implements ProjectsWsAction {
private static final String ACTION = "bulk_delete";
private final ComponentCleanerService componentCleanerService;
private final DbClient dbClient;
private final UserSession userSession;
private final ProjectLifeCycleListeners projectLifeCycleListeners;
public BulkDeleteAction(ComponentCleanerService componentCleanerService, DbClient dbClient, UserSession userSession,
ProjectLifeCycleListeners projectLifeCycleListeners) {
this.componentCleanerService = componentCleanerService;
this.dbClient = dbClient;
this.userSession = userSession;
this.projectLifeCycleListeners = projectLifeCycleListeners;
}
@Override
public void define(WebService.NewController context) {
String parameterRequiredMessage = format("At least one parameter is required among %s, %s and %s",
PARAM_ANALYZED_BEFORE, PARAM_PROJECTS, Param.TEXT_QUERY);
WebService.NewAction action = context
.createAction(ACTION)
.setPost(true)
.setDescription("Delete one or several projects.<br />" +
"Only the 1'000 first items in project filters are taken into account.<br />" +
"Requires 'Administer System' permission.<br />" +
parameterRequiredMessage)
.setSince("5.2")
.setHandler(this)
.setChangelog(
new Change("7.8", parameterRequiredMessage),
new Change("9.1", "The parameter '" + PARAM_ANALYZED_BEFORE + "' "
+ "takes into account the analysis of all branches and pull requests, not only the main branch."));
action
.createParam(PARAM_PROJECTS)
.setDescription("Comma-separated list of project keys")
.setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
action.createParam(Param.TEXT_QUERY)
.setDescription("Limit to: <ul>" +
"<li>component names that contain the supplied string</li>" +
"<li>component keys that contain the supplied string</li>" +
"</ul>")
.setExampleValue("sonar");
action.createParam(PARAM_QUALIFIERS)
.setDescription("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers")
.setPossibleValues(PROJECT, VIEW, APP)
.setDefaultValue(PROJECT);
action.createParam(PARAM_VISIBILITY)
.setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
"If no visibility is specified, the default project visibility will be used.",
Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
.setRequired(false)
.setInternal(true)
.setSince("6.4")
.setPossibleValues(Visibility.getLabels());
action.createParam(PARAM_ANALYZED_BEFORE)
.setDescription("Filter the projects for which last analysis of any branch is older than the given date (exclusive).<br> " +
"Either a date (server timezone) or datetime can be provided.")
.setSince("6.6")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
action.createParam(PARAM_ON_PROVISIONED_ONLY)
.setDescription("Filter the projects that are provisioned")
.setBooleanPossibleValues()
.setDefaultValue("false")
.setSince("6.6");
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchRequest searchRequest = toSearchWsRequest(request);
userSession.checkLoggedIn();
try (DbSession dbSession = dbClient.openSession(false)) {
userSession.checkPermission(GlobalPermission.ADMINISTER);
checkAtLeastOneParameterIsPresent(searchRequest);
checkIfAnalyzedBeforeIsFutureDate(searchRequest);
ComponentQuery query = buildDbQuery(searchRequest);
Set<ComponentDto> componentDtos = new HashSet<>(dbClient.componentDao().selectByQuery(dbSession, query, 0, Integer.MAX_VALUE));
List<EntityDto> entities = dbClient.entityDao().selectByKeys(dbSession, componentDtos.stream().map(ComponentDto::getKey).collect(toSet()));
try {
entities.forEach(p -> componentCleanerService.deleteEntity(dbSession, p));
} finally {
callDeleteListeners(dbSession, entities);
}
}
response.noContent();
}
private void callDeleteListeners(DbSession dbSession, List<EntityDto> entities) {
Set<String> entityUuids = entities.stream().map(EntityDto::getUuid).collect(toSet());
Map<String, String> mainBranchUuidByEntityUuid = dbClient.branchDao().selectMainBranchesByProjectUuids(dbSession, entityUuids).stream()
.collect(Collectors.toMap(BranchDto::getProjectUuid, BranchDto::getUuid));
ImmutableSet<DeletedProject> deletedProjects = entities.stream().map(entity -> new DeletedProject(Project.from(entity), mainBranchUuidByEntityUuid.get(entity.getUuid())))
.collect(toImmutableSet());
projectLifeCycleListeners.onProjectsDeleted(deletedProjects);
}
private static void checkAtLeastOneParameterIsPresent(SearchRequest searchRequest) {
boolean analyzedBeforePresent = !Strings.isNullOrEmpty(searchRequest.getAnalyzedBefore());
List<String> projects = searchRequest.getProjects();
boolean projectsPresent = projects != null && !projects.isEmpty();
boolean queryPresent = !Strings.isNullOrEmpty(searchRequest.getQuery());
boolean atLeastOneParameterIsPresent = analyzedBeforePresent || projectsPresent || queryPresent;
checkArgument(atLeastOneParameterIsPresent, format("At least one parameter among %s, %s and %s must be provided",
PARAM_ANALYZED_BEFORE, PARAM_PROJECTS, Param.TEXT_QUERY));
}
private static void checkIfAnalyzedBeforeIsFutureDate(SearchRequest searchRequest) {
String analyzedBeforeParam = searchRequest.getAnalyzedBefore();
Optional.ofNullable(analyzedBeforeParam)
.filter(StringUtils::isNotEmpty)
.map(DateUtils::parseDateOrDateTime)
.ifPresent(analyzedBeforeDate -> {
boolean isFutureDate = new Date().compareTo(analyzedBeforeDate) < 0;
checkArgument(!isFutureDate, format("Provided value for parameter %s must not be a future date", PARAM_ANALYZED_BEFORE));
});
}
private static SearchRequest toSearchWsRequest(Request request) {
return SearchRequest.builder()
.setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
.setQuery(request.param(Param.TEXT_QUERY))
.setVisibility(request.param(PARAM_VISIBILITY))
.setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
.setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
.setProjects(restrictTo1000Values(request.paramAsStrings(PARAM_PROJECTS)))
.build();
}
@CheckForNull
private static List<String> restrictTo1000Values(@Nullable List<String> values) {
if (values == null) {
return null;
}
return values.subList(0, min(values.size(), 1_000));
}
}
| 10,063 | 44.745455 | 174 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/CreateAction.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.project.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.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.component.ComponentCreationData;
import org.sonar.server.component.ComponentUpdater;
import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver;
import org.sonar.server.project.DefaultBranchNameResolver;
import org.sonar.server.project.ProjectDefaultVisibility;
import org.sonar.server.project.Visibility;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Projects.CreateWsResponse;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.abbreviate;
import static org.sonar.api.resources.Qualifiers.PROJECT;
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.db.permission.GlobalPermission.PROVISION_PROJECTS;
import static org.sonar.server.component.NewComponent.newComponentBuilder;
import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION;
import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION;
import static org.sonar.server.newcodeperiod.NewCodeDefinitionResolver.checkNewCodeDefinitionParam;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.ACTION_CREATE;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_MAIN_BRANCH;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NAME;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_TYPE;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_NEW_CODE_DEFINITION_VALUE;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
public class CreateAction implements ProjectsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentUpdater componentUpdater;
private final ProjectDefaultVisibility projectDefaultVisibility;
private final DefaultBranchNameResolver defaultBranchNameResolver;
private final NewCodeDefinitionResolver newCodeDefinitionResolver;
public CreateAction(DbClient dbClient, UserSession userSession, ComponentUpdater componentUpdater,
ProjectDefaultVisibility projectDefaultVisibility, DefaultBranchNameResolver defaultBranchNameResolver, NewCodeDefinitionResolver newCodeDefinitionResolver) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentUpdater = componentUpdater;
this.projectDefaultVisibility = projectDefaultVisibility;
this.defaultBranchNameResolver = defaultBranchNameResolver;
this.newCodeDefinitionResolver = newCodeDefinitionResolver;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_CREATE)
.setDescription("Create a project.<br/>" +
"Requires 'Create Projects' permission")
.setSince("4.0")
.setPost(true)
.setResponseExample(getClass().getResource("create-example.json"))
.setHandler(this);
action.setChangelog(
new Change("9.8", "Field 'mainBranch' added to the request"),
new Change("7.1", "The 'visibility' parameter is public"));
action.createParam(PARAM_PROJECT)
.setDescription("Key of the project")
.setRequired(true)
.setMaximumLength(MAX_COMPONENT_KEY_LENGTH)
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_NAME)
.setDescription("Name of the project. If name is longer than %d, it is abbreviated.", MAX_COMPONENT_NAME_LENGTH)
.setRequired(true)
.setExampleValue("SonarQube");
action.createParam(PARAM_MAIN_BRANCH)
.setDescription("Key of the main branch of the project. If not provided, the default main branch key will be used.")
.setSince("9.8")
.setExampleValue("develop");
action.createParam(PARAM_VISIBILITY)
.setDescription("Whether the created project should be visible to everyone, or only specific user/groups.<br/>" +
"If no visibility is specified, the default project visibility will be used.")
.setSince("6.4")
.setPossibleValues(Visibility.getLabels());
action.createParam(PARAM_NEW_CODE_DEFINITION_TYPE)
.setDescription(NEW_CODE_PERIOD_TYPE_DESCRIPTION_PROJECT_CREATION)
.setSince("10.1");
action.createParam(PARAM_NEW_CODE_DEFINITION_VALUE)
.setDescription(NEW_CODE_PERIOD_VALUE_DESCRIPTION_PROJECT_CREATION)
.setSince("10.1");
}
@Override
public void handle(Request request, Response response) throws Exception {
CreateRequest createRequest = toCreateRequest(request);
writeProtobuf(doHandle(createRequest), request, response);
}
private CreateWsResponse doHandle(CreateRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
userSession.checkPermission(PROVISION_PROJECTS);
checkNewCodeDefinitionParam(request.getNewCodeDefinitionType(), request.getNewCodeDefinitionValue());
ComponentCreationData componentData = createProject(request, dbSession);
if (request.getNewCodeDefinitionType() != null) {
String defaultBranchName = Optional.ofNullable(request.getMainBranchKey()).orElse(defaultBranchNameResolver.getEffectiveMainBranchName());
newCodeDefinitionResolver.createNewCodeDefinition(dbSession, componentData.mainBranchDto().getUuid(), defaultBranchName, request.getNewCodeDefinitionType(),
request.getNewCodeDefinitionValue());
}
componentUpdater.commitAndIndex(dbSession, componentData);
return toCreateResponse(componentData.projectDto());
}
}
private ComponentCreationData createProject(CreateRequest request, DbSession dbSession) {
String visibility = request.getVisibility();
boolean changeToPrivate = visibility == null ? projectDefaultVisibility.get(dbSession).isPrivate() : "private".equals(visibility);
return componentUpdater.createWithoutCommit(dbSession, newComponentBuilder()
.setKey(request.getProjectKey())
.setName(request.getName())
.setPrivate(changeToPrivate)
.setQualifier(PROJECT)
.build(),
userSession.isLoggedIn() ? userSession.getUuid() : null,
userSession.isLoggedIn() ? userSession.getLogin() : null,
request.getMainBranchKey());
}
private static CreateRequest toCreateRequest(Request request) {
return CreateRequest.builder()
.setProjectKey(request.mandatoryParam(PARAM_PROJECT))
.setName(abbreviate(request.mandatoryParam(PARAM_NAME), MAX_COMPONENT_NAME_LENGTH))
.setVisibility(request.param(PARAM_VISIBILITY))
.setMainBranchKey(request.param(PARAM_MAIN_BRANCH))
.setNewCodeDefinitionType(request.param(PARAM_NEW_CODE_DEFINITION_TYPE))
.setNewCodeDefinitionValue(request.param(PARAM_NEW_CODE_DEFINITION_VALUE))
.build();
}
private static CreateWsResponse toCreateResponse(EntityDto project) {
return CreateWsResponse.newBuilder()
.setProject(CreateWsResponse.Project.newBuilder()
.setKey(project.getKey())
.setName(project.getName())
.setQualifier(project.getQualifier())
.setVisibility(Visibility.getLabel(project.isPrivate())))
.build();
}
static class CreateRequest {
private final String projectKey;
private final String name;
private final String mainBranchKey;
@CheckForNull
private final String visibility;
@CheckForNull
private final String newCodeDefinitionType;
@CheckForNull
private final String newCodeDefinitionValue;
private CreateRequest(Builder builder) {
this.projectKey = builder.projectKey;
this.name = builder.name;
this.visibility = builder.visibility;
this.mainBranchKey = builder.mainBranchKey;
this.newCodeDefinitionType = builder.newCodeDefinitionType;
this.newCodeDefinitionValue = builder.newCodeDefinitionValue;
}
public String getProjectKey() {
return projectKey;
}
public String getName() {
return name;
}
@CheckForNull
public String getVisibility() {
return visibility;
}
public String getMainBranchKey() {
return mainBranchKey;
}
@CheckForNull
public String getNewCodeDefinitionType() {
return newCodeDefinitionType;
}
@CheckForNull
public String getNewCodeDefinitionValue() {
return newCodeDefinitionValue;
}
public static Builder builder() {
return new Builder();
}
}
static class Builder {
private String projectKey;
private String name;
private String mainBranchKey;
@CheckForNull
private String visibility;
@CheckForNull
private String newCodeDefinitionType;
@CheckForNull
private String newCodeDefinitionValue;
private Builder() {
}
public Builder setProjectKey(String projectKey) {
requireNonNull(projectKey);
this.projectKey = projectKey;
return this;
}
public Builder setName(String name) {
requireNonNull(name);
this.name = name;
return this;
}
public Builder setVisibility(@Nullable String visibility) {
this.visibility = visibility;
return this;
}
public Builder setMainBranchKey(@Nullable String mainBranchKey) {
this.mainBranchKey = mainBranchKey;
return this;
}
public Builder setNewCodeDefinitionType(@Nullable String newCodeDefinitionType) {
this.newCodeDefinitionType = newCodeDefinitionType;
return this;
}
public Builder setNewCodeDefinitionValue(@Nullable String newCodeDefinitionValue) {
this.newCodeDefinitionValue = newCodeDefinitionValue;
return this;
}
public CreateRequest build() {
requireNonNull(projectKey);
requireNonNull(name);
return new CreateRequest(this);
}
}
}
| 11,378 | 37.836177 | 164 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/DeleteAction.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.project.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.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentCleanerService;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.project.DeletedProject;
import org.sonar.server.project.Project;
import org.sonar.server.project.ProjectLifeCycleListeners;
import org.sonar.server.user.UserSession;
import static java.util.Collections.singleton;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT;
public class DeleteAction implements ProjectsWsAction {
private static final String ACTION = "delete";
private final ComponentCleanerService componentCleanerService;
private final ComponentFinder componentFinder;
private final DbClient dbClient;
private final UserSession userSession;
private final ProjectLifeCycleListeners projectLifeCycleListeners;
public DeleteAction(ComponentCleanerService componentCleanerService, ComponentFinder componentFinder, DbClient dbClient,
UserSession userSession, ProjectLifeCycleListeners projectLifeCycleListeners) {
this.componentCleanerService = componentCleanerService;
this.componentFinder = componentFinder;
this.dbClient = dbClient;
this.userSession = userSession;
this.projectLifeCycleListeners = projectLifeCycleListeners;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context
.createAction(ACTION)
.setPost(true)
.setDescription("Delete a project.<br> " +
"Requires 'Administer System' permission or 'Administer' permission on the project.")
.setSince("5.2")
.setHandler(this);
action
.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setRequired(true)
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
}
@Override
public void handle(Request request, Response response) throws Exception {
// fail-fast if not logged in
userSession.checkLoggedIn();
String key = request.mandatoryParam(PARAM_PROJECT);
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = componentFinder.getProjectByKey(dbSession, key);
BranchDto mainBranch = componentFinder.getMainBranch(dbSession, project);
checkPermission(project);
componentCleanerService.deleteEntity(dbSession, project);
projectLifeCycleListeners.onProjectsDeleted(singleton(new DeletedProject(Project.fromProjectDtoWithTags(project), mainBranch.getUuid())));
}
response.noContent();
}
private void checkPermission(ProjectDto project) {
if (!userSession.hasEntityPermission(UserRole.ADMIN, project)) {
userSession.checkPermission(GlobalPermission.ADMINISTER);
}
}
}
| 3,965 | 38.66 | 144 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/ProjectFinder.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.project.ws;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
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.permission.GlobalPermission;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.user.UserSession;
import static java.util.Comparator.comparing;
import static java.util.Comparator.nullsFirst;
import static java.util.Locale.ENGLISH;
import static java.util.Objects.requireNonNull;
import static java.util.stream.Collectors.toSet;
@ServerSide
public class ProjectFinder {
private final DbClient dbClient;
private final UserSession userSession;
public ProjectFinder(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
public SearchResult search(DbSession dbSession, @Nullable String searchQuery) {
List<ProjectDto> allProjects = dbClient.projectDao().selectProjects(dbSession);
Set<String> projectsUserHasAccessTo = userSession.keepAuthorizedEntities(UserRole.SCAN, allProjects)
.stream()
.map(ProjectDto::getKey)
.collect(toSet());
applyQueryAndPermissionFilter(searchQuery, allProjects, projectsUserHasAccessTo);
List<Project> resultProjects = allProjects.stream()
.sorted(comparing(ProjectDto::getName, nullsFirst(String.CASE_INSENSITIVE_ORDER)))
.map(p -> new Project(p.getKey(), p.getName()))
.toList();
return new SearchResult(resultProjects);
}
private void applyQueryAndPermissionFilter(@Nullable String searchQuery, final List<ProjectDto> projects,
Set<String> projectsUserHasAccessTo) {
Iterator<ProjectDto> projectIterator = projects.iterator();
while (projectIterator.hasNext()) {
ProjectDto project = projectIterator.next();
if (isFilteredByQuery(searchQuery, project.getName()) || !hasPermission(projectsUserHasAccessTo, project.getKey())) {
projectIterator.remove();
}
}
}
private static boolean isFilteredByQuery(@Nullable String query, String projectName) {
return query != null && !projectName.toLowerCase(ENGLISH).contains(query.toLowerCase(ENGLISH));
}
private boolean hasPermission(Set<String> projectsUserHasAccessTo, String projectKey) {
return userSession.hasPermission(GlobalPermission.SCAN) || projectsUserHasAccessTo.contains(projectKey);
}
public static class SearchResult {
private final List<Project> projects;
public SearchResult(List<Project> projects) {
this.projects = projects;
}
public List<Project> getProjects() {
return projects;
}
}
public static class Project {
private final String key;
private final String name;
public Project(String key, @Nullable String name) {
this.key = requireNonNull(key, "Key cant be null");
this.name = name;
}
public String getKey() {
return key;
}
@CheckForNull
public String getName() {
return name;
}
}
}
| 3,979 | 32.166667 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/ProjectsWs.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.project.ws;
import java.util.Arrays;
import org.sonar.api.server.ws.WebService;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.CONTROLLER;
public class ProjectsWs implements WebService {
private final ProjectsWsAction[] actions;
public ProjectsWs(ProjectsWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController(CONTROLLER)
.setSince("2.10")
.setDescription("Manage project existence.");
Arrays.stream(actions).forEach(action -> action.define(controller));
controller.done();
}
}
| 1,507 | 32.511111 | 78 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/ProjectsWsAction.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.project.ws;
import org.sonar.server.ws.WsAction;
public interface ProjectsWsAction extends WsAction {
// marker interface
}
| 996 | 35.925926 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/ProjectsWsModule.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.project.ws;
import org.sonar.core.platform.Module;
import org.sonar.server.project.ProjectDefaultVisibility;
import org.sonar.server.project.ProjectLifeCycleListenersImpl;
public class ProjectsWsModule extends Module {
public ProjectsWsModule() {
// nothing to do
}
@Override
protected void configureModule() {
add(
ProjectDefaultVisibility.class,
ProjectFinder.class,
ProjectLifeCycleListenersImpl.class,
ProjectsWs.class,
CreateAction.class,
BulkDeleteAction.class,
DeleteAction.class,
UpdateKeyAction.class,
SearchMyProjectsAction.class,
SearchAction.class,
SearchMyScannableProjectsAction.class,
UpdateVisibilityAction.class,
UpdateDefaultVisibilityAction.class);
}
}
| 1,640 | 31.82 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/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.project.ws;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
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.server.ws.WebService.Param;
import org.sonar.api.utils.Paging;
import org.sonar.db.DatabaseUtils;
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.ComponentQuery;
import org.sonar.db.component.ProjectLastAnalysisDateDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.permission.GlobalPermission;
import org.sonar.server.project.Visibility;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Projects.SearchWsResponse;
import static java.util.Optional.ofNullable;
import static java.util.function.Function.identity;
import static org.sonar.api.resources.Qualifiers.APP;
import static org.sonar.api.resources.Qualifiers.PROJECT;
import static org.sonar.api.resources.Qualifiers.VIEW;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.api.utils.DateUtils.parseDateOrDateTime;
import static org.sonar.server.project.Visibility.PRIVATE;
import static org.sonar.server.project.Visibility.PUBLIC;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_002;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.Projects.SearchWsResponse.Component;
import static org.sonarqube.ws.Projects.SearchWsResponse.newBuilder;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.ACTION_SEARCH;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.MAX_PAGE_SIZE;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ANALYZED_BEFORE;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_ON_PROVISIONED_ONLY;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECTS;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_QUALIFIERS;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
public class SearchAction implements ProjectsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
public SearchAction(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_SEARCH)
.setSince("6.3")
.setDescription("Search for projects or views to administrate them.<br>" +
"Requires 'Administer System' permission")
.addPagingParams(100, MAX_PAGE_SIZE)
.setResponseExample(getClass().getResource("search-example.json"))
.setChangelog(new Change("9.1", "The parameter '" + PARAM_ANALYZED_BEFORE + "' and the field 'lastAnalysisDate' of the returned projects "
+ "take into account the analysis of all branches and pull requests, not only the main branch."))
.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 contain the supplied string</li>" +
"</ul>")
.setExampleValue("sonar");
action.createParam(PARAM_QUALIFIERS)
.setDescription("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers")
.setPossibleValues(PROJECT, VIEW, APP)
.setDefaultValue(PROJECT);
action.createParam(PARAM_VISIBILITY)
.setDescription("Filter the projects that should be visible to everyone (%s), or only specific user/groups (%s).<br/>" +
"If no visibility is specified, the default project visibility will be used.",
Visibility.PUBLIC.getLabel(), Visibility.PRIVATE.getLabel())
.setRequired(false)
.setInternal(true)
.setSince("6.4")
.setPossibleValues(Visibility.getLabels());
action.createParam(PARAM_ANALYZED_BEFORE)
.setDescription("Filter the projects for which the last analysis of all branches are older than the given date (exclusive).<br> " +
"Either a date (server timezone) or datetime can be provided.")
.setSince("6.6")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200");
action.createParam(PARAM_ON_PROVISIONED_ONLY)
.setDescription("Filter the projects that are provisioned")
.setBooleanPossibleValues()
.setDefaultValue("false")
.setSince("6.6");
action
.createParam(PARAM_PROJECTS)
.setDescription("Comma-separated list of project keys")
.setSince("6.6")
// Limitation of ComponentDao#selectByQuery(), max 1000 values are accepted.
// Restricting size of HTTP parameter allows to not fail with SQL error
.setMaxValuesAllowed(DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)
.setExampleValue(String.join(",", KEY_PROJECT_EXAMPLE_001, KEY_PROJECT_EXAMPLE_002));
}
@Override
public void handle(Request wsRequest, Response wsResponse) throws Exception {
SearchWsResponse searchWsResponse = doHandle(toSearchWsRequest(wsRequest));
writeProtobuf(searchWsResponse, wsRequest, wsResponse);
}
private static SearchRequest toSearchWsRequest(Request request) {
return SearchRequest.builder()
.setQualifiers(request.mandatoryParamAsStrings(PARAM_QUALIFIERS))
.setQuery(request.param(Param.TEXT_QUERY))
.setPage(request.mandatoryParamAsInt(Param.PAGE))
.setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
.setVisibility(request.param(PARAM_VISIBILITY))
.setAnalyzedBefore(request.param(PARAM_ANALYZED_BEFORE))
.setOnProvisionedOnly(request.mandatoryParamAsBoolean(PARAM_ON_PROVISIONED_ONLY))
.setProjects(request.paramAsStrings(PARAM_PROJECTS))
.build();
}
private SearchWsResponse doHandle(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
userSession.checkPermission(GlobalPermission.ADMINISTER);
ComponentQuery query = buildDbQuery(request);
Paging paging = buildPaging(dbSession, request, query);
List<ComponentDto> components = dbClient.componentDao().selectByQuery(dbSession, query, paging.offset(), paging.pageSize());
Set<String> componentUuids = components.stream().map(ComponentDto::uuid).collect(Collectors.toSet());
List<BranchDto> branchDtos = dbClient.branchDao().selectByUuids(dbSession, componentUuids);
Map<String, String> projectUuidByComponentUuid = branchDtos.stream().collect(Collectors.toMap(BranchDto::getUuid,BranchDto::getProjectUuid));
Map<String, Long> lastAnalysisDateByComponentUuid = dbClient.snapshotDao().selectLastAnalysisDateByProjectUuids(dbSession, projectUuidByComponentUuid.values()).stream()
.collect(Collectors.toMap(ProjectLastAnalysisDateDto::getProjectUuid, ProjectLastAnalysisDateDto::getDate));
Map<String, SnapshotDto> snapshotsByComponentUuid = dbClient.snapshotDao()
.selectLastAnalysesByRootComponentUuids(dbSession, componentUuids).stream()
.collect(Collectors.toMap(SnapshotDto::getRootComponentUuid, identity()));
return buildResponse(components, snapshotsByComponentUuid, lastAnalysisDateByComponentUuid, projectUuidByComponentUuid, paging);
}
}
static ComponentQuery buildDbQuery(SearchRequest request) {
List<String> qualifiers = request.getQualifiers();
ComponentQuery.Builder query = ComponentQuery.builder()
.setQualifiers(qualifiers.toArray(new String[qualifiers.size()]));
ofNullable(request.getQuery()).ifPresent(q -> {
query.setNameOrKeyQuery(q);
query.setPartialMatchOnKey(true);
});
ofNullable(request.getVisibility()).ifPresent(v -> query.setPrivate(Visibility.isPrivate(v)));
ofNullable(request.getAnalyzedBefore()).ifPresent(d -> query.setAllBranchesAnalyzedBefore(parseDateOrDateTime(d).getTime()));
query.setOnProvisionedOnly(request.isOnProvisionedOnly());
ofNullable(request.getProjects()).ifPresent(keys -> query.setComponentKeys(new HashSet<>(keys)));
return query.build();
}
private Paging buildPaging(DbSession dbSession, SearchRequest request, ComponentQuery query) {
int total = dbClient.componentDao().countByQuery(dbSession, query);
return Paging.forPageIndex(request.getPage())
.withPageSize(request.getPageSize())
.andTotal(total);
}
private static SearchWsResponse buildResponse(List<ComponentDto> components, Map<String, SnapshotDto> snapshotsByComponentUuid,
Map<String, Long> lastAnalysisDateByComponentUuid, Map<String, String> projectUuidByComponentUuid, Paging paging) {
SearchWsResponse.Builder responseBuilder = newBuilder();
responseBuilder.getPagingBuilder()
.setPageIndex(paging.pageIndex())
.setPageSize(paging.pageSize())
.setTotal(paging.total())
.build();
components.stream()
.map(dto -> dtoToProject(dto, snapshotsByComponentUuid.get(dto.uuid()), lastAnalysisDateByComponentUuid.get(projectUuidByComponentUuid.get(dto.uuid()))))
.forEach(responseBuilder::addComponents);
return responseBuilder.build();
}
private static Component dtoToProject(ComponentDto dto, @Nullable SnapshotDto snapshot, @Nullable Long lastAnalysisDate) {
Component.Builder builder = Component.newBuilder()
.setKey(dto.getKey())
.setName(dto.name())
.setQualifier(dto.qualifier())
.setVisibility(dto.isPrivate() ? PRIVATE.getLabel() : PUBLIC.getLabel());
if (snapshot != null) {
ofNullable(lastAnalysisDate).ifPresent(d -> builder.setLastAnalysisDate(formatDateTime(d)));
ofNullable(snapshot.getRevision()).ifPresent(builder::setRevision);
}
return builder.build();
}
}
| 10,977 | 47.149123 | 174 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/SearchMyProjectsAction.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.project.ws;
import com.google.common.collect.ImmutableSet;
import java.util.List;
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.measures.CoreMetrics;
import org.sonar.api.resources.Qualifiers;
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.web.UserRole;
import org.sonar.db.DatabaseUtils;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.Pagination;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ProjectLinkDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.Projects.SearchMyProjectsWsResponse;
import org.sonarqube.ws.Projects.SearchMyProjectsWsResponse.Link;
import org.sonarqube.ws.Projects.SearchMyProjectsWsResponse.Project;
import static com.google.common.base.Strings.emptyToNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.server.project.ws.SearchMyProjectsData.builder;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchMyProjectsAction implements ProjectsWsAction {
private static final int MAX_SIZE = 500;
private final DbClient dbClient;
private final UserSession userSession;
public SearchMyProjectsAction(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
context.createAction("search_my_projects")
.setDescription("Return list of projects for which the current user has 'Administer' permission. Maximum 1'000 projects are returned.")
.setResponseExample(getClass().getResource("search_my_projects-example.json"))
.addPagingParams(100, MAX_SIZE)
.setSince("6.0")
.setInternal(true)
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchMyProjectsWsResponse searchMyProjectsWsResponse = doHandle(toRequest(request));
writeProtobuf(searchMyProjectsWsResponse, request, response);
}
private SearchMyProjectsWsResponse doHandle(SearchMyProjectsRequest request) {
checkAuthenticated();
try (DbSession dbSession = dbClient.openSession(false)) {
SearchMyProjectsData data = load(dbSession, request);
return buildResponse(request, data);
}
}
private static SearchMyProjectsWsResponse buildResponse(SearchMyProjectsRequest request, SearchMyProjectsData data) {
SearchMyProjectsWsResponse.Builder response = SearchMyProjectsWsResponse.newBuilder();
ProjectDtoToWs projectDtoToWs = new ProjectDtoToWs(data);
data.projects().stream()
.map(projectDtoToWs)
.forEach(response::addProjects);
response.getPagingBuilder()
.setPageIndex(request.getPage())
.setPageSize(request.getPageSize())
.setTotal(data.totalNbOfProjects())
.build();
return response.build();
}
private void checkAuthenticated() {
userSession.checkLoggedIn();
}
private static SearchMyProjectsRequest toRequest(Request request) {
return SearchMyProjectsRequest.builder()
.setPage(request.mandatoryParamAsInt(Param.PAGE))
.setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
.build();
}
private static class ProjectDtoToWs implements Function<ProjectDto, Project> {
private final SearchMyProjectsData data;
private ProjectDtoToWs(SearchMyProjectsData data) {
this.data = data;
}
@Override
public Project apply(ProjectDto dto) {
Project.Builder project = Project.newBuilder();
project
.setKey(dto.getKey())
.setName(dto.getName());
ofNullable(emptyToNull(dto.getDescription())).ifPresent(project::setDescription);
data.projectLinksFor(dto.getUuid()).stream()
.map(ProjectLinkDtoToWs.INSTANCE)
.forEach(project::addLinks);
String mainBranchUuid = data.mainBranchUuidForProjectUuid(dto.getUuid());
data.lastSnapshot(mainBranchUuid).ifPresent(s -> {
project.setLastAnalysisDate(formatDateTime(s.getCreatedAt()));
ofNullable(s.getRevision()).ifPresent(project::setRevision);
});
data.qualityGateStatusFor(mainBranchUuid).ifPresent(project::setQualityGate);
return project.build();
}
}
private enum ProjectLinkDtoToWs implements Function<ProjectLinkDto, Link> {
INSTANCE;
@Override
public Link apply(ProjectLinkDto dto) {
Link.Builder link = Link.newBuilder();
link.setHref(dto.getHref());
if (!isNullOrEmpty(dto.getName())) {
link.setName(dto.getName());
}
if (!isNullOrEmpty(dto.getType())) {
link.setType(dto.getType());
}
return link.build();
}
}
private SearchMyProjectsData load(DbSession dbSession, SearchMyProjectsRequest request) {
SearchMyProjectsData.Builder data = builder();
ProjectsResult searchResult = searchProjects(dbSession, request);
List<ProjectDto> projects = searchResult.projects;
List<String> projectUuids = projects.stream().map(ProjectDto::getUuid).toList();
List<ProjectLinkDto> projectLinks = dbClient.projectLinkDao().selectByProjectUuids(dbSession, projectUuids);
List<BranchDto> branches = searchResult.branches;
Set<String> mainBranchUuids = branches.stream().map(BranchDto::getUuid).collect(Collectors.toSet());
List<SnapshotDto> snapshots = dbClient.snapshotDao()
.selectLastAnalysesByRootComponentUuids(dbSession, mainBranchUuids);
List<LiveMeasureDto> qualityGates = dbClient.liveMeasureDao()
.selectByComponentUuidsAndMetricKeys(dbSession, mainBranchUuids, singletonList(CoreMetrics.ALERT_STATUS_KEY));
data
.setProjects(projects)
.setBranches(searchResult.branches)
.setProjectLinks(projectLinks)
.setSnapshots(snapshots)
.setQualityGates(qualityGates)
.setTotalNbOfProjects(searchResult.total);
return data.build();
}
private ProjectsResult searchProjects(DbSession dbSession, SearchMyProjectsRequest request) {
String userUuid = requireNonNull(userSession.getUuid(), "Current user must be authenticated");
List<String> entitiesUuid = dbClient.roleDao().selectEntityUuidsByPermissionAndUserUuidAndQualifier(dbSession, UserRole.ADMIN, userUuid, Set.of(Qualifiers.PROJECT));
ImmutableSet<String> subSetEntityUuids = ImmutableSet.copyOf(entitiesUuid.subList(0, Math.min(entitiesUuid.size(), DatabaseUtils.PARTITION_SIZE_FOR_ORACLE)));
Pagination pagination = Pagination.forPage(request.page).andSize(request.pageSize);
List<ProjectDto> projectDtos = dbClient.projectDao().selectByUuids(dbSession, subSetEntityUuids, pagination);
List<BranchDto> branchDtos = dbClient.branchDao().selectMainBranchesByProjectUuids(dbSession, projectDtos.stream().map(ProjectDto::getUuid).collect(Collectors.toSet()));
return new ProjectsResult(projectDtos, branchDtos, subSetEntityUuids.size());
}
private static class ProjectsResult {
private final List<ProjectDto> projects;
private final List<BranchDto> branches;
private final int total;
private ProjectsResult(List<ProjectDto> projects, List<BranchDto> branches, int total) {
this.projects = projects;
this.branches = branches;
assertThatAllCollectionsHaveSameSize(projects, branches);
this.total = total;
}
private static void assertThatAllCollectionsHaveSameSize(List<ProjectDto> projects, List<BranchDto> branches) {
if (projects.size() != branches.size()) {
throw new IllegalStateException("There must be the same number of projects as the branches.");
}
}
}
private static class SearchMyProjectsRequest {
private final Integer page;
private final Integer pageSize;
private SearchMyProjectsRequest(Builder builder) {
this.page = builder.page;
this.pageSize = builder.pageSize;
}
@CheckForNull
public Integer getPage() {
return page;
}
@CheckForNull
public Integer getPageSize() {
return pageSize;
}
public static Builder builder() {
return new Builder();
}
}
private static class Builder {
private Integer page;
private Integer pageSize;
private Builder() {
// enforce method constructor
}
public Builder setPage(@Nullable Integer page) {
this.page = page;
return this;
}
public Builder setPageSize(@Nullable Integer pageSize) {
this.pageSize = pageSize;
return this;
}
public SearchMyProjectsRequest build() {
return new SearchMyProjectsRequest(this);
}
}
}
| 10,040 | 34.480565 | 173 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/SearchMyProjectsData.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.project.ws;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ListMultimap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ProjectLinkDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.project.ProjectDto;
import static com.google.common.collect.ImmutableList.copyOf;
import static java.util.Objects.requireNonNull;
import static java.util.function.Function.identity;
class SearchMyProjectsData {
private final List<ProjectDto> projects;
private final Map<String, String> branchUuidByProjectUuids;
private final ListMultimap<String, ProjectLinkDto> projectLinksByProjectUuid;
private final Map<String, SnapshotDto> snapshotsByComponentUuid;
private final Map<String, String> qualityGateStatuses;
private final int totalNbOfProject;
private SearchMyProjectsData(Builder builder) {
this.projects = copyOf(builder.projects);
this.branchUuidByProjectUuids = buildBranchUuidByProjectUuidMap(builder.branches);
this.projectLinksByProjectUuid = buildProjectLinks(builder.projectLinks);
this.snapshotsByComponentUuid =builder.snapshots.stream().collect(Collectors.toMap(SnapshotDto::getRootComponentUuid, identity()));
this.qualityGateStatuses = buildQualityGateStatuses(builder.qualityGates);
this.totalNbOfProject = builder.totalNbOfProjects;
}
static Builder builder() {
return new Builder();
}
List<ProjectDto> projects() {
return projects;
}
List<ProjectLinkDto> projectLinksFor(String projectUuid) {
return projectLinksByProjectUuid.get(projectUuid);
}
Optional<SnapshotDto> lastSnapshot(String componentUuid) {
return Optional.ofNullable(snapshotsByComponentUuid.get(componentUuid));
}
Optional<String> qualityGateStatusFor(String componentUuid) {
return Optional.ofNullable(qualityGateStatuses.get(componentUuid));
}
int totalNbOfProjects() {
return totalNbOfProject;
}
private static ListMultimap<String, ProjectLinkDto> buildProjectLinks(List<ProjectLinkDto> dtos) {
ImmutableListMultimap.Builder<String, ProjectLinkDto> projectLinks = ImmutableListMultimap.builder();
dtos.forEach(projectLink -> projectLinks.put(projectLink.getProjectUuid(), projectLink));
return projectLinks.build();
}
private static Map<String, String> buildBranchUuidByProjectUuidMap(List<BranchDto> branches) {
return branches.stream().collect(Collectors.toMap(BranchDto::getProjectUuid, BranchDto::getUuid));
}
private static Map<String, String> buildQualityGateStatuses(List<LiveMeasureDto> measures) {
return ImmutableMap.copyOf(measures.stream()
.collect(Collectors.toMap(LiveMeasureDto::getComponentUuid, LiveMeasureDto::getDataAsString)));
}
public String mainBranchUuidForProjectUuid(String projectUuid) {
String branchUuid = branchUuidByProjectUuids.get(projectUuid);
if(branchUuid==null){
throw new IllegalStateException("Project must have a corresponding main branch.");
}
return branchUuid;
}
static class Builder {
private List<ProjectDto> projects;
private List<BranchDto> branches;
private List<ProjectLinkDto> projectLinks;
private List<SnapshotDto> snapshots;
private List<LiveMeasureDto> qualityGates;
private Integer totalNbOfProjects;
private Builder() {
// enforce method constructor
}
Builder setProjects(List<ProjectDto> projects) {
this.projects = projects;
return this;
}
Builder setBranches(List<BranchDto> branches) {
this.branches = branches;
return this;
}
public Builder setProjectLinks(List<ProjectLinkDto> projectLinks) {
this.projectLinks = projectLinks;
return this;
}
public Builder setSnapshots(List<SnapshotDto> snapshots) {
this.snapshots = snapshots;
return this;
}
public Builder setQualityGates(List<LiveMeasureDto> qGateStatuses) {
this.qualityGates = qGateStatuses;
return this;
}
public Builder setTotalNbOfProjects(Integer totalNbOfProjects) {
this.totalNbOfProjects = totalNbOfProjects;
return this;
}
SearchMyProjectsData build() {
requireNonNull(projects);
requireNonNull(branches);
requireNonNull(projectLinks);
requireNonNull(snapshots);
requireNonNull(qualityGates);
requireNonNull(totalNbOfProjects);
return new SearchMyProjectsData(this);
}
}
}
| 5,513 | 33.037037 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/SearchMyScannableProjectsAction.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.project.ws;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService.NewAction;
import org.sonar.api.server.ws.WebService.NewController;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonarqube.ws.Projects.SearchMyScannableProjectsResponse.Project;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.server.project.ws.ProjectFinder.SearchResult;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonarqube.ws.Projects.SearchMyScannableProjectsResponse;
public class SearchMyScannableProjectsAction implements ProjectsWsAction {
private final DbClient dbClient;
private final ProjectFinder projectFinder;
public SearchMyScannableProjectsAction(DbClient dbClient, ProjectFinder projectFinder) {
this.dbClient = dbClient;
this.projectFinder = projectFinder;
}
@Override
public void define(NewController controller) {
NewAction action = controller.createAction("search_my_scannable_projects")
.setDescription("List projects that a user can scan.")
.setSince("9.5")
.setInternal(true)
.setResponseExample(getClass().getResource("search-my-scannable-projects-example.json"))
.setHandler(this);
action.createSearchQuery("project", "project names");
}
@Override
public void handle(Request request, Response response) {
try (DbSession dbSession = dbClient.openSession(false)) {
String query = request.param(TEXT_QUERY);
SearchResult searchResult = projectFinder.search(dbSession, query);
SearchMyScannableProjectsResponse.Builder searchProjects = SearchMyScannableProjectsResponse.newBuilder();
searchResult.getProjects().stream()
.map(p -> Project.newBuilder()
.setKey(p.getKey())
.setName(p.getName()))
.forEach(searchProjects::addProjects);
writeProtobuf(searchProjects.build(), request, response);
}
}
}
| 2,874 | 37.333333 | 112 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/SearchRequest.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.project.ws;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Collections.singletonList;
import static java.util.Objects.requireNonNull;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.MAX_PAGE_SIZE;
class SearchRequest {
private final String query;
private final List<String> qualifiers;
private final String visibility;
private final Integer page;
private final Integer pageSize;
private final String analyzedBefore;
private final boolean onProvisionedOnly;
private final List<String> projects;
public SearchRequest(Builder builder) {
this.query = builder.query;
this.qualifiers = builder.qualifiers;
this.visibility = builder.visibility;
this.page = builder.page;
this.pageSize = builder.pageSize;
this.analyzedBefore = builder.analyzedBefore;
this.onProvisionedOnly = builder.onProvisionedOnly;
this.projects = builder.projects;
}
public List<String> getQualifiers() {
return qualifiers;
}
@CheckForNull
public Integer getPage() {
return page;
}
@CheckForNull
public Integer getPageSize() {
return pageSize;
}
@CheckForNull
public String getQuery() {
return query;
}
@CheckForNull
public String getVisibility() {
return visibility;
}
@CheckForNull
public String getAnalyzedBefore() {
return analyzedBefore;
}
public boolean isOnProvisionedOnly() {
return onProvisionedOnly;
}
@CheckForNull
public List<String> getProjects() {
return projects;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private List<String> qualifiers = singletonList(Qualifiers.PROJECT);
private Integer page;
private Integer pageSize;
private String query;
private String visibility;
private String analyzedBefore;
private boolean onProvisionedOnly = false;
private List<String> projects;
public Builder setQualifiers(List<String> qualifiers) {
this.qualifiers = requireNonNull(qualifiers, "Qualifiers cannot be null");
return this;
}
public Builder setPage(@Nullable Integer page) {
this.page = page;
return this;
}
public Builder setPageSize(@Nullable Integer pageSize) {
this.pageSize = pageSize;
return this;
}
public Builder setQuery(@Nullable String query) {
this.query = query;
return this;
}
public Builder setVisibility(@Nullable String visibility) {
this.visibility = visibility;
return this;
}
public Builder setAnalyzedBefore(@Nullable String lastAnalysisBefore) {
this.analyzedBefore = lastAnalysisBefore;
return this;
}
public Builder setOnProvisionedOnly(boolean onProvisionedOnly) {
this.onProvisionedOnly = onProvisionedOnly;
return this;
}
public Builder setProjects(@Nullable List<String> projects) {
this.projects = projects;
return this;
}
public SearchRequest build() {
checkArgument(projects == null || !projects.isEmpty(), "Project key list must not be empty");
checkArgument(pageSize == null || pageSize <= MAX_PAGE_SIZE, "Page size must not be greater than %s", MAX_PAGE_SIZE);
return new SearchRequest(this);
}
}
}
| 4,308 | 27.163399 | 123 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/UpdateDefaultVisibilityAction.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.project.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.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.project.ProjectDefaultVisibility;
import org.sonar.server.project.Visibility;
import org.sonar.server.user.UserSession;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
public class UpdateDefaultVisibilityAction implements ProjectsWsAction {
static final String ACTION = "update_default_visibility";
static final String PARAM_PROJECT_VISIBILITY = "projectVisibility";
private final UserSession userSession;
private final DbClient dbClient;
private final ProjectDefaultVisibility projectDefaultVisibility;
public UpdateDefaultVisibilityAction(UserSession userSession, DbClient dbClient, ProjectDefaultVisibility projectDefaultVisibility) {
this.userSession = userSession;
this.dbClient = dbClient;
this.projectDefaultVisibility = projectDefaultVisibility;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION)
.setPost(true)
.setDescription("Update the default visibility for new projects.<br/>Requires System Administrator privileges")
.setChangelog(
new Change("7.3", "This WS used to be located at /api/organizations/update_project_visibility"))
.setInternal(true)
.setSince("6.4")
.setHandler(this);
action.createParam(PARAM_PROJECT_VISIBILITY)
.setRequired(true)
.setDescription("Default visibility for projects")
.setPossibleValues(Visibility.getLabels());
}
@Override
public void handle(Request request, Response response) throws Exception {
String newDefaultProjectVisibility = request.mandatoryParam(PARAM_PROJECT_VISIBILITY);
try (DbSession dbSession = dbClient.openSession(false)) {
if (!userSession.isSystemAdministrator()) {
throw insufficientPrivilegesException();
}
projectDefaultVisibility.set(dbSession, newDefaultProjectVisibility);
dbSession.commit();
}
response.noContent();
}
}
| 3,103 | 38.291139 | 135 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/UpdateKeyAction.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.project.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.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.component.ComponentService;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.ACTION_UPDATE_KEY;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_FROM;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_TO;
public class UpdateKeyAction implements ProjectsWsAction {
private final DbClient dbClient;
private final ComponentService componentService;
private final ComponentFinder componentFinder;
public UpdateKeyAction(DbClient dbClient, ComponentService componentService, ComponentFinder componentFinder) {
this.dbClient = dbClient;
this.componentService = componentService;
this.componentFinder = componentFinder;
}
@Override
public void define(WebService.NewController context) {
doDefine(context);
}
public WebService.NewAction doDefine(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_UPDATE_KEY)
.setDescription("Update a project all its sub-components keys.<br>" +
"Requires one of the following permissions: " +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"</ul>")
.setSince("6.1")
.setPost(true)
.setHandler(this);
action.setChangelog(
new Change("7.1", "Ability to update key of a disabled module"));
action.createParam(PARAM_FROM)
.setDescription("Project key")
.setRequired(true)
.setExampleValue("my_old_project");
action.createParam(PARAM_TO)
.setDescription("New project key")
.setRequired(true)
.setExampleValue("my_new_project");
return action;
}
@Override
public void handle(Request request, Response response) throws Exception {
String key = request.mandatoryParam(PARAM_FROM);
String newKey = request.mandatoryParam(PARAM_TO);
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = componentFinder.getProjectByKey(dbSession, key);
componentService.updateKey(dbSession, project, newKey);
}
response.noContent();
}
}
| 3,353 | 35.456522 | 113 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/ws/UpdateVisibilityAction.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.project.ws;
import java.util.Optional;
import org.sonar.api.config.Configuration;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.Uuids;
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.permission.GroupPermissionDto;
import org.sonar.db.permission.UserPermissionDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserId;
import org.sonar.server.es.Indexers;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.project.Visibility;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.client.project.ProjectsWsParameters;
import static java.util.Collections.singletonList;
import static java.util.Optional.ofNullable;
import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_DEFAULT_VALUE;
import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY;
import static org.sonar.api.web.UserRole.ADMIN;
import static org.sonar.api.web.UserRole.PUBLIC_PERMISSIONS;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_PROJECT;
import static org.sonarqube.ws.client.project.ProjectsWsParameters.PARAM_VISIBILITY;
public class UpdateVisibilityAction implements ProjectsWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final Indexers indexers;
private final UuidFactory uuidFactory;
private final Configuration configuration;
public UpdateVisibilityAction(DbClient dbClient, UserSession userSession, Indexers indexers, UuidFactory uuidFactory, Configuration configuration) {
this.dbClient = dbClient;
this.userSession = userSession;
this.indexers = indexers;
this.uuidFactory = uuidFactory;
this.configuration = configuration;
}
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ProjectsWsParameters.ACTION_UPDATE_VISIBILITY)
.setDescription("Updates visibility of a project, application or a portfolio.<br>" +
"Requires 'Project administer' permission on the specified entity")
.setSince("6.4")
.setPost(true)
.setHandler(this);
action.createParam(PARAM_PROJECT)
.setDescription("Project, application or portfolio key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001)
.setRequired(true);
action.createParam(PARAM_VISIBILITY)
.setDescription("New visibility")
.setPossibleValues(Visibility.getLabels())
.setRequired(true);
}
private void validateRequest(DbSession dbSession, EntityDto entityDto) {
boolean isGlobalAdmin = userSession.isSystemAdministrator();
boolean isProjectAdmin = userSession.hasEntityPermission(ADMIN, entityDto);
boolean allowChangingPermissionsByProjectAdmins = configuration.getBoolean(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY)
.orElse(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_DEFAULT_VALUE);
if (!isProjectAdmin || (!isGlobalAdmin && !allowChangingPermissionsByProjectAdmins)) {
throw insufficientPrivilegesException();
}
//This check likely can be removed when we remove the column 'private' from components table
checkRequest(noPendingTask(dbSession, entityDto.getKey()), "Component visibility can't be changed as long as it has background task(s) pending or in progress");
}
@Override
public void handle(Request request, Response response) throws Exception {
userSession.checkLoggedIn();
String entityKey = request.mandatoryParam(PARAM_PROJECT);
boolean changeToPrivate = Visibility.isPrivate(request.mandatoryParam(PARAM_VISIBILITY));
try (DbSession dbSession = dbClient.openSession(false)) {
EntityDto entityDto = dbClient.entityDao().selectByKey(dbSession, entityKey)
.orElseThrow(() -> BadRequestException.create("Component must be a project, a portfolio or an application"));
validateRequest(dbSession, entityDto);
if (changeToPrivate != entityDto.isPrivate()) {
setPrivateForRootComponentUuid(dbSession, entityDto, changeToPrivate);
if (changeToPrivate) {
updatePermissionsToPrivate(dbSession, entityDto);
} else {
updatePermissionsToPublic(dbSession, entityDto);
}
indexers.commitAndIndexEntities(dbSession, singletonList(entityDto), Indexers.EntityEvent.PERMISSION_CHANGE);
}
response.noContent();
}
}
private void setPrivateForRootComponentUuid(DbSession dbSession, EntityDto entity, boolean newIsPrivate) {
Optional<BranchDto> branchDto = dbClient.branchDao().selectMainBranchByProjectUuid(dbSession, entity.getUuid());
String branchUuid = branchDto.isPresent() ? branchDto.get().getUuid() : entity.getUuid();
dbClient.componentDao().setPrivateForBranchUuid(dbSession, branchUuid, newIsPrivate, entity.getKey(), entity.getQualifier(), entity.getName());
if (entity.isProjectOrApp()) {
dbClient.projectDao().updateVisibility(dbSession, entity.getUuid(), newIsPrivate);
dbClient.branchDao().selectByProjectUuid(dbSession, entity.getUuid()).stream()
.filter(branch -> !branch.isMain())
.forEach(branch -> dbClient.componentDao().setPrivateForBranchUuidWithoutAuditLog(dbSession, branch.getUuid(), newIsPrivate));
} else {
dbClient.portfolioDao().updateVisibilityByPortfolioUuid(dbSession, entity.getUuid(), newIsPrivate);
}
}
private boolean noPendingTask(DbSession dbSession, String entityKey) {
EntityDto entityDto = dbClient.entityDao().selectByKey(dbSession, entityKey).orElseThrow(() -> new IllegalStateException("Can't find entity " + entityKey));
return dbClient.ceQueueDao().selectByEntityUuid(dbSession, entityDto.getUuid()).isEmpty();
}
private void updatePermissionsToPrivate(DbSession dbSession, EntityDto entity) {
// delete project permissions for group AnyOne
dbClient.groupPermissionDao().deleteByEntityUuidForAnyOne(dbSession, entity);
// grant UserRole.CODEVIEWER and UserRole.USER to any group or user with at least one permission on project
PUBLIC_PERMISSIONS.forEach(permission -> {
dbClient.groupPermissionDao().selectGroupUuidsWithPermissionOnEntityBut(dbSession, entity.getUuid(), permission)
.forEach(group -> insertProjectPermissionOnGroup(dbSession, entity, permission, group));
dbClient.userPermissionDao().selectUserIdsWithPermissionOnEntityBut(dbSession, entity.getUuid(), permission)
.forEach(userUuid -> insertProjectPermissionOnUser(dbSession, entity, permission, userUuid));
});
}
private void insertProjectPermissionOnUser(DbSession dbSession, EntityDto entity, String permission, UserId userId) {
dbClient.userPermissionDao().insert(dbSession, new UserPermissionDto(Uuids.create(), permission, userId.getUuid(), entity.getUuid()),
entity, userId, null);
}
private void insertProjectPermissionOnGroup(DbSession dbSession, EntityDto entity, String permission, String groupUuid) {
String groupName = ofNullable(dbClient.groupDao().selectByUuid(dbSession, groupUuid)).map(GroupDto::getName).orElse(null);
dbClient.groupPermissionDao().insert(dbSession, new GroupPermissionDto()
.setUuid(uuidFactory.create())
.setEntityUuid(entity.getUuid())
.setGroupUuid(groupUuid)
.setGroupName(groupName)
.setRole(permission)
.setEntityName(entity.getName()), entity, null);
}
private void updatePermissionsToPublic(DbSession dbSession, EntityDto entity) {
PUBLIC_PERMISSIONS.forEach(permission -> {
// delete project group permission for UserRole.CODEVIEWER and UserRole.USER
dbClient.groupPermissionDao().deleteByEntityAndPermission(dbSession, permission, entity);
// delete project user permission for UserRole.CODEVIEWER and UserRole.USER
dbClient.userPermissionDao().deleteEntityPermissionOfAnyUser(dbSession, permission, entity);
});
}
}
| 9,259 | 48.518717 | 164 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/project/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.project.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 967 | 39.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/CreateEventAction.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.projectanalysis.ws;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import org.sonar.api.resources.Qualifiers;
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.System2;
import org.sonar.api.web.UserRole;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.ProjectAnalyses.CreateEventResponse;
import org.sonarqube.ws.ProjectAnalyses.Event;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Optional.ofNullable;
import static org.sonar.db.event.EventValidator.MAX_NAME_LENGTH;
import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER;
import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION;
import static org.sonar.server.projectanalysis.ws.EventCategory.fromLabel;
import static org.sonar.server.projectanalysis.ws.EventValidator.checkVersionName;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_ANALYSIS;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_CATEGORY;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_NAME;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class CreateEventAction implements ProjectAnalysesWsAction {
private final DbClient dbClient;
private final UuidFactory uuidFactory;
private final System2 system;
private final UserSession userSession;
public CreateEventAction(DbClient dbClient, UuidFactory uuidFactory, System2 system, UserSession userSession) {
this.dbClient = dbClient;
this.uuidFactory = uuidFactory;
this.system = system;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("create_event")
.setDescription("Create a project analysis event.<br>" +
"Only event of category '%s' and '%s' can be created.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer System'</li>" +
" <li>'Administer' rights on the specified project</li>" +
"</ul>",
VERSION.name(), OTHER.name())
.setSince("6.3")
.setPost(true)
.setResponseExample(getClass().getResource("create_event-example.json"))
.setHandler(this);
action.createParam(PARAM_ANALYSIS)
.setDescription("Analysis key")
.setExampleValue(Uuids.UUID_EXAMPLE_01)
.setRequired(true);
action.createParam(PARAM_CATEGORY)
.setDescription("Category")
.setDefaultValue(OTHER)
.setPossibleValues(VERSION, OTHER);
action.createParam(PARAM_NAME)
.setRequired(true)
.setMaximumLength(MAX_NAME_LENGTH)
.setDescription("Name")
.setExampleValue("5.6");
}
@Override
public void handle(Request httpRequest, Response httpResponse) throws Exception {
CreateEventRequest request = toAddEventRequest(httpRequest);
CreateEventResponse response = doHandle(request);
writeProtobuf(response, httpRequest, httpResponse);
}
private CreateEventResponse doHandle(CreateEventRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
SnapshotDto analysis = getAnalysis(dbSession, request);
ProjectDto project = getProjectOrApplication(dbSession, analysis);
checkRequest(request, project);
checkExistingDbEvents(dbSession, request, analysis);
EventDto dbEvent = insertDbEvent(dbSession, request, analysis);
return toCreateEventResponse(dbEvent);
}
}
private EventDto insertDbEvent(DbSession dbSession, CreateEventRequest request, SnapshotDto analysis) {
EventDto dbEvent = dbClient.eventDao().insert(dbSession, toDbEvent(request, analysis));
if (VERSION.equals(request.getCategory())) {
analysis.setProjectVersion(request.getName());
dbClient.snapshotDao().update(dbSession, analysis);
}
dbSession.commit();
return dbEvent;
}
private SnapshotDto getAnalysis(DbSession dbSession, CreateEventRequest request) {
return dbClient.snapshotDao().selectByUuid(dbSession, request.getAnalysis())
.orElseThrow(() -> new NotFoundException(format("Analysis '%s' not found", request.getAnalysis())));
}
private ProjectDto getProjectOrApplication(DbSession dbSession, SnapshotDto analysis) {
return dbClient.branchDao().selectByUuid(dbSession, analysis.getRootComponentUuid())
.flatMap(branch -> dbClient.projectDao().selectByUuid(dbSession, branch.getProjectUuid()))
.orElseThrow(() -> new IllegalStateException(String.format("Project of analysis '%s' not found", analysis.getUuid())));
}
private void checkRequest(CreateEventRequest request, ProjectDto project) {
userSession.checkEntityPermission(UserRole.ADMIN, project);
checkArgument(EventCategory.VERSION != request.getCategory() || Qualifiers.PROJECT.equals(project.getQualifier()), "A version event must be created on a project");
checkVersionName(request.getCategory(), request.getName());
}
private static CreateEventRequest toAddEventRequest(Request request) {
return CreateEventRequest.builder()
.setAnalysis(request.mandatoryParam(PARAM_ANALYSIS))
.setName(request.mandatoryParam(PARAM_NAME))
.setCategory(request.mandatoryParamAsEnum(PARAM_CATEGORY, EventCategory.class))
.build();
}
private EventDto toDbEvent(CreateEventRequest request, SnapshotDto analysis) {
return new EventDto()
.setUuid(uuidFactory.create())
.setAnalysisUuid(analysis.getUuid())
.setComponentUuid(analysis.getRootComponentUuid())
.setCategory(request.getCategory().getLabel())
.setName(request.getName())
.setCreatedAt(system.now())
.setDate(analysis.getCreatedAt());
}
private static CreateEventResponse toCreateEventResponse(EventDto dbEvent) {
Event.Builder wsEvent = Event.newBuilder()
.setKey(dbEvent.getUuid())
.setCategory(fromLabel(dbEvent.getCategory()).name())
.setAnalysis(dbEvent.getAnalysisUuid())
.setName(dbEvent.getName());
ofNullable(dbEvent.getDescription()).ifPresent(wsEvent::setDescription);
return CreateEventResponse.newBuilder().setEvent(wsEvent).build();
}
private void checkExistingDbEvents(DbSession dbSession, CreateEventRequest request, SnapshotDto analysis) {
List<EventDto> dbEvents = dbClient.eventDao().selectByAnalysisUuid(dbSession, analysis.getUuid());
Predicate<EventDto> similarEventExisting = filterSimilarEvents(request);
dbEvents.stream()
.filter(similarEventExisting)
.findAny()
.ifPresent(throwException(request));
}
private static Predicate<EventDto> filterSimilarEvents(CreateEventRequest request) {
switch (request.getCategory()) {
case VERSION:
return dbEvent -> VERSION.getLabel().equals(dbEvent.getCategory());
case OTHER:
return dbEvent -> OTHER.getLabel().equals(dbEvent.getCategory()) && request.getName().equals(dbEvent.getName());
default:
throw new IllegalStateException("Event category not handled: " + request.getCategory());
}
}
private static Consumer<EventDto> throwException(CreateEventRequest request) {
switch (request.getCategory()) {
case VERSION:
return dbEvent -> {
throw new IllegalArgumentException(format("A version event already exists on analysis '%s'", request.getAnalysis()));
};
case OTHER:
return dbEvent -> {
throw new IllegalArgumentException(format("An '%s' event with the same name already exists on analysis '%s'", OTHER.getLabel(), request.getAnalysis()));
};
default:
throw new IllegalStateException("Event category not handled: " + request.getCategory());
}
}
private static class CreateEventRequest {
private final String analysis;
private final EventCategory category;
private final String name;
private CreateEventRequest(Builder builder) {
analysis = builder.analysis;
category = builder.category;
name = builder.name;
}
public String getAnalysis() {
return analysis;
}
public EventCategory getCategory() {
return category;
}
public String getName() {
return name;
}
public static Builder builder() {
return new Builder();
}
}
private static class Builder {
private String analysis;
private EventCategory category = EventCategory.OTHER;
private String name;
private Builder() {
// enforce static factory method
}
public Builder setAnalysis(String analysis) {
this.analysis = analysis;
return this;
}
public Builder setCategory(EventCategory category) {
this.category = category;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public CreateEventRequest build() {
checkArgument(analysis != null, "Analysis key is required");
checkArgument(category != null, "Category is required");
checkArgument(name != null, "Name is required");
return new CreateEventRequest(this);
}
}
}
| 10,502 | 37.332117 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/DeleteAction.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.projectanalysis.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.api.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.SnapshotDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.sonar.db.component.SnapshotDto.STATUS_UNPROCESSED;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_ANALYSIS;
public class DeleteAction implements ProjectAnalysesWsAction {
private final DbClient dbClient;
private final UserSession userSession;
public DeleteAction(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("delete")
.setDescription("Delete a project analysis.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer System'</li>" +
" <li>'Administer' rights on the project of the specified analysis</li>" +
"</ul>")
.setSince("6.3")
.setPost(true)
.setHandler(this);
action.createParam(PARAM_ANALYSIS)
.setDescription("Analysis key")
.setExampleValue(Uuids.UUID_EXAMPLE_04)
.setRequired(true);
}
@Override
public void handle(Request request, Response response) throws Exception {
String analysisUuid = request.mandatoryParam(PARAM_ANALYSIS);
try (DbSession dbSession = dbClient.openSession(false)) {
SnapshotDto analysis = dbClient.snapshotDao().selectByUuid(dbSession, analysisUuid)
.orElseThrow(() -> analysisNotFoundException(analysisUuid));
if (STATUS_UNPROCESSED.equals(analysis.getStatus())) {
throw analysisNotFoundException(analysisUuid);
}
userSession.checkComponentUuidPermission(UserRole.ADMIN, analysis.getRootComponentUuid());
checkArgument(!analysis.getLast(), "The last analysis '%s' cannot be deleted", analysisUuid);
checkNotUsedInNewCodePeriod(dbSession, analysis);
analysis.setStatus(STATUS_UNPROCESSED);
dbClient.snapshotDao().update(dbSession, analysis);
dbSession.commit();
}
response.noContent();
}
private void checkNotUsedInNewCodePeriod(DbSession dbSession, SnapshotDto analysis) {
boolean isSetAsBaseline = dbClient.newCodePeriodDao().existsByProjectAnalysisUuid(dbSession, analysis.getUuid());
checkArgument(!isSetAsBaseline,
"The analysis '%s' can not be deleted because it is set as a new code period baseline", analysis.getUuid());
}
private static NotFoundException analysisNotFoundException(String analysis) {
return new NotFoundException(format("Analysis '%s' not found", analysis));
}
}
| 3,912 | 38.525253 | 117 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/DeleteEventAction.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.projectanalysis.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.api.web.UserRole;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER;
import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION;
import static org.sonar.server.projectanalysis.ws.EventValidator.checkModifiable;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_EVENT;
public class DeleteEventAction implements ProjectAnalysesWsAction {
private final DbClient dbClient;
private final UserSession userSession;
public DeleteEventAction(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("delete_event")
.setDescription("Delete a project analysis event.<br>" +
"Only event of category '%s' and '%s' can be deleted.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer System'</li>" +
" <li>'Administer' rights on the specified project</li>" +
"</ul>",
VERSION.name(), OTHER.name())
.setPost(true)
.setSince("6.3")
.setHandler(this);
action.createParam(PARAM_EVENT)
.setDescription("Event key")
.setExampleValue(Uuids.UUID_EXAMPLE_02)
.setRequired(true);
}
@Override
public void handle(Request request, Response response) throws Exception {
String eventP = request.mandatoryParam(PARAM_EVENT);
try (DbSession dbSession = dbClient.openSession(false)) {
EventDto event = getEvent(dbSession, eventP);
userSession.checkComponentUuidPermission(UserRole.ADMIN, event.getComponentUuid());
checkModifiable().accept(event);
deleteEvent(dbSession, event);
}
response.noContent();
}
private EventDto getEvent(DbSession dbSession, String event) {
return dbClient.eventDao().selectByUuid(dbSession, event)
.orElseThrow(() -> new NotFoundException(format("Event '%s' not found", event)));
}
private void deleteEvent(DbSession dbSession, EventDto dbEvent) {
if (VERSION.getLabel().equals(dbEvent.getCategory())) {
SnapshotDto analysis = dbClient.snapshotDao().selectByUuid(dbSession, dbEvent.getAnalysisUuid())
.orElseThrow(() -> new IllegalStateException(format("Analysis '%s' not found", dbEvent.getAnalysisUuid())));
checkArgument(!analysis.getLast(), "Cannot delete the version event of last analysis");
analysis.setProjectVersion(null);
dbClient.snapshotDao().update(dbSession, analysis);
}
dbClient.eventDao().delete(dbSession, dbEvent.getUuid());
dbSession.commit();
}
}
| 4,080 | 39.405941 | 116 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/EventCategory.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.projectanalysis.ws;
public enum EventCategory {
VERSION("Version"), OTHER("Other"), QUALITY_PROFILE("Profile"), QUALITY_GATE("Alert"), DEFINITION_CHANGE("Definition change");
private final String label;
EventCategory(String label) {
this.label = label;
}
public String getLabel() {
return label;
}
public static EventCategory fromLabel(String label) {
for (EventCategory category : values()) {
if (category.getLabel().equals(label)) {
return category;
}
}
throw new IllegalArgumentException("Unknown event category label '" + label + "'");
}
}
| 1,474 | 31.777778 | 128 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/EventValidator.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.projectanalysis.ws;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import java.util.Set;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventDto;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER;
import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION;
import static org.sonar.server.projectanalysis.ws.EventCategory.fromLabel;
class EventValidator {
private static final Set<String> AUTHORIZED_CATEGORIES = ImmutableSet.of(VERSION.name(), OTHER.name());
private static final String AUTHORIZED_CATEGORIES_INLINED = Joiner.on(", ").join(AUTHORIZED_CATEGORIES);
private EventValidator() {
// prevent instantiation
}
static Consumer<EventDto> checkModifiable() {
return event -> checkArgument(AUTHORIZED_CATEGORIES.contains(fromLabel(event.getCategory()).name()),
"Event of category '%s' cannot be modified. Authorized categories: %s",
EventCategory.fromLabel(event.getCategory()), AUTHORIZED_CATEGORIES_INLINED);
}
static void checkVersionName(EventCategory category, @Nullable String name) {
checkVersionName(category.getLabel(), name);
}
static void checkVersionName(@Nullable String category, @Nullable String name) {
if (VERSION.getLabel().equals(category) && name != null) {
// check against max version length defined on SnapshotDto to enforce consistency between version events and snapshot versions
checkArgument(name.length() <= SnapshotDto.MAX_VERSION_LENGTH,
"Event name length (%s) is longer than the maximum authorized (%s). '%s' was provided.", name.length(), SnapshotDto.MAX_VERSION_LENGTH, name);
}
}
}
| 2,697 | 43.229508 | 150 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/ProjectAnalysesWs.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.projectanalysis.ws;
import org.sonar.api.server.ws.WebService;
public class ProjectAnalysesWs implements WebService {
private final ProjectAnalysesWsAction[] actions;
public ProjectAnalysesWs(ProjectAnalysesWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/project_analyses")
.setDescription("Manage project analyses.")
.setSince("6.3");
for (ProjectAnalysesWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,468 | 31.644444 | 79 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/ProjectAnalysesWsAction.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.projectanalysis.ws;
import org.sonar.server.ws.WsAction;
public interface ProjectAnalysesWsAction extends WsAction {
// Marker interface
}
| 1,011 | 36.481481 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/ProjectAnalysesWsParameters.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.projectanalysis.ws;
public class ProjectAnalysesWsParameters {
public static final String PARAM_ANALYSIS = "analysis";
public static final String PARAM_CATEGORY = "category";
public static final String PARAM_NAME = "name";
public static final String PARAM_EVENT = "event";
public static final String PARAM_PROJECT = "project";
public static final String PARAM_FROM = "from";
public static final String PARAM_TO = "to";
public static final String PARAM_BRANCH = "branch";
public static final String PARAM_PULL_REQUEST = "pullRequest";
public static final String PARAM_STATUS = "statuses";
private ProjectAnalysesWsParameters() {
// static access only
}
}
| 1,552 | 39.868421 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/ProjectAnalysisWsModule.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.projectanalysis.ws;
import org.sonar.core.platform.Module;
public class ProjectAnalysisWsModule extends Module {
@Override
protected void configureModule() {
add(
ProjectAnalysesWs.class,
// actions
CreateEventAction.class,
UpdateEventAction.class,
DeleteEventAction.class,
DeleteAction.class,
SearchAction.class);
}
}
| 1,243 | 30.897436 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/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.projectanalysis.ws;
import java.util.EnumSet;
import java.util.List;
import java.util.Set;
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.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.web.UserRole;
import org.sonar.core.config.CorePropertyDefinitions;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.component.SnapshotQuery;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import org.sonar.server.ws.KeyExamples;
import org.sonarqube.ws.ProjectAnalyses;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime;
import static org.sonar.api.utils.DateUtils.parseStartingDateOrDateTime;
import static org.sonar.db.component.SnapshotDto.STATUS_LIVE_MEASURE_COMPUTED;
import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
import static org.sonar.db.component.SnapshotDto.STATUS_UNPROCESSED;
import static org.sonar.db.component.SnapshotQuery.SORT_FIELD.BY_DATE;
import static org.sonar.db.component.SnapshotQuery.SORT_ORDER.DESC;
import static org.sonar.server.projectanalysis.ws.EventCategory.OTHER;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_BRANCH;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_CATEGORY;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_FROM;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_PROJECT;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_STATUS;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_TO;
import static org.sonar.server.projectanalysis.ws.SearchRequest.DEFAULT_PAGE_SIZE;
import static org.sonar.server.ws.KeyExamples.KEY_BRANCH_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchAction implements ProjectAnalysesWsAction {
private static final Set<String> ALLOWED_QUALIFIERS = Set.of(Qualifiers.PROJECT, Qualifiers.APP, Qualifiers.VIEW);
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
public SearchAction(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("search")
.setDescription("Search a project analyses and attached events.<br>" +
"Requires the following permission: 'Browse' on the specified project. <br>" +
"For applications, it also requires 'Browse' permission on its child projects.")
.setSince("6.3")
.setResponseExample(getClass().getResource("search-example.json"))
.setChangelog(
new Change("9.0", "Add field response 'detectedCI'"),
new Change("7.5", "Add QualityGate information on Applications"))
.setHandler(this);
action.addPagingParams(DEFAULT_PAGE_SIZE, 500);
action.createParam(PARAM_PROJECT)
.setDescription("Project key")
.setRequired(true)
.setExampleValue(KeyExamples.KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_BRANCH)
.setDescription("Key of a branch")
.setSince("6.6")
.setInternal(true)
.setExampleValue(KEY_BRANCH_EXAMPLE_001);
action.createParam(PARAM_CATEGORY)
.setDescription("Event category. Filter analyses that have at least one event of the category specified.")
.setPossibleValues(EnumSet.allOf(EventCategory.class))
.setExampleValue(OTHER.name());
action.createParam(PARAM_FROM)
.setDescription("Filter analyses created after the given date (inclusive). <br>" +
"Either a date (server timezone) or datetime can be provided")
.setExampleValue("2013-05-01")
.setSince("6.5");
action.createParam(PARAM_TO)
.setDescription("Filter analyses created before the given date (inclusive). <br>" +
"Either a date (server timezone) or datetime can be provided")
.setExampleValue("2017-10-19 or 2017-10-19T13:00:00+0200")
.setSince("6.5");
action.createParam(PARAM_STATUS)
.setDescription("List of statuses of desired analysis.")
.setDefaultValue(STATUS_PROCESSED)
.setInternal(true)
.setPossibleValues(STATUS_PROCESSED, STATUS_UNPROCESSED, STATUS_LIVE_MEASURE_COMPUTED)
.setExampleValue(String.join(",", STATUS_PROCESSED, STATUS_UNPROCESSED, STATUS_LIVE_MEASURE_COMPUTED))
.setSince("9.4");
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchData searchData = load(toWsRequest(request));
ProjectAnalyses.SearchResponse searchResponse = new SearchResponseBuilder(searchData).build();
writeProtobuf(searchResponse, request, response);
}
private static SearchRequest toWsRequest(Request request) {
String category = request.param(PARAM_CATEGORY);
List<String> statuses = request.paramAsStrings(PARAM_STATUS);
return SearchRequest.builder()
.setProject(request.mandatoryParam(PARAM_PROJECT))
.setBranch(request.param(PARAM_BRANCH))
.setCategory(category == null ? null : EventCategory.valueOf(category))
.setPage(request.mandatoryParamAsInt(Param.PAGE))
.setPageSize(request.mandatoryParamAsInt(Param.PAGE_SIZE))
.setFrom(request.param(PARAM_FROM))
.setTo(request.param(PARAM_TO))
.setStatuses(statuses == null ? List.of(STATUS_PROCESSED) : statuses)
.build();
}
private SearchData load(SearchRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
SearchData.Builder searchResults = SearchData.builder(dbSession, request);
addProject(searchResults);
checkPermission(searchResults.getProject());
addManualBaseline(searchResults);
addAnalyses(searchResults);
addEvents(searchResults);
return searchResults.build();
}
}
private void addManualBaseline(SearchData.Builder data) {
dbClient.branchDao().selectByUuid(data.getDbSession(), data.getProject().uuid())
.ifPresent(branchDto -> dbClient.newCodePeriodDao().selectByBranch(
data.getDbSession(), branchDto.getProjectUuid(), branchDto.getUuid())
.ifPresent(newCodePeriodDto -> data.setManualBaseline(newCodePeriodDto.getValue())));
}
private void addAnalyses(SearchData.Builder data) {
SnapshotQuery dbQuery = new SnapshotQuery()
.setRootComponentUuid(data.getProject().uuid())
.setStatuses(data.getRequest().getStatuses())
.setSort(BY_DATE, DESC);
ofNullable(data.getRequest().getFrom()).ifPresent(from -> dbQuery.setCreatedAfter(parseStartingDateOrDateTime(from).getTime()));
ofNullable(data.getRequest().getTo()).ifPresent(to -> dbQuery.setCreatedBefore(parseEndingDateOrDateTime(to).getTime() + 1_000L));
List<SnapshotDto> snapshotDtos = dbClient.snapshotDao().selectAnalysesByQuery(data.getDbSession(), dbQuery);
var detectedCIs = dbClient.analysisPropertiesDao().selectByKeyAndAnalysisUuids(data.getDbSession(),
CorePropertyDefinitions.SONAR_ANALYSIS_DETECTEDCI,
snapshotDtos.stream().map(SnapshotDto::getUuid).toList());
data.setAnalyses(snapshotDtos);
data.setDetectedCIs(detectedCIs);
}
private void addEvents(SearchData.Builder data) {
List<String> analyses = data.getAnalyses().stream().map(SnapshotDto::getUuid).toList();
data.setEvents(dbClient.eventDao().selectByAnalysisUuids(data.getDbSession(), analyses));
data.setComponentChanges(dbClient.eventComponentChangeDao().selectByAnalysisUuids(data.getDbSession(), analyses));
}
private void checkPermission(ComponentDto project) {
userSession.checkComponentPermission(UserRole.USER, project);
if (Scopes.PROJECT.equals(project.scope()) && Qualifiers.APP.equals(project.qualifier())) {
userSession.checkChildProjectsPermission(UserRole.USER, project);
}
}
private void addProject(SearchData.Builder data) {
ComponentDto project = loadComponent(data.getDbSession(), data.getRequest());
checkArgument(Scopes.PROJECT.equals(project.scope()) && ALLOWED_QUALIFIERS.contains(project.qualifier()), "A project, portfolio or application is required");
data.setProject(project);
}
private ComponentDto loadComponent(DbSession dbSession, SearchRequest request) {
String project = request.getProject();
String branch = request.getBranch();
String pullRequest = request.getPullRequest();
return componentFinder.getByKeyAndOptionalBranchOrPullRequest(dbSession, project, branch, pullRequest);
}
}
| 9,999 | 45.948357 | 161 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/SearchData.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.projectanalysis.ws;
import com.google.common.collect.ListMultimap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.utils.Paging;
import org.sonar.core.util.stream.MoreCollectors;
import org.sonar.db.DbSession;
import org.sonar.db.component.AnalysisPropertyDto;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventComponentChangeDto;
import org.sonar.db.event.EventDto;
import static java.util.Objects.requireNonNull;
class SearchData {
final List<SnapshotDto> analyses;
final Map<String, String> detectedCIs;
final ListMultimap<String, EventDto> eventsByAnalysis;
final ListMultimap<String, EventComponentChangeDto> componentChangesByEventUuid;
final Paging paging;
@CheckForNull
private final String manualBaseline;
private SearchData(Builder builder) {
this.analyses = builder.analyses;
this.detectedCIs = builder.detectedCIs;
this.eventsByAnalysis = buildEvents(builder.events);
this.componentChangesByEventUuid = buildComponentChanges(builder.componentChanges);
this.paging = Paging
.forPageIndex(builder.getRequest().getPage())
.withPageSize(builder.getRequest().getPageSize())
.andTotal(builder.countAnalyses);
this.manualBaseline = builder.manualBaseline;
}
private static ListMultimap<String, EventDto> buildEvents(List<EventDto> events) {
return events.stream().collect(MoreCollectors.index(EventDto::getAnalysisUuid));
}
private static ListMultimap<String, EventComponentChangeDto> buildComponentChanges(List<EventComponentChangeDto> changes) {
return changes.stream().collect(MoreCollectors.index(EventComponentChangeDto::getEventUuid));
}
static Builder builder(DbSession dbSession, SearchRequest request) {
return new Builder(dbSession, request);
}
public Optional<String> getManualBaseline() {
return Optional.ofNullable(manualBaseline);
}
static class Builder {
private final DbSession dbSession;
private final SearchRequest request;
private ComponentDto project;
private List<SnapshotDto> analyses;
private Map<String, String> detectedCIs;
private int countAnalyses;
private String manualBaseline;
private List<EventDto> events;
private List<EventComponentChangeDto> componentChanges;
private Builder(DbSession dbSession, SearchRequest request) {
this.dbSession = dbSession;
this.request = request;
}
Builder setProject(ComponentDto project) {
this.project = project;
return this;
}
Builder setAnalyses(List<SnapshotDto> analyses) {
Stream<SnapshotDto> stream = analyses.stream();
// no filter by category, the pagination can be applied
if (request.getCategory() == null) {
stream = stream
.skip(Paging.offset(request.getPage(), request.getPageSize()))
.limit(request.getPageSize());
}
this.analyses = stream.toList();
this.countAnalyses = analyses.size();
return this;
}
Builder setDetectedCIs(List<AnalysisPropertyDto> detectedCIs) {
this.detectedCIs = detectedCIs.stream().collect(Collectors.toMap(AnalysisPropertyDto::getAnalysisUuid,
AnalysisPropertyDto::getValue));
return this;
}
Builder setEvents(List<EventDto> events) {
this.events = events;
return this;
}
public List<EventComponentChangeDto> getComponentChanges() {
return componentChanges;
}
Builder setComponentChanges(List<EventComponentChangeDto> componentChanges) {
this.componentChanges = componentChanges;
return this;
}
DbSession getDbSession() {
return dbSession;
}
SearchRequest getRequest() {
return request;
}
ComponentDto getProject() {
return project;
}
List<SnapshotDto> getAnalyses() {
return analyses;
}
Map<String, String> getDetectedCIs() {
return detectedCIs;
}
public Builder setManualBaseline(@Nullable String manualBaseline) {
this.manualBaseline = manualBaseline;
return this;
}
private void filterByCategory() {
ListMultimap<String, String> eventCategoriesByAnalysisUuid = events.stream()
.collect(MoreCollectors.index(EventDto::getAnalysisUuid, EventDto::getCategory));
Predicate<SnapshotDto> byCategory = a -> eventCategoriesByAnalysisUuid.get(a.getUuid()).contains(request.getCategory().getLabel());
this.countAnalyses = (int) analyses.stream().filter(byCategory).count();
this.analyses = analyses.stream()
.filter(byCategory)
.skip(Paging.offset(request.getPage(), request.getPageSize()))
.limit(request.getPageSize())
.toList();
}
SearchData build() {
requireNonNull(analyses);
requireNonNull(events);
if (request.getCategory() != null) {
filterByCategory();
}
return new SearchData(this);
}
}
}
| 6,027 | 32.303867 | 137 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/SearchRequest.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.projectanalysis.ws;
import java.util.List;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
class SearchRequest {
static final int DEFAULT_PAGE_SIZE = 100;
static final int MAX_SIZE = 500;
private final String project;
private final String branch;
private final String pullRequest;
private final EventCategory category;
private final int page;
private final int pageSize;
private final String from;
private final String to;
private final List<String> statuses;
private SearchRequest(Builder builder) {
this.project = builder.project;
this.branch = builder.branch;
this.pullRequest = builder.pullRequest;
this.category = builder.category;
this.page = builder.page;
this.pageSize = builder.pageSize;
this.from = builder.from;
this.to = builder.to;
this.statuses = builder.statuses;
}
public String getProject() {
return project;
}
@CheckForNull
public String getBranch() {
return branch;
}
@CheckForNull
public String getPullRequest() {
return pullRequest;
}
@CheckForNull
public EventCategory getCategory() {
return category;
}
public int getPage() {
return page;
}
public int getPageSize() {
return pageSize;
}
@CheckForNull
public String getFrom() {
return from;
}
@CheckForNull
public String getTo() {
return to;
}
public List<String> getStatuses() {
return statuses;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String project;
private String branch;
private String pullRequest;
private EventCategory category;
private int page = 1;
private int pageSize = DEFAULT_PAGE_SIZE;
private String from;
private String to;
private List<String> statuses;
private Builder() {
// enforce static factory method
}
public Builder setProject(String project) {
this.project = project;
return this;
}
public Builder setBranch(@Nullable String branch) {
this.branch = branch;
return this;
}
public Builder setPullRequest(@Nullable String pullRequest) {
this.pullRequest = pullRequest;
return this;
}
public Builder setCategory(@Nullable EventCategory category) {
this.category = category;
return this;
}
public Builder setPage(int page) {
this.page = page;
return this;
}
public Builder setPageSize(int pageSize) {
this.pageSize = pageSize;
return this;
}
public Builder setFrom(@Nullable String from) {
this.from = from;
return this;
}
public Builder setTo(@Nullable String to) {
this.to = to;
return this;
}
public Builder setStatuses(@Nullable List<String> statuses) {
this.statuses = statuses;
return this;
}
public SearchRequest build() {
requireNonNull(project, "Project is required");
checkArgument(pageSize <= MAX_SIZE, "Page size must be lower than or equal to " + MAX_SIZE);
return new SearchRequest(this);
}
}
}
| 4,105 | 23.586826 | 98 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/SearchResponseBuilder.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.projectanalysis.ws;
import com.google.common.collect.ListMultimap;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventComponentChangeDto;
import org.sonar.db.event.EventDto;
import org.sonarqube.ws.ProjectAnalyses;
import org.sonarqube.ws.ProjectAnalyses.Analysis;
import org.sonarqube.ws.ProjectAnalyses.Event;
import org.sonarqube.ws.ProjectAnalyses.QualityGate;
import org.sonarqube.ws.ProjectAnalyses.SearchResponse;
import static java.lang.String.format;
import static java.util.Optional.ofNullable;
import static org.sonar.api.utils.DateUtils.formatDateTime;
import static org.sonar.core.util.stream.MoreCollectors.index;
import static org.sonar.server.projectanalysis.ws.EventCategory.fromLabel;
class SearchResponseBuilder {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchResponseBuilder.class);
private final Analysis.Builder wsAnalysis;
private final Event.Builder wsEvent;
private final SearchData searchData;
private final QualityGate.Builder wsQualityGate;
private final ProjectAnalyses.DefinitionChange.Builder wsDefinitionChange;
SearchResponseBuilder(SearchData searchData) {
this.wsAnalysis = Analysis.newBuilder();
this.wsEvent = Event.newBuilder();
this.wsQualityGate = QualityGate.newBuilder();
this.wsDefinitionChange = ProjectAnalyses.DefinitionChange.newBuilder();
this.searchData = searchData;
}
SearchResponse build() {
SearchResponse.Builder wsResponse = SearchResponse.newBuilder();
addAnalyses(wsResponse);
addPagination(wsResponse);
return wsResponse.build();
}
private void addAnalyses(SearchResponse.Builder wsResponse) {
searchData.analyses.stream()
.map(this::dbToWsAnalysis)
.map(this::attachEvents)
.forEach(wsResponse::addAnalyses);
}
private Analysis.Builder dbToWsAnalysis(SnapshotDto dbAnalysis) {
var builder = wsAnalysis.clear();
builder
.setKey(dbAnalysis.getUuid())
.setDate(formatDateTime(dbAnalysis.getCreatedAt()))
.setManualNewCodePeriodBaseline(searchData.getManualBaseline().filter(dbAnalysis.getUuid()::equals).isPresent());
ofNullable(dbAnalysis.getProjectVersion()).ifPresent(builder::setProjectVersion);
ofNullable(dbAnalysis.getBuildString()).ifPresent(builder::setBuildString);
ofNullable(dbAnalysis.getRevision()).ifPresent(builder::setRevision);
ofNullable(searchData.detectedCIs.get(dbAnalysis.getUuid())).ifPresent(builder::setDetectedCI);
return builder;
}
private Analysis.Builder attachEvents(Analysis.Builder analysis) {
searchData.eventsByAnalysis.get(analysis.getKey())
.stream()
.map(this::dbToWsEvent)
.forEach(analysis::addEvents);
return analysis;
}
private Event.Builder dbToWsEvent(EventDto dbEvent) {
wsEvent.clear().setKey(dbEvent.getUuid());
ofNullable(dbEvent.getName()).ifPresent(wsEvent::setName);
ofNullable(dbEvent.getDescription()).ifPresent(wsEvent::setDescription);
ofNullable(dbEvent.getCategory()).ifPresent(cat -> wsEvent.setCategory(fromLabel(cat).name()));
if (dbEvent.getCategory() != null) {
switch (EventCategory.fromLabel(dbEvent.getCategory())) {
case DEFINITION_CHANGE:
addDefinitionChange(dbEvent);
break;
case QUALITY_GATE:
addQualityGateInformation(dbEvent);
break;
default:
break;
}
}
return wsEvent;
}
private void addQualityGateInformation(EventDto event) {
wsQualityGate.clear();
List<EventComponentChangeDto> eventComponentChangeDtos = searchData.componentChangesByEventUuid.get(event.getUuid());
if (eventComponentChangeDtos.isEmpty()) {
return;
}
if (event.getData() != null) {
try {
Gson gson = new Gson();
Data data = gson.fromJson(event.getData(), Data.class);
wsQualityGate.setStillFailing(data.isStillFailing());
wsQualityGate.setStatus(data.getStatus());
} catch (JsonSyntaxException ex) {
LOGGER.error("Unable to retrieve data from event uuid=" + event.getUuid(), ex);
return;
}
}
wsQualityGate.addAllFailing(eventComponentChangeDtos.stream()
.map(SearchResponseBuilder::toFailing)
.toList());
wsEvent.setQualityGate(wsQualityGate.build());
}
private void addDefinitionChange(EventDto event) {
wsDefinitionChange.clear();
List<EventComponentChangeDto> eventComponentChangeDtos = searchData.componentChangesByEventUuid.get(event.getUuid());
if (eventComponentChangeDtos.isEmpty()) {
return;
}
ListMultimap<String, EventComponentChangeDto> componentChangeByKey = eventComponentChangeDtos.stream()
.collect(index(EventComponentChangeDto::getComponentKey));
try {
wsDefinitionChange.addAllProjects(
componentChangeByKey.asMap().values().stream()
.map(SearchResponseBuilder::addChange)
.map(Project::toProject)
.toList()
);
wsEvent.setDefinitionChange(wsDefinitionChange.build());
} catch (IllegalStateException e) {
LOGGER.error(e.getMessage(), e);
}
}
private static Project addChange(Collection<EventComponentChangeDto> changes) {
if (changes.size() == 1) {
return addSingleChange(changes.iterator().next());
} else {
return addBranchChange(changes);
}
}
private static Project addSingleChange(EventComponentChangeDto componentChange) {
Project project = new Project()
.setKey(componentChange.getComponentKey())
.setName(componentChange.getComponentName())
.setBranch(componentChange.getComponentBranchKey());
switch (componentChange.getCategory()) {
case ADDED:
project.setChangeType("ADDED");
break;
case REMOVED:
project.setChangeType("REMOVED");
break;
default:
throw new IllegalStateException(format("Unknown change %s for eventComponentChange uuid: %s", componentChange.getCategory(), componentChange.getUuid()));
}
return project;
}
private static Project addBranchChange(Collection<EventComponentChangeDto> changes) {
if (changes.size() != 2) {
throw new IllegalStateException(format("Too many changes on same project (%d) for eventComponentChange uuids : %s",
changes.size(),
changes.stream().map(EventComponentChangeDto::getUuid).collect(Collectors.joining(","))));
}
Optional<EventComponentChangeDto> addedChange = changes.stream().filter(c -> c.getCategory().equals(EventComponentChangeDto.ChangeCategory.ADDED)).findFirst();
Optional<EventComponentChangeDto> removedChange = changes.stream().filter(c -> c.getCategory().equals(EventComponentChangeDto.ChangeCategory.REMOVED)).findFirst();
if (!addedChange.isPresent() || !removedChange.isPresent() || addedChange.equals(removedChange)) {
Iterator<EventComponentChangeDto> iterator = changes.iterator();
// We are missing two different ADDED and REMOVED changes
EventComponentChangeDto firstChange = iterator.next();
EventComponentChangeDto secondChange = iterator.next();
throw new IllegalStateException(format("Incorrect changes : [uuid=%s change=%s, branch=%s] and [uuid=%s, change=%s, branch=%s]",
firstChange.getUuid(), firstChange.getCategory().name(), firstChange.getComponentBranchKey(),
secondChange.getUuid(), secondChange.getCategory().name(), secondChange.getComponentBranchKey()));
}
return new Project()
.setName(addedChange.get().getComponentName())
.setKey(addedChange.get().getComponentKey())
.setChangeType("BRANCH_CHANGED")
.setNewBranch(addedChange.get().getComponentBranchKey())
.setOldBranch(removedChange.get().getComponentBranchKey());
}
private void addPagination(SearchResponse.Builder wsResponse) {
wsResponse.getPagingBuilder()
.setPageIndex(searchData.paging.pageIndex())
.setPageSize(searchData.paging.pageSize())
.setTotal(searchData.paging.total())
.build();
}
private static ProjectAnalyses.Failing toFailing(EventComponentChangeDto change) {
ProjectAnalyses.Failing.Builder builder = ProjectAnalyses.Failing.newBuilder()
.setKey(change.getComponentKey())
.setName(change.getComponentName());
if (change.getComponentBranchKey() != null) {
builder.setBranch(change.getComponentBranchKey());
}
return builder.build();
}
private static class Data {
private boolean stillFailing;
private String status;
public Data() {
// Empty constructor because it's used by GSon
}
boolean isStillFailing() {
return stillFailing;
}
public Data setStillFailing(boolean stillFailing) {
this.stillFailing = stillFailing;
return this;
}
String getStatus() {
return status;
}
public Data setStatus(String status) {
this.status = status;
return this;
}
}
private static class Project {
private String key;
private String name;
private String changeType;
private String branch;
private String oldBranch;
private String newBranch;
public Project setKey(String key) {
this.key = key;
return this;
}
public Project setName(String name) {
this.name = name;
return this;
}
public Project setChangeType(String changeType) {
this.changeType = changeType;
return this;
}
public Project setBranch(@Nullable String branch) {
this.branch = branch;
return this;
}
public Project setOldBranch(@Nullable String oldBranch) {
this.oldBranch = oldBranch;
return this;
}
public Project setNewBranch(@Nullable String newBranch) {
this.newBranch = newBranch;
return this;
}
private ProjectAnalyses.Project toProject() {
ProjectAnalyses.Project.Builder builder = ProjectAnalyses.Project.newBuilder();
builder
.setKey(key)
.setName(name)
.setChangeType(changeType);
ofNullable(branch).ifPresent(builder::setBranch);
ofNullable(oldBranch).ifPresent(builder::setOldBranch);
ofNullable(newBranch).ifPresent(builder::setNewBranch);
return builder.build();
}
}
}
| 11,417 | 34.459627 | 167 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/ws/UpdateEventAction.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.projectanalysis.ws;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
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.component.SnapshotDto;
import org.sonar.db.event.EventDto;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.ProjectAnalyses.Event;
import org.sonarqube.ws.ProjectAnalyses.UpdateEventResponse;
import javax.annotation.CheckForNull;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.ofNullable;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.sonar.server.projectanalysis.ws.EventValidator.checkModifiable;
import static org.sonar.server.projectanalysis.ws.EventValidator.checkVersionName;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
import static org.sonar.server.projectanalysis.ws.EventCategory.VERSION;
import static org.sonar.server.projectanalysis.ws.EventCategory.fromLabel;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_EVENT;
import static org.sonar.server.projectanalysis.ws.ProjectAnalysesWsParameters.PARAM_NAME;
public class UpdateEventAction implements ProjectAnalysesWsAction {
private final DbClient dbClient;
private final UserSession userSession;
public UpdateEventAction(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("update_event")
.setDescription("Update a project analysis event.<br>" +
"Only events of category '%s' and '%s' can be updated.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
" <li>'Administer System'</li>" +
" <li>'Administer' rights on the specified project</li>" +
"</ul>",
EventCategory.VERSION.name(), EventCategory.OTHER.name())
.setSince("6.3")
.setPost(true)
.setResponseExample(getClass().getResource("update_event-example.json"))
.setHandler(this);
action.createParam(PARAM_EVENT)
.setDescription("Event key")
.setExampleValue(Uuids.UUID_EXAMPLE_08)
.setRequired(true);
action.createParam(PARAM_NAME)
.setMaximumLength(org.sonar.db.event.EventValidator.MAX_NAME_LENGTH)
.setDescription("New name")
.setExampleValue("5.6")
.setRequired(true);
}
@Override
public void handle(Request httpRequest, Response httpResponse) throws Exception {
Stream.of(httpRequest)
.map(toUpdateEventRequest())
.map(this::doHandle)
.forEach(wsResponse -> writeProtobuf(wsResponse, httpRequest, httpResponse));
}
private UpdateEventResponse doHandle(UpdateEventRequest request) {
try (DbSession dbSession = dbClient.openSession(false)) {
EventDto event = Optional.ofNullable(getDbEvent(dbSession, request)).orElseThrow(() -> new IllegalStateException("Event not found"));
checkPermissions().accept(event);
checkModifiable().accept(event);
checkVersionNameLength(request).accept(event);
event = updateNameAndDescription(request).apply(event);
checkNonConflictingOtherEvents(dbSession).accept(event);
updateInDb(dbSession).accept(event);
return toWsResponse().apply(event);
}
}
private Consumer<EventDto> updateInDb(DbSession dbSession) {
return event -> {
dbClient.eventDao().update(dbSession, event.getUuid(), event.getName(), event.getDescription());
if (VERSION.getLabel().equals(event.getCategory())) {
SnapshotDto analysis = getAnalysis(dbSession, event);
analysis.setProjectVersion(event.getName());
dbClient.snapshotDao().update(dbSession, analysis);
}
dbSession.commit();
};
}
private EventDto getDbEvent(DbSession dbSession, UpdateEventRequest request) {
checkArgument(isNotBlank(request.getName()), "A non empty name is required");
return dbClient.eventDao().selectByUuid(dbSession, request.getEvent())
.orElseThrow(() -> new NotFoundException(format("Event '%s' not found", request.getEvent())));
}
private Consumer<EventDto> checkPermissions() {
return event -> userSession.checkComponentUuidPermission(UserRole.ADMIN, event.getComponentUuid());
}
private Consumer<EventDto> checkNonConflictingOtherEvents(DbSession dbSession) {
return candidateEvent -> {
List<EventDto> dbEvents = dbClient.eventDao().selectByAnalysisUuid(dbSession, candidateEvent.getAnalysisUuid());
Predicate<EventDto> otherEventWithSameName = otherEvent -> !candidateEvent.getUuid().equals(otherEvent.getUuid()) && otherEvent.getName().equals(candidateEvent.getName());
dbEvents.stream()
.filter(otherEventWithSameName)
.findAny()
.ifPresent(event -> {
throw new IllegalArgumentException(format("An '%s' event with the same name already exists on analysis '%s'",
candidateEvent.getCategory(),
candidateEvent.getAnalysisUuid()));
});
};
}
private static Consumer<EventDto> checkVersionNameLength(UpdateEventRequest request) {
return candidateEvent -> checkVersionName(candidateEvent.getCategory(), request.getName());
}
private SnapshotDto getAnalysis(DbSession dbSession, EventDto event) {
return dbClient.snapshotDao().selectByUuid(dbSession, event.getAnalysisUuid())
.orElseThrow(() -> new IllegalStateException(format("Analysis '%s' is not found", event.getAnalysisUuid())));
}
private static Function<EventDto, EventDto> updateNameAndDescription(UpdateEventRequest request) {
return event -> {
ofNullable(request.getName()).ifPresent(event::setName);
return event;
};
}
private static Function<EventDto, UpdateEventResponse> toWsResponse() {
return dbEvent -> {
Event.Builder wsEvent = Event.newBuilder()
.setKey(dbEvent.getUuid())
.setCategory(fromLabel(dbEvent.getCategory()).name())
.setAnalysis(dbEvent.getAnalysisUuid());
ofNullable(dbEvent.getName()).ifPresent(wsEvent::setName);
ofNullable(dbEvent.getDescription()).ifPresent(wsEvent::setDescription);
return UpdateEventResponse.newBuilder().setEvent(wsEvent).build();
};
}
private static Function<Request, UpdateEventRequest> toUpdateEventRequest() {
return request -> new UpdateEventRequest(
request.mandatoryParam(PARAM_EVENT),
request.param(PARAM_NAME));
}
private static class UpdateEventRequest {
private final String event;
private final String name;
public UpdateEventRequest(String event, String name) {
this.event = requireNonNull(event, "Event key is required");
this.name = requireNonNull(name, "Name is required");
}
public String getEvent() {
return event;
}
@CheckForNull
public String getName() {
return name;
}
}
}
| 8,277 | 39.184466 | 177 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectanalysis/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.projectanalysis.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 976 | 38.08 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectdump/ws/ExportAction.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.projectdump.ws;
import org.sonar.api.server.ws.Change;
import org.sonar.server.ce.projectdump.ExportSubmitter;
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.ce.task.CeTask;
import org.sonar.server.user.UserSession;
public class ExportAction implements ProjectDumpAction {
public static final String ACTION_KEY = "export";
private static final String PARAMETER_PROJECT_KEY = "key";
private final UserSession userSession;
private final ExportSubmitter exportSubmitter;
private final ProjectDumpWsSupport projectDumpWsSupport;
public ExportAction(ProjectDumpWsSupport projectDumpWsSupport, UserSession userSession, ExportSubmitter exportSubmitter) {
this.projectDumpWsSupport = projectDumpWsSupport;
this.userSession = userSession;
this.exportSubmitter = exportSubmitter;
}
@Override
public void define(WebService.NewController newController) {
WebService.NewAction newAction = newController.createAction(ACTION_KEY)
.setDescription("Triggers project dump so that the project can be imported to another SonarQube server " +
"(see " + ProjectDumpWs.CONTROLLER_PATH + "/import, available in Enterprise Edition). " +
"Requires the 'Administer' permission.")
.setSince("1.0")
.setPost(true)
.setHandler(this)
.setChangelog(new Change("9.2", "Moved from Enterprise Edition to Community Edition"))
.setResponseExample(getClass().getResource("example-export.json"));
newAction.createParam(PARAMETER_PROJECT_KEY)
.setRequired(true)
.setExampleValue("my_project");
}
@Override
public void handle(Request request, Response response) {
String projectKey = request.mandatoryParam(PARAMETER_PROJECT_KEY);
projectDumpWsSupport.verifyAdminOfProjectByKey(projectKey);
CeTask task = exportSubmitter.submitProjectExport(projectKey, userSession.getUuid());
try (JsonWriter writer = response.newJsonWriter()) {
CeTask.Component component = task.getComponent().get();
writer.beginObject()
.prop("taskId", task.getUuid())
.prop("projectId", component.getUuid())
.prop("projectKey", component.getKey().orElse(null))
.prop("projectName", component.getName().orElse(null))
.endObject()
.close();
}
}
}
| 3,280 | 39.506173 | 124 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectdump/ws/ProjectDumpAction.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.projectdump.ws;
import org.sonar.server.ws.WsAction;
public interface ProjectDumpAction extends WsAction {
}
| 980 | 35.333333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectdump/ws/ProjectDumpWs.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.projectdump.ws;
import com.google.common.collect.ImmutableList;
import java.util.List;
import org.sonar.api.server.ws.WebService;
public class ProjectDumpWs implements WebService {
public static final String CONTROLLER_PATH = "api/project_dump";
private final List<ProjectDumpAction> actions;
public ProjectDumpWs(ProjectDumpAction... actions) {
this.actions = ImmutableList.copyOf(actions);
}
@Override
public void define(Context context) {
NewController controller = context.createController(CONTROLLER_PATH)
.setDescription("Project export/import")
.setSince("1.0");
for (ProjectDumpAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,592 | 32.1875 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectdump/ws/ProjectDumpWsSupport.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.projectdump.ws;
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.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
@ServerSide
public class ProjectDumpWsSupport {
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
public ProjectDumpWsSupport(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
}
public void verifyAdminOfProjectByKey(String projectKey) {
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey);
userSession.checkEntityPermission(UserRole.ADMIN, project);
}
}
}
| 1,838 | 35.78 | 108 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectdump/ws/StatusAction.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.projectdump.ws;
import java.io.File;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.annotation.Nullable;
import org.sonar.api.config.Configuration;
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.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.StringUtils.isNotBlank;
import static org.sonar.core.util.Slug.slugify;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.db.DatabaseUtils.closeQuietly;
import static org.sonar.process.ProcessProperties.Property.PATH_DATA;
import static org.sonar.server.component.ComponentFinder.ParamNames.ID_AND_KEY;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
public class StatusAction implements ProjectDumpAction {
private static final String PARAM_PROJECT_KEY = "key";
private static final String PARAM_PROJECT_ID = "id";
private static final String DUMP_FILE_EXTENSION = ".zip";
private static final String GOVERNANCE_DIR_NAME = "governance";
private static final String PROJECT_DUMPS_DIR_NAME = "project_dumps";
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final String dataPath;
private final File importDir;
private final File exportDir;
public StatusAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, Configuration config) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
this.dataPath = config.get(PATH_DATA.getKey()).get();
this.importDir = this.getProjectDumpDir("import");
this.exportDir = this.getProjectDumpDir("export");
}
@Override
public void define(WebService.NewController controller) {
WebService.NewAction action = controller.createAction("status")
.setDescription("Provide the import and export status of a project. Permission 'Administer' is required. " +
"The project id or project key must be provided.")
.setSince("1.0")
.setInternal(true)
.setPost(false)
.setHandler(this)
.setResponseExample(getClass().getResource("example-status.json"));
action.createParam(PARAM_PROJECT_ID)
.setDescription("Project id")
.setExampleValue(UUID_EXAMPLE_01);
action.createParam(PARAM_PROJECT_KEY)
.setDescription("Project key")
.setExampleValue("my_project");
}
@Override
public void handle(Request request, Response response) throws Exception {
String uuid = request.param(PARAM_PROJECT_ID);
String key = request.param(PARAM_PROJECT_KEY);
checkRequest(uuid == null ^ key == null, "Project id or project key must be provided, not both.");
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = getProject(dbSession, uuid, key);
userSession.checkEntityPermission(UserRole.ADMIN, project);
WsResponse wsResponse = new WsResponse();
checkDumps(project, wsResponse);
SnapshotsStatus snapshots = checkSnapshots(dbSession, project);
if (snapshots.hasLast) {
wsResponse.setCanBeExported();
} else if (!snapshots.hasAny) {
wsResponse.setCanBeImported();
}
write(response, wsResponse);
}
}
private SnapshotsStatus checkSnapshots(DbSession dbSession, ProjectDto project) throws SQLException {
PreparedStatement stmt = null;
ResultSet rs = null;
try {
String sql = "select" +
" count(*), islast" +
" from snapshots" +
" where" +
" root_component_uuid = ?" +
" group by" +
" islast";
stmt = dbClient.getMyBatis().newScrollingSelectStatement(dbSession, sql);
stmt.setString(1, project.getUuid());
rs = stmt.executeQuery();
SnapshotsStatus res = new SnapshotsStatus();
while (rs.next()) {
long count = rs.getLong(1);
boolean isLast = rs.getBoolean(2);
if (isLast) {
res.setHasLast(count > 0);
}
if (count > 0) {
res.setHasAny(true);
}
}
return res;
} finally {
closeQuietly(rs);
closeQuietly(stmt);
}
}
private File getProjectDumpDir(String type) {
final File governanceDir = new File(this.dataPath, GOVERNANCE_DIR_NAME);
final File projectDumpDir = new File(governanceDir, PROJECT_DUMPS_DIR_NAME);
return new File(projectDumpDir, type);
}
private void checkDumps(ProjectDto project, WsResponse wsResponse) {
String fileName = slugify(project.getKey()) + DUMP_FILE_EXTENSION;
final File importFile = new File(this.importDir, fileName);
final File exportFile = new File(this.exportDir, fileName);
if (importFile.exists() && importFile.isFile()) {
wsResponse.setDumpToImport(importFile.toPath().toString());
}
if (exportFile.exists() && exportFile.isFile()) {
wsResponse.setExportedDump(exportFile.toPath().toString());
}
}
private static void write(Response response, WsResponse wsResponse) {
JsonWriter jsonWriter = response.newJsonWriter();
jsonWriter
.beginObject()
.prop("canBeExported", wsResponse.canBeExported)
.prop("canBeImported", wsResponse.canBeImported)
.prop("exportedDump", wsResponse.exportedDump)
.prop("dumpToImport", wsResponse.dumpToImport)
.endObject();
jsonWriter.close();
}
private static class WsResponse {
private String exportedDump = null;
private String dumpToImport = null;
private boolean canBeExported = false;
private boolean canBeImported = false;
public void setExportedDump(String exportedDump) {
checkArgument(isNotBlank(exportedDump), "exportedDump can not be null nor empty");
this.exportedDump = exportedDump;
}
public void setDumpToImport(String dumpToImport) {
checkArgument(isNotBlank(dumpToImport), "dumpToImport can not be null nor empty");
this.dumpToImport = dumpToImport;
}
public void setCanBeExported() {
this.canBeExported = true;
}
public void setCanBeImported() {
this.canBeImported = true;
}
}
private static class SnapshotsStatus {
private boolean hasLast = false;
private boolean hasAny = false;
public void setHasLast(boolean hasLast) {
this.hasLast = hasLast;
}
public void setHasAny(boolean hasAny) {
this.hasAny = hasAny;
}
}
private ProjectDto getProject(DbSession dbSession, @Nullable String uuid, @Nullable String key) {
return componentFinder.getProjectByUuidOrKey(dbSession, uuid, key, ID_AND_KEY);
}
}
| 7,887 | 34.531532 | 122 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectdump/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.projectdump.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 39.5 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/ws/CreateAction.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.projectlink.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.api.web.UserRole;
import org.sonar.core.util.UuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ProjectLinkDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.ProjectLinks;
import org.sonarqube.ws.ProjectLinks.CreateWsResponse;
import static org.sonar.core.util.Slug.slugify;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.ACTION_CREATE;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_NAME;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_ID;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_KEY;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_URL;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class CreateAction implements ProjectLinksWsAction {
private static final int LINK_NAME_MAX_LENGTH = 128;
private static final int LINK_URL_MAX_LENGTH = 2048;
private static final int LINK_TYPE_MAX_LENGTH = 20;
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
private final UuidFactory uuidFactory;
public CreateAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder, UuidFactory uuidFactory) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
this.uuidFactory = uuidFactory;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_CREATE)
.setDescription("Create a new project link.<br>" +
"Requires 'Administer' permission on the specified project, " +
"or global 'Administer' permission.")
.setHandler(this)
.setPost(true)
.setResponseExample(getClass().getResource("create-example.json"))
.setSince("6.1");
action.createParam(PARAM_PROJECT_ID)
.setDescription("Project id")
.setExampleValue(UUID_EXAMPLE_01);
action.createParam(PARAM_PROJECT_KEY)
.setDescription("Project key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
action.createParam(PARAM_NAME)
.setRequired(true)
.setMaximumLength(LINK_NAME_MAX_LENGTH)
.setDescription("Link name")
.setExampleValue("Custom");
action.createParam(PARAM_URL)
.setRequired(true)
.setMaximumLength(LINK_URL_MAX_LENGTH)
.setDescription("Link url")
.setExampleValue("http://example.com");
}
@Override
public void handle(Request request, Response response) throws Exception {
CreateRequest searchWsRequest = toCreateWsRequest(request);
CreateWsResponse createWsResponse = doHandle(searchWsRequest);
writeProtobuf(createWsResponse, request, response);
}
private CreateWsResponse doHandle(CreateRequest createWsRequest) {
String name = createWsRequest.getName();
String url = createWsRequest.getUrl();
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = getProject(dbSession, createWsRequest);
userSession.checkEntityPermission(UserRole.ADMIN, project);
ProjectLinkDto link = new ProjectLinkDto()
.setUuid(uuidFactory.create())
.setProjectUuid(project.getUuid())
.setName(name)
.setHref(url)
.setType(nameToType(name));
dbClient.projectLinkDao().insert(dbSession, link);
dbSession.commit();
return buildResponse(link);
}
}
private static CreateWsResponse buildResponse(ProjectLinkDto link) {
return CreateWsResponse.newBuilder().setLink(ProjectLinks.Link.newBuilder()
.setId(String.valueOf(link.getUuid()))
.setName(link.getName())
.setType(link.getType())
.setUrl(link.getHref()))
.build();
}
private ProjectDto getProject(DbSession dbSession, CreateRequest request) {
return componentFinder.getProjectByUuidOrKey(
dbSession,
request.getProjectId(),
request.getProjectKey(),
ComponentFinder.ParamNames.PROJECT_ID_AND_KEY);
}
private static CreateRequest toCreateWsRequest(Request request) {
return new CreateRequest()
.setProjectId(request.param(PARAM_PROJECT_ID))
.setProjectKey(request.param(PARAM_PROJECT_KEY))
.setName(request.mandatoryParam(PARAM_NAME))
.setUrl(request.mandatoryParam(PARAM_URL));
}
private static String nameToType(String name) {
String slugified = slugify(name);
return slugified.substring(0, Math.min(slugified.length(), LINK_TYPE_MAX_LENGTH));
}
private static class CreateRequest {
private String name;
private String projectId;
private String projectKey;
private String url;
public CreateRequest setName(String name) {
this.name = name;
return this;
}
public String getName() {
return name;
}
public CreateRequest setProjectId(String projectId) {
this.projectId = projectId;
return this;
}
public String getProjectId() {
return projectId;
}
public CreateRequest setProjectKey(String projectKey) {
this.projectKey = projectKey;
return this;
}
public String getProjectKey() {
return projectKey;
}
public CreateRequest setUrl(String url) {
this.url = url;
return this;
}
public String getUrl() {
return url;
}
}
}
| 6,697 | 32.828283 | 125 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/ws/DeleteAction.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.projectlink.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.api.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ProjectLinkDto;
import org.sonar.server.exceptions.BadRequestException;
import org.sonar.server.exceptions.NotFoundException;
import org.sonar.server.user.UserSession;
import static org.sonar.db.component.ProjectLinkDto.PROVIDED_TYPES;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.ACTION_DELETE;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_ID;
public class DeleteAction implements ProjectLinksWsAction {
private final DbClient dbClient;
private final UserSession userSession;
public DeleteAction(DbClient dbClient, UserSession userSession) {
this.dbClient = dbClient;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_DELETE)
.setDescription("Delete existing project link.<br>" +
"Requires 'Administer' permission on the specified project, " +
"or global 'Administer' permission.")
.setHandler(this)
.setPost(true)
.setSince("6.1");
action.createParam(PARAM_ID)
.setRequired(true)
.setDescription("Link id")
.setExampleValue("17");
}
@Override
public void handle(Request request, Response response) throws Exception {
doHandle(request.mandatoryParam(PARAM_ID));
response.noContent();
}
private void doHandle(String id) {
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectLinkDto link = dbClient.projectLinkDao().selectByUuid(dbSession, id);
link = NotFoundException.checkFound(link, "Link with id '%s' not found", id);
checkProjectAdminPermission(link);
checkNotProvided(link);
dbClient.projectLinkDao().delete(dbSession, link.getUuid());
dbSession.commit();
}
}
private static void checkNotProvided(ProjectLinkDto link) {
String type = link.getType();
boolean isProvided = type != null && PROVIDED_TYPES.contains(type);
BadRequestException.checkRequest(!isProvided, "Provided link cannot be deleted.");
}
private void checkProjectAdminPermission(ProjectLinkDto link) {
userSession.checkComponentUuidPermission(UserRole.ADMIN, link.getProjectUuid());
}
}
| 3,356 | 35.89011 | 86 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/ws/ProjectLinksModule.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.projectlink.ws;
import org.sonar.core.platform.Module;
public class ProjectLinksModule extends Module {
@Override
protected void configureModule() {
add(
ProjectLinksWs.class,
// actions
SearchAction.class,
CreateAction.class,
DeleteAction.class);
}
}
| 1,164 | 30.486486 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/ws/ProjectLinksWs.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.projectlink.ws;
import org.sonar.api.server.ws.WebService;
public class ProjectLinksWs implements WebService {
private final ProjectLinksWsAction[] actions;
public ProjectLinksWs(ProjectLinksWsAction... actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/project_links")
.setDescription("Manage projects links.")
.setSince("6.1");
for (ProjectLinksWsAction action : actions) {
action.define(controller);
}
controller.done();
}
}
| 1,444 | 31.111111 | 76 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/ws/ProjectLinksWsAction.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.projectlink.ws;
import org.sonar.server.ws.WsAction;
public interface ProjectLinksWsAction extends WsAction {
// Marker interface
}
| 1,005 | 34.928571 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/ws/ProjectLinksWsParameters.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.projectlink.ws;
public class ProjectLinksWsParameters {
//actions
public static final String ACTION_SEARCH = "search";
public static final String ACTION_CREATE = "create";
public static final String ACTION_DELETE = "delete";
// parameters
public static final String PARAM_PROJECT_ID = "projectId";
public static final String PARAM_PROJECT_KEY = "projectKey";
public static final String PARAM_ID = "id";
public static final String PARAM_NAME = "name";
public static final String PARAM_URL = "url";
private ProjectLinksWsParameters() {
// static utility class
}
}
| 1,462 | 35.575 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/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.projectlink.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.web.UserRole;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.ProjectLinkDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.user.UserSession;
import org.sonarqube.ws.ProjectLinks.Link;
import org.sonarqube.ws.ProjectLinks.SearchWsResponse;
import static java.util.Optional.ofNullable;
import static org.sonar.core.util.Uuids.UUID_EXAMPLE_01;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.ACTION_SEARCH;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_ID;
import static org.sonar.server.projectlink.ws.ProjectLinksWsParameters.PARAM_PROJECT_KEY;
import static org.sonar.server.user.AbstractUserSession.insufficientPrivilegesException;
import static org.sonar.server.ws.KeyExamples.KEY_PROJECT_EXAMPLE_001;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchAction implements ProjectLinksWsAction {
private final DbClient dbClient;
private final UserSession userSession;
private final ComponentFinder componentFinder;
public SearchAction(DbClient dbClient, UserSession userSession, ComponentFinder componentFinder) {
this.dbClient = dbClient;
this.userSession = userSession;
this.componentFinder = componentFinder;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction(ACTION_SEARCH)
.setDescription("List links of a project.<br>" +
"The '%s' or '%s' must be provided.<br>" +
"Requires one of the following permissions:" +
"<ul>" +
"<li>'Administer System'</li>" +
"<li>'Administer' rights on the specified project</li>" +
"<li>'Browse' on the specified project</li>" +
"</ul>",
PARAM_PROJECT_ID, PARAM_PROJECT_KEY)
.setHandler(this)
.setResponseExample(getClass().getResource("search-example.json"))
.setSince("6.1");
action.createParam(PARAM_PROJECT_ID)
.setDescription("Project Id")
.setExampleValue(UUID_EXAMPLE_01);
action.createParam(PARAM_PROJECT_KEY)
.setDescription("Project Key")
.setExampleValue(KEY_PROJECT_EXAMPLE_001);
}
@Override
public void handle(Request request, Response response) throws Exception {
SearchRequest searchWsRequest = toSearchWsRequest(request);
SearchWsResponse searchWsResponse = doHandle(searchWsRequest);
writeProtobuf(searchWsResponse, request, response);
}
private SearchWsResponse doHandle(SearchRequest searchWsRequest) {
try (DbSession dbSession = dbClient.openSession(false)) {
ProjectDto project = getProjectByUuidOrKey(dbSession, searchWsRequest);
List<ProjectLinkDto> links = dbClient.projectLinkDao()
.selectByProjectUuid(dbSession, project.getUuid());
return buildResponse(links);
}
}
private static SearchWsResponse buildResponse(List<ProjectLinkDto> links) {
return SearchWsResponse.newBuilder()
.addAllLinks(links.stream()
.map(SearchAction::buildLink)
.toList())
.build();
}
private static Link buildLink(ProjectLinkDto link) {
Link.Builder builder = Link.newBuilder()
.setId(String.valueOf(link.getUuid()))
.setType(link.getType())
.setUrl(link.getHref());
ofNullable(link.getName()).ifPresent(builder::setName);
return builder.build();
}
private ProjectDto getProjectByUuidOrKey(DbSession dbSession, SearchRequest request) {
ProjectDto project = componentFinder.getProjectByUuidOrKey(
dbSession,
request.getProjectId(),
request.getProjectKey(),
ComponentFinder.ParamNames.PROJECT_ID_AND_KEY);
if (!userSession.hasEntityPermission(UserRole.ADMIN, project) &&
!userSession.hasEntityPermission(UserRole.USER, project)) {
throw insufficientPrivilegesException();
}
return project;
}
private static SearchRequest toSearchWsRequest(Request request) {
return new SearchRequest()
.setProjectId(request.param(PARAM_PROJECT_ID))
.setProjectKey(request.param(PARAM_PROJECT_KEY));
}
private static class SearchRequest {
private String projectId;
private String projectKey;
public SearchRequest setProjectId(String projectId) {
this.projectId = projectId;
return this;
}
public String getProjectId() {
return projectId;
}
public SearchRequest setProjectKey(String projectKey) {
this.projectKey = projectKey;
return this;
}
public String getProjectKey() {
return projectKey;
}
}
}
| 5,704 | 35.107595 | 100 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projectlink/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.projectlink.ws;
import javax.annotation.ParametersAreNonnullByDefault;
| 971 | 39.5 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/TagsWsSupport.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.projecttag;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
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.project.ProjectDto;
import org.sonar.server.component.ComponentFinder;
import org.sonar.server.es.Indexers;
import org.sonar.server.user.UserSession;
import static java.util.Collections.singletonList;
import static org.sonar.server.es.Indexers.EntityEvent.PROJECT_TAGS_UPDATE;
import static org.sonar.server.exceptions.BadRequestException.checkRequest;
public class TagsWsSupport {
/**
* The characters allowed in project tags are lower-case
* letters, digits, plus (+), sharp (#), dash (-) and dot (.)
*/
private static final Pattern VALID_TAG_REGEXP = Pattern.compile("[a-z0-9+#\\-.]+$");
private final DbClient dbClient;
private final ComponentFinder componentFinder;
private final UserSession userSession;
private final Indexers indexers;
private final System2 system2;
public TagsWsSupport(DbClient dbClient, ComponentFinder componentFinder, UserSession userSession, Indexers indexers, System2 system2) {
this.dbClient = dbClient;
this.componentFinder = componentFinder;
this.userSession = userSession;
this.indexers = indexers;
this.system2 = system2;
}
public void updateProjectTags(DbSession dbSession, String projectKey, List<String> providedTags) {
List<String> validatedTags = checkAndUnifyTags(providedTags);
ProjectDto project = componentFinder.getProjectByKey(dbSession, projectKey);
updateTagsForProjectsOrApplication(dbSession, validatedTags, project);
}
public void updateApplicationTags(DbSession dbSession, String applicationKey, List<String> providedTags) {
List<String> validatedTags = checkAndUnifyTags(providedTags);
ProjectDto application = componentFinder.getApplicationByKey(dbSession, applicationKey);
updateTagsForProjectsOrApplication(dbSession, validatedTags, application);
}
private void updateTagsForProjectsOrApplication(DbSession dbSession, List<String> tags, ProjectDto projectOrApplication) {
userSession.checkEntityPermission(UserRole.ADMIN, projectOrApplication);
projectOrApplication.setTags(tags);
projectOrApplication.setUpdatedAt(system2.now());
dbClient.projectDao().updateTags(dbSession, projectOrApplication);
indexers.commitAndIndexEntities(dbSession, singletonList(projectOrApplication), PROJECT_TAGS_UPDATE);
}
public static List<String> checkAndUnifyTags(List<String> tags) {
return tags.stream()
.filter(StringUtils::isNotBlank)
.map(t -> t.toLowerCase(Locale.ENGLISH))
.map(TagsWsSupport::checkTag)
.distinct()
.toList();
}
private static String checkTag(String tag) {
checkRequest(VALID_TAG_REGEXP.matcher(tag).matches(), "Tag '%s' is invalid. Tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'", tag);
return tag;
}
}
| 3,902 | 40.084211 | 149 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/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.projecttag;
import javax.annotation.ParametersAreNonnullByDefault;
| 968 | 37.76 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/ws/ProjectTagsWs.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.projecttag.ws;
import java.util.List;
import org.sonar.api.server.ws.WebService;
public class ProjectTagsWs implements WebService {
private final List<ProjectTagsWsAction> actions;
public ProjectTagsWs(List<ProjectTagsWsAction> actions) {
this.actions = actions;
}
@Override
public void define(Context context) {
NewController controller = context.createController("api/project_tags")
.setDescription("Manage project tags")
.setSince("6.4");
actions.forEach(a -> a.define(controller));
controller.done();
}
}
| 1,423 | 32.116279 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/ws/ProjectTagsWsAction.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.projecttag.ws;
import org.sonar.server.ws.WsAction;
public interface ProjectTagsWsAction extends WsAction {
// marker interface
}
| 1,002 | 36.148148 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/ws/ProjectTagsWsModule.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.projecttag.ws;
import org.sonar.core.platform.Module;
import org.sonar.server.projecttag.TagsWsSupport;
public class ProjectTagsWsModule extends Module {
@Override
protected void configureModule() {
add(
TagsWsSupport.class,
ProjectTagsWs.class,
SetAction.class,
SearchAction.class
);
}
}
| 1,197 | 32.277778 | 75 | java |
sonarqube | sonarqube-master/server/sonar-webserver-webapi/src/main/java/org/sonar/server/projecttag/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.projecttag.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.server.measure.index.ProjectMeasuresIndex;
import org.sonarqube.ws.ProjectTags;
import static org.sonar.api.server.ws.WebService.Param.PAGE;
import static org.sonar.api.server.ws.WebService.Param.PAGE_SIZE;
import static org.sonar.api.server.ws.WebService.Param.TEXT_QUERY;
import static org.sonar.server.ws.WsUtils.writeProtobuf;
public class SearchAction implements ProjectTagsWsAction {
private final ProjectMeasuresIndex index;
public SearchAction(ProjectMeasuresIndex index) {
this.index = index;
}
@Override
public void define(WebService.NewController context) {
WebService.NewAction action = context.createAction("search")
.setDescription("Search tags")
.setSince("6.4")
.setResponseExample(getClass().getResource("search-example.json"))
.setChangelog(new Change("9.2", "Parameter 'page' added"))
.setHandler(this);
action.addSearchQuery("off", "tags");
action.addPagingParams(10, 100);
}
@Override
public void handle(Request request, Response response) throws Exception {
ProjectTags.SearchResponse wsResponse = doHandle(request);
writeProtobuf(wsResponse, request, response);
}
private ProjectTags.SearchResponse doHandle(Request request) {
List<String> tags = index.searchTags(request.param(TEXT_QUERY), request.mandatoryParamAsInt(PAGE), request.mandatoryParamAsInt(PAGE_SIZE));
return ProjectTags.SearchResponse.newBuilder().addAllTags(tags).build();
}
}
| 2,545 | 37.575758 | 143 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.