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-api/src/main/java/org/sonar/server/health/HealthChecker.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.health; public interface HealthChecker { /** * Perform a check of the health of the current SonarQube node, either as a standalone node or as a member * of a cluster. */ Health checkNode(); /** * Perform a check of the health of the SonarQube cluster. * * @throws IllegalStateException if clustering is not enabled. */ ClusterHealth checkCluster(); }
1,250
33.75
108
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/health/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.health; import javax.annotation.ParametersAreNonnullByDefault;
963
39.166667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/http/JavaxHttpRequest.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.http; import java.io.BufferedReader; import java.io.IOException; import java.util.Arrays; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.sonar.api.server.http.Cookie; import org.sonar.api.server.http.HttpRequest; /** * Implementation of {@link HttpRequest} based on a delegate of {@link HttpServletRequest} from the Javax Servlet API. */ public class JavaxHttpRequest implements HttpRequest { private final HttpServletRequest delegate; public JavaxHttpRequest(HttpServletRequest delegate) { this.delegate = delegate; } public HttpServletRequest getDelegate() { return delegate; } @Override public int getServerPort() { return delegate.getServerPort(); } @Override public boolean isSecure() { return delegate.isSecure(); } @Override public String getScheme() { return delegate.getScheme(); } @Override public String getServerName() { return delegate.getServerName(); } @Override public String getRequestURL() { return delegate.getRequestURL().toString(); } @Override public String getRequestURI() { return delegate.getRequestURI(); } @Override public String getQueryString() { return delegate.getQueryString(); } @Override public String getContextPath() { return delegate.getContextPath(); } @Override public String getParameter(String name) { return delegate.getParameter(name); } @Override public String[] getParameterValues(String name) { return delegate.getParameterValues(name); } @Override public String getHeader(String name) { return delegate.getHeader(name); } @Override public Enumeration<String> getHeaderNames() { return delegate.getHeaderNames(); } @Override public Enumeration<String> getHeaders(String name) { return delegate.getHeaders(name); } @Override public String getMethod() { return delegate.getMethod(); } @Override public String getRemoteAddr() { return delegate.getRemoteAddr(); } @Override public void setAttribute(String name, Object value) { delegate.setAttribute(name, value); } @Override public String getServletPath() { return delegate.getServletPath(); } @Override public BufferedReader getReader() throws IOException { return delegate.getReader(); } @Override public Cookie[] getCookies() { javax.servlet.http.Cookie[] cookies = delegate.getCookies(); if (cookies != null) { return Arrays.stream(cookies) .map(JavaxCookie::new) .toArray(Cookie[]::new); } return new Cookie[0]; } public static class JavaxCookie implements Cookie { private final javax.servlet.http.Cookie delegate; public JavaxCookie(javax.servlet.http.Cookie delegate) { this.delegate = delegate; } @Override public String getName() { return delegate.getName(); } @Override public String getValue() { return delegate.getValue(); } @Override public String getPath() { return delegate.getPath(); } @Override public boolean isSecure() { return delegate.getSecure(); } @Override public boolean isHttpOnly() { return delegate.isHttpOnly(); } @Override public int getMaxAge() { return delegate.getMaxAge(); } } }
4,221
21.945652
118
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/http/JavaxHttpResponse.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.http; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Collection; import javax.servlet.http.HttpServletResponse; import org.sonar.api.server.http.Cookie; import org.sonar.api.server.http.HttpResponse; /** * Implementation of {@link HttpResponse} based on a delegate of {@link HttpServletResponse} from the Javax Servlet API. */ public class JavaxHttpResponse implements HttpResponse { private final HttpServletResponse delegate; public JavaxHttpResponse(HttpServletResponse delegate) { this.delegate = delegate; } public HttpServletResponse getDelegate() { return delegate; } @Override public void addHeader(String name, String value) { delegate.addHeader(name, value); } @Override public String getHeader(String name) { return delegate.getHeader(name); } @Override public Collection<String> getHeaders(String name) { return delegate.getHeaders(name); } @Override public void setStatus(int status) { delegate.setStatus(status); } @Override public int getStatus() { return delegate.getStatus(); } @Override public void setContentType(String contentType) { delegate.setContentType(contentType); } @Override public PrintWriter getWriter() throws IOException { return delegate.getWriter(); } @Override public void setHeader(String name, String value) { delegate.setHeader(name, value); } @Override public void sendRedirect(String location) throws IOException { delegate.sendRedirect(location); } @Override public void addCookie(Cookie cookie) { javax.servlet.http.Cookie javaxCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue()); javaxCookie.setPath(cookie.getPath()); javaxCookie.setSecure(cookie.isSecure()); javaxCookie.setHttpOnly(cookie.isHttpOnly()); javaxCookie.setMaxAge(cookie.getMaxAge()); delegate.addCookie(javaxCookie); } @Override public OutputStream getOutputStream() throws IOException { return delegate.getOutputStream(); } @Override public void setCharacterEncoding(String charset) { delegate.setCharacterEncoding(charset); } }
3,064
26.863636
120
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/http/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.http; import javax.annotation.ParametersAreNonnullByDefault;
961
39.083333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/platform/ClusterFeature.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; import org.sonar.api.ExtensionPoint; import org.sonar.api.server.ServerSide; @ServerSide @ExtensionPoint public interface ClusterFeature { boolean isEnabled(); }
1,046
31.71875
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/platform/Platform.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; import org.sonar.core.platform.ExtensionContainer; public interface Platform { void doStart(); Status status(); ExtensionContainer getContainer(); enum Status { BOOTING, SAFEMODE, STARTING, UP } }
1,094
30.285714
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/platform/SystemInfoWriter.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; import org.sonar.api.utils.text.JsonWriter; public interface SystemInfoWriter { void write(JsonWriter json) throws Exception; }
1,010
36.444444
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/platform/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; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/DetectPluginChange.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; import java.util.Map; import java.util.stream.Collectors; import org.sonar.api.Startable; import org.sonar.api.utils.Preconditions; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.Loggers; import org.sonar.api.utils.log.Profiler; import org.sonar.core.plugin.PluginType; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.plugin.PluginDto; import static java.util.function.Function.identity; public class DetectPluginChange implements Startable { private static final Logger LOG = Loggers.get(DetectPluginChange.class); private final ServerPluginRepository serverPluginRepository; private final DbClient dbClient; private Boolean changesDetected = null; public DetectPluginChange(ServerPluginRepository serverPluginRepository, DbClient dbClient) { this.serverPluginRepository = serverPluginRepository; this.dbClient = dbClient; } @Override public void start() { Preconditions.checkState(changesDetected == null, "Can only call #start() once"); Profiler profiler = Profiler.create(LOG).startInfo("Detect plugin changes"); changesDetected = anyChange(); if (changesDetected) { LOG.debug("Plugin changes detected"); } else { LOG.info("No plugin change detected"); } profiler.stopDebug(); } /** * @throws NullPointerException if {@link #start} hasn't been called */ public boolean anyPluginChanged() { return changesDetected; } private boolean anyChange() { try (DbSession dbSession = dbClient.openSession(false)) { Map<String, PluginDto> dbPluginsByKey = dbClient.pluginDao().selectAll(dbSession).stream() .filter(p -> !p.isRemoved()) .collect(Collectors.toMap(PluginDto::getKee, identity())); Map<String, ServerPlugin> filePluginsByKey = serverPluginRepository.getPlugins().stream() .collect(Collectors.toMap(p -> p.getPluginInfo().getKey(), p -> p)); if (!dbPluginsByKey.keySet().equals(filePluginsByKey.keySet())) { return true; } for (ServerPlugin installed : filePluginsByKey.values()) { PluginDto dbPlugin = dbPluginsByKey.get(installed.getPluginInfo().getKey()); if (changed(dbPlugin, installed)) { return true; } } } return false; } private static boolean changed(PluginDto dbPlugin, ServerPlugin filePlugin) { return !dbPlugin.getFileHash().equals(filePlugin.getJar().getMd5()) || !dbPlugin.getType().equals(toTypeDto(filePlugin.getType())); } static PluginDto.Type toTypeDto(PluginType type) { switch (type) { case EXTERNAL: return PluginDto.Type.EXTERNAL; case BUNDLED: return PluginDto.Type.BUNDLED; default: throw new IllegalStateException("Unknown type: " + type); } } @Override public void stop() { // Nothing to do } }
3,746
33.063636
135
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/PluginConsentVerifier.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; import java.util.Optional; import org.sonar.api.Startable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.extension.PluginRiskConsent; import org.sonar.core.plugin.PluginType; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.PropertyDto; import static org.sonar.core.config.CorePropertyDefinitions.PLUGINS_RISK_CONSENT; import static org.sonar.core.extension.PluginRiskConsent.NOT_ACCEPTED; import static org.sonar.core.extension.PluginRiskConsent.REQUIRED; import static org.sonar.server.log.ServerProcessLogging.STARTUP_LOGGER_NAME; public class PluginConsentVerifier implements Startable { private static final Logger LOGGER = LoggerFactory.getLogger(STARTUP_LOGGER_NAME); private final ServerPluginRepository pluginRepository; private final DbClient dbClient; public PluginConsentVerifier(ServerPluginRepository pluginRepository, DbClient dbClient) { this.pluginRepository = pluginRepository; this.dbClient = dbClient; } @Override public void start() { boolean hasExternalPlugins = pluginRepository.getPlugins().stream().anyMatch(plugin -> plugin.getType().equals(PluginType.EXTERNAL)); try (DbSession session = dbClient.openSession(false)) { PropertyDto property = Optional.ofNullable(dbClient.propertiesDao().selectGlobalProperty(session, PLUGINS_RISK_CONSENT)) .orElse(defaultPluginRiskConsentProperty()); if (hasExternalPlugins && NOT_ACCEPTED == PluginRiskConsent.valueOf(property.getValue())) { addWarningInSonarDotLog(); property.setValue(REQUIRED.name()); dbClient.propertiesDao().saveProperty(session, property); session.commit(); } else if (!hasExternalPlugins && REQUIRED == PluginRiskConsent.valueOf(property.getValue())) { dbClient.propertiesDao().deleteGlobalProperty(PLUGINS_RISK_CONSENT, session); session.commit(); } } } private static PropertyDto defaultPluginRiskConsentProperty() { PropertyDto property = new PropertyDto(); property.setKey(PLUGINS_RISK_CONSENT); property.setValue(NOT_ACCEPTED.name()); return property; } private static void addWarningInSonarDotLog() { String highlighter = "####################################################################################################################"; String msg = "Plugin(s) detected. Plugins are not provided by SonarSource and are therefore installed at your own risk." + " A SonarQube administrator needs to acknowledge this risk once logged in."; LOGGER.warn(highlighter); LOGGER.warn(msg); LOGGER.warn(highlighter); } @Override public void stop() { // Nothing to do } }
3,599
39
144
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/PluginDownloader.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; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.Optional; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.Startable; import org.sonar.api.utils.HttpDownloader; import org.sonar.core.platform.PluginInfo; import org.sonar.server.platform.ServerFileSystem; import org.sonar.updatecenter.common.Release; import org.sonar.updatecenter.common.UpdateCenter; import org.sonar.updatecenter.common.Version; import static org.apache.commons.io.FileUtils.copyFile; import static org.apache.commons.io.FileUtils.copyFileToDirectory; import static org.apache.commons.io.FileUtils.forceMkdir; import static org.apache.commons.io.FileUtils.toFile; import static org.apache.commons.lang.StringUtils.substringAfterLast; import static org.sonar.core.util.FileUtils.deleteQuietly; import static org.sonar.server.exceptions.BadRequestException.checkRequest; /** * Downloads plugins from update center. Files are copied in the directory extensions/downloads and then * moved to extensions/plugins after server restart. */ public class PluginDownloader implements Startable { private static final Logger LOG = LoggerFactory.getLogger(PluginDownloader.class); private static final String TMP_SUFFIX = "tmp"; private static final String PLUGIN_EXTENSION = "jar"; private final UpdateCenterMatrixFactory updateCenterMatrixFactory; private final HttpDownloader downloader; private final File downloadDir; public PluginDownloader(UpdateCenterMatrixFactory updateCenterMatrixFactory, HttpDownloader downloader, ServerFileSystem fileSystem) { this.updateCenterMatrixFactory = updateCenterMatrixFactory; this.downloader = downloader; this.downloadDir = fileSystem.getDownloadedPluginsDir(); } /** * Deletes the temporary files remaining from previous downloads */ @Override public void start() { try { forceMkdir(downloadDir); for (File tempFile : listTempFile(this.downloadDir)) { deleteQuietly(tempFile); } } catch (IOException e) { throw new IllegalStateException("Fail to create the directory: " + downloadDir, e); } } @Override public void stop() { // Nothing to do } public void cancelDownloads() { try { if (downloadDir.exists()) { org.sonar.core.util.FileUtils.cleanDirectory(downloadDir); } } catch (IOException e) { throw new IllegalStateException("Fail to clean the plugin downloads directory: " + downloadDir, e); } } /** * @return the list of download plugins as {@link PluginInfo} instances */ public Collection<PluginInfo> getDownloadedPlugins() { return listPlugins(this.downloadDir) .stream() .map(PluginInfo::create) .toList(); } public void download(String pluginKey, Version version) { Optional<UpdateCenter> updateCenter = updateCenterMatrixFactory.getUpdateCenter(true); if (updateCenter.isPresent()) { List<Release> installablePlugins = updateCenter.get().findInstallablePlugins(pluginKey, version); checkRequest(!installablePlugins.isEmpty(), "Error while downloading plugin '%s' with version '%s'. No compatible plugin found.", pluginKey, version.getName()); for (Release release : installablePlugins) { try { downloadRelease(release); } catch (Exception e) { String message = String.format("Fail to download the plugin (%s, version %s) from %s (error is : %s)", release.getArtifact().getKey(), release.getVersion().getName(), release.getDownloadUrl(), e.getMessage()); LOG.debug(message, e); throw new IllegalStateException(message, e); } } } } private void downloadRelease(Release release) throws URISyntaxException, IOException { String url = release.getDownloadUrl(); Objects.requireNonNull(url, "Download URL should not be null"); URI uri = new URI(url); if (url.startsWith("file:")) { // used for tests File file = toFile(uri.toURL()); copyFileToDirectory(file, downloadDir); } else { String filename = substringAfterLast(uri.getPath(), "/"); if (!filename.endsWith("." + PLUGIN_EXTENSION)) { filename = release.getKey() + "-" + release.getVersion() + "." + PLUGIN_EXTENSION; } File targetFile = new File(downloadDir, filename); File tempFile = new File(downloadDir, filename + "." + TMP_SUFFIX); downloader.download(uri, tempFile); copyFile(tempFile, targetFile); deleteQuietly(tempFile); } } private static Collection<File> listTempFile(File dir) { return FileUtils.listFiles(dir, new String[] {TMP_SUFFIX}, false); } private static Collection<File> listPlugins(File dir) { return FileUtils.listFiles(dir, new String[] {PLUGIN_EXTENSION}, false); } }
5,881
36.227848
166
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/PluginFilesAndMd5.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; import java.io.File; import java.io.IOException; import java.io.InputStream; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.io.FileUtils; import static java.util.Objects.requireNonNull; @Immutable public class PluginFilesAndMd5 { private final FileAndMd5 loadedJar; @Nullable private final FileAndMd5 compressedJar; public PluginFilesAndMd5(FileAndMd5 loadedJar, @Nullable FileAndMd5 compressedJar) { this.loadedJar = requireNonNull(loadedJar); this.compressedJar = compressedJar; } public FileAndMd5 getLoadedJar() { return loadedJar; } @Nullable public FileAndMd5 getCompressedJar() { return compressedJar; } @Immutable public static class FileAndMd5 { private final File file; private final String md5; public FileAndMd5(File file) { try (InputStream fis = FileUtils.openInputStream(file)) { this.file = file; this.md5 = DigestUtils.md5Hex(fis); } catch (IOException e) { throw new IllegalStateException("Fail to compute md5 of " + file, e); } } public File getFile() { return file; } public String getMd5() { return md5; } } }
2,157
27.773333
86
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/PluginJarLoader.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; import com.google.common.base.Strings; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import javax.inject.Inject; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.SonarRuntime; import org.sonar.api.utils.MessageException; import org.sonar.core.platform.PluginInfo; import org.sonar.server.platform.ServerFileSystem; import static java.lang.String.format; import static org.apache.commons.io.FileUtils.moveFile; import static org.sonar.core.plugin.PluginType.BUNDLED; import static org.sonar.core.plugin.PluginType.EXTERNAL; import static org.sonar.core.util.FileUtils.deleteQuietly; import static org.sonar.server.log.ServerProcessLogging.STARTUP_LOGGER_NAME; public class PluginJarLoader { private static final Logger STARTUP_LOGGER = LoggerFactory.getLogger(STARTUP_LOGGER_NAME); private static final Logger LOG = LoggerFactory.getLogger(PluginJarLoader.class); // List of plugins that are silently removed if installed private static final Set<String> DEFAULT_BLACKLISTED_PLUGINS = Set.of("scmactivity", "issuesreport", "genericcoverage"); // List of plugins that should prevent the server to finish its startup private static final Set<String> FORBIDDEN_INCOMPATIBLE_PLUGINS = Set.of( "sqale", "report", "views", "authgithub", "authgitlab", "authbitbucket", "authsaml", "ldap", "scmgit", "scmsvn"); private static final String LOAD_ERROR_GENERIC_MESSAGE = "Startup failed: Plugins can't be loaded. See web logs for more information"; private final ServerFileSystem fs; private final SonarRuntime sonarRuntime; private final Set<String> blacklistedPluginKeys; @Inject public PluginJarLoader(ServerFileSystem fs, SonarRuntime sonarRuntime) { this(fs, sonarRuntime, DEFAULT_BLACKLISTED_PLUGINS); } PluginJarLoader(ServerFileSystem fs, SonarRuntime sonarRuntime, Set<String> blacklistedPluginKeys) { this.fs = fs; this.sonarRuntime = sonarRuntime; this.blacklistedPluginKeys = blacklistedPluginKeys; } /** * Load the plugins that are located in lib/extensions and extensions/plugins. Blacklisted plugins are deleted. */ public Collection<ServerPluginInfo> loadPlugins() { Map<String, ServerPluginInfo> bundledPluginsByKey = new LinkedHashMap<>(); for (ServerPluginInfo bundled : getBundledPluginsMetadata()) { failIfContains(bundledPluginsByKey, bundled, plugin -> MessageException.of(format("Found two versions of the plugin %s [%s] in the directory %s. Please remove one of %s or %s.", bundled.getName(), bundled.getKey(), getRelativeDir(fs.getInstalledBundledPluginsDir()), bundled.getNonNullJarFile().getName(), plugin.getNonNullJarFile().getName()))); bundledPluginsByKey.put(bundled.getKey(), bundled); } Map<String, ServerPluginInfo> externalPluginsByKey = new LinkedHashMap<>(); for (ServerPluginInfo external : getExternalPluginsMetadata()) { failIfContains(bundledPluginsByKey, external, plugin -> MessageException.of(format("Found a plugin '%s' in the directory '%s' with the same key [%s] as a built-in feature '%s'. Please remove '%s'.", external.getName(), getRelativeDir(fs.getInstalledExternalPluginsDir()), external.getKey(), plugin.getName(), new File(getRelativeDir(fs.getInstalledExternalPluginsDir()), external.getNonNullJarFile().getName())))); failIfContains(externalPluginsByKey, external, plugin -> MessageException.of(format("Found two versions of the plugin '%s' [%s] in the directory '%s'. Please remove %s or %s.", external.getName(), external.getKey(), getRelativeDir(fs.getInstalledExternalPluginsDir()), external.getNonNullJarFile().getName(), plugin.getNonNullJarFile().getName()))); externalPluginsByKey.put(external.getKey(), external); } for (PluginInfo downloaded : getDownloadedPluginsMetadata()) { failIfContains(bundledPluginsByKey, downloaded, plugin -> MessageException.of(format("Fail to update plugin: %s. Built-in feature with same key already exists: %s. Move or delete plugin from %s directory", plugin.getName(), plugin.getKey(), getRelativeDir(fs.getDownloadedPluginsDir())))); ServerPluginInfo installedPlugin; if (externalPluginsByKey.containsKey(downloaded.getKey())) { deleteQuietly(externalPluginsByKey.get(downloaded.getKey()).getNonNullJarFile()); installedPlugin = moveDownloadedPluginToExtensions(downloaded); LOG.info("Plugin {} [{}] updated to version {}", installedPlugin.getName(), installedPlugin.getKey(), installedPlugin.getVersion()); } else { installedPlugin = moveDownloadedPluginToExtensions(downloaded); LOG.info("Plugin {} [{}] installed", installedPlugin.getName(), installedPlugin.getKey()); } externalPluginsByKey.put(downloaded.getKey(), installedPlugin); } Map<String, ServerPluginInfo> plugins = new HashMap<>(externalPluginsByKey.size() + bundledPluginsByKey.size()); plugins.putAll(externalPluginsByKey); plugins.putAll(bundledPluginsByKey); PluginRequirementsValidator.unloadIncompatiblePlugins(plugins); return plugins.values(); } private static String getRelativeDir(File dir) { Path parent = dir.toPath().getParent().getParent(); return parent.relativize(dir.toPath()).toString(); } private static void failIfContains(Map<String, ? extends PluginInfo> map, PluginInfo value, Function<PluginInfo, RuntimeException> msg) { PluginInfo pluginInfo = map.get(value.getKey()); if (pluginInfo != null) { RuntimeException exception = msg.apply(pluginInfo); logGenericPluginLoadErrorLog(); throw exception; } } private static void logGenericPluginLoadErrorLog() { STARTUP_LOGGER.error(LOAD_ERROR_GENERIC_MESSAGE); } private List<ServerPluginInfo> getBundledPluginsMetadata() { return loadPluginsFromDir(fs.getInstalledBundledPluginsDir(), jar -> ServerPluginInfo.create(jar, BUNDLED)); } private List<ServerPluginInfo> getExternalPluginsMetadata() { return loadPluginsFromDir(fs.getInstalledExternalPluginsDir(), jar -> ServerPluginInfo.create(jar, EXTERNAL)); } private List<PluginInfo> getDownloadedPluginsMetadata() { return loadPluginsFromDir(fs.getDownloadedPluginsDir(), PluginInfo::create); } private ServerPluginInfo moveDownloadedPluginToExtensions(PluginInfo pluginInfo) { File destDir = fs.getInstalledExternalPluginsDir(); File destFile = new File(destDir, pluginInfo.getNonNullJarFile().getName()); if (destFile.exists()) { deleteQuietly(destFile); } movePlugin(pluginInfo.getNonNullJarFile(), destFile); return ServerPluginInfo.create(destFile, EXTERNAL); } private static void movePlugin(File sourcePluginFile, File destPluginFile) { try { moveFile(sourcePluginFile, destPluginFile); } catch (IOException e) { throw new IllegalStateException(format("Fail to move plugin: %s to %s", sourcePluginFile.getAbsolutePath(), destPluginFile.getAbsolutePath()), e); } } private <T extends PluginInfo> List<T> loadPluginsFromDir(File pluginsDir, Function<File, T> toPluginInfo) { List<T> list = listJarFiles(pluginsDir).stream() .map(toPluginInfo) .filter(this::checkPluginInfo) .toList(); failIfContainsIncompatiblePlugins(list); return list; } private static void failIfContainsIncompatiblePlugins(List<? extends PluginInfo> plugins) { List<String> incompatiblePlugins = plugins.stream() .filter(p -> FORBIDDEN_INCOMPATIBLE_PLUGINS.contains(p.getKey())) .map(p -> "'" + p.getKey() + "'") .sorted() .toList(); if (!incompatiblePlugins.isEmpty()) { logGenericPluginLoadErrorLog(); throw MessageException.of(String.format("The following %s no longer compatible with this version of SonarQube: %s", incompatiblePlugins.size() > 1 ? "plugins are" : "plugin is", String.join(", ", incompatiblePlugins))); } } private boolean checkPluginInfo(PluginInfo info) { String pluginKey = info.getKey(); if (blacklistedPluginKeys.contains(pluginKey)) { LOG.warn("Plugin {} [{}] is blacklisted and is being uninstalled", info.getName(), pluginKey); deleteQuietly(info.getNonNullJarFile()); return false; } if (Strings.isNullOrEmpty(info.getMainClass()) && Strings.isNullOrEmpty(info.getBasePlugin())) { LOG.warn("Plugin {} [{}] is ignored because entry point class is not defined", info.getName(), info.getKey()); return false; } if (!info.isCompatibleWith(sonarRuntime.getApiVersion().toString())) { throw MessageException.of(format("Plugin %s [%s] requires at least Sonar Plugin API version %s (current: %s)", info.getName(), info.getKey(), info.getMinimalSonarPluginApiVersion(), sonarRuntime.getApiVersion())); } return true; } private static Collection<File> listJarFiles(File dir) { if (dir.exists()) { return FileUtils.listFiles(dir, new String[] {"jar"}, false); } return Collections.emptyList(); } }
10,238
43.907895
178
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/PluginUninstaller.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; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.Startable; import org.sonar.core.platform.PluginInfo; import org.sonar.server.platform.ServerFileSystem; import static java.lang.String.format; import static org.apache.commons.io.FileUtils.forceMkdir; import static org.apache.commons.io.FileUtils.moveFileToDirectory; import static org.sonar.core.plugin.PluginType.EXTERNAL; public class PluginUninstaller implements Startable { private static final Logger LOG = LoggerFactory.getLogger(PluginUninstaller.class); private static final String PLUGIN_EXTENSION = "jar"; private final ServerFileSystem fs; private final ServerPluginRepository pluginRepository; public PluginUninstaller(ServerFileSystem fs, ServerPluginRepository pluginRepository) { this.fs = fs; this.pluginRepository = pluginRepository; } @Override public void start() { try { forceMkdir(fs.getUninstalledPluginsDir()); } catch (IOException e) { throw new IllegalStateException("Fail to create the directory: " + fs.getUninstalledPluginsDir(), e); } } @Override public void stop() { // Nothing to do } /** * Uninstall a plugin and its dependents */ public void uninstall(String pluginKey) { if (!pluginRepository.hasPlugin(pluginKey) || pluginRepository.getPlugin(pluginKey).getType() != EXTERNAL) { throw new IllegalArgumentException(format("Plugin [%s] is not installed", pluginKey)); } Set<String> uninstallKeys = new HashSet<>(); uninstallKeys.add(pluginKey); appendDependentPluginKeys(pluginKey, uninstallKeys); for (String uninstallKey : uninstallKeys) { PluginInfo info = pluginRepository.getPluginInfo(uninstallKey); // we don't check type because the dependent of an external plugin should never be a bundled plugin! uninstall(info.getKey(), info.getName(), info.getNonNullJarFile().getName()); } } public void cancelUninstalls() { for (File file : listJarFiles(fs.getUninstalledPluginsDir())) { try { moveFileToDirectory(file, fs.getInstalledExternalPluginsDir(), false); } catch (IOException e) { throw new IllegalStateException("Fail to cancel plugin uninstalls", e); } } } /** * @return the list of plugins to be uninstalled as {@link PluginInfo} instances */ public Collection<PluginInfo> getUninstalledPlugins() { return listJarFiles(fs.getUninstalledPluginsDir()).stream() .map(PluginInfo::create) .toList(); } private static Collection<File> listJarFiles(File dir) { if (dir.exists()) { return FileUtils.listFiles(dir, new String[] {PLUGIN_EXTENSION}, false); } return Collections.emptyList(); } private void uninstall(String key, String name, String fileName) { try { if (!getPluginFile(fileName).exists()) { LOG.info("Plugin already uninstalled: {} [{}]", name, key); return; } LOG.info("Uninstalling plugin {} [{}]", name, key); File masterFile = getPluginFile(fileName); moveFileToDirectory(masterFile, fs.getUninstalledPluginsDir(), true); } catch (IOException e) { throw new IllegalStateException(format("Fail to uninstall plugin %s [%s]", name, key), e); } } private File getPluginFile(String fileName) { // just to be sure that file is located in from extensions/plugins return new File(fs.getInstalledExternalPluginsDir(), fileName); } private void appendDependentPluginKeys(String pluginKey, Set<String> appendTo) { for (PluginInfo otherPlugin : pluginRepository.getPluginInfos()) { if (otherPlugin.getKey().equals(pluginKey)) { continue; } for (PluginInfo.RequiredPlugin requirement : otherPlugin.getRequiredPlugins()) { if (requirement.getKey().equals(pluginKey)) { appendTo.add(otherPlugin.getKey()); appendDependentPluginKeys(otherPlugin.getKey(), appendTo); } } } } }
5,066
33.469388
112
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/ServerPlugin.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; import org.sonar.api.Plugin; import org.sonar.core.platform.PluginInfo; import org.sonar.core.plugin.PluginType; import org.sonar.server.plugins.PluginFilesAndMd5.FileAndMd5; public class ServerPlugin { private final PluginInfo pluginInfo; private final PluginType type; private final Plugin instance; private final FileAndMd5 jar; private final ClassLoader classloader; public ServerPlugin(PluginInfo pluginInfo, PluginType type, Plugin instance, FileAndMd5 jar) { this(pluginInfo, type, instance, jar, instance.getClass().getClassLoader()); } public ServerPlugin(PluginInfo pluginInfo, PluginType type, Plugin instance, FileAndMd5 jar, ClassLoader classloader) { this.pluginInfo = pluginInfo; this.type = type; this.instance = instance; this.jar = jar; this.classloader = classloader; } public PluginInfo getPluginInfo() { return pluginInfo; } public Plugin getInstance() { return instance; } public PluginType getType() { return type; } public FileAndMd5 getJar() { return jar; } public ClassLoader getClassloader() { return classloader; } }
2,013
29.515152
121
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/ServerPluginInfo.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; import java.io.File; import java.io.IOException; import java.util.Objects; import org.sonar.core.platform.PluginInfo; import org.sonar.core.plugin.PluginType; import org.sonar.updatecenter.common.PluginManifest; public class ServerPluginInfo extends PluginInfo { private PluginType type; public ServerPluginInfo(String key) { super(key); } public static ServerPluginInfo create(File jarFile, PluginType type) { try { PluginManifest manifest = new PluginManifest(jarFile); ServerPluginInfo serverPluginInfo = new ServerPluginInfo(manifest.getKey()); serverPluginInfo.fillFields(jarFile, manifest, type); return serverPluginInfo; } catch (IOException e) { throw new IllegalStateException("Fail to extract plugin metadata from file: " + jarFile, e); } } private void fillFields(File jarFile, PluginManifest manifest, PluginType type) { super.fillFields(jarFile, manifest); setType(type); } public PluginType getType() { return type; } public ServerPluginInfo setType(PluginType type) { this.type = type; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } if (!super.equals(o)) { return false; } ServerPluginInfo that = (ServerPluginInfo) o; return type == that.type; } @Override public int hashCode() { return Objects.hash(super.hashCode(), type); } }
2,392
28.54321
98
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/ServerPluginJarExploder.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; import java.io.File; import org.apache.commons.io.FileUtils; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.ZipUtils; import org.sonar.core.platform.ExplodedPlugin; import org.sonar.core.platform.PluginClassLoader; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginJarExploder; import org.sonar.server.platform.ServerFileSystem; import static org.apache.commons.io.FileUtils.forceMkdir; @ServerSide public class ServerPluginJarExploder extends PluginJarExploder { private final ServerFileSystem fs; public ServerPluginJarExploder(ServerFileSystem fs) { this.fs = fs; } /** * JAR files of directory extensions/plugins can be moved when server is up and plugins are uninstalled. * For this reason these files must not be locked by classloaders. They are copied to the directory * web/deploy/plugins in order to be loaded by {@link PluginClassLoader}. */ @Override public ExplodedPlugin explode(PluginInfo plugin) { File toDir = new File(fs.getDeployedPluginsDir(), plugin.getKey()); try { forceMkdir(toDir); org.sonar.core.util.FileUtils.cleanDirectory(toDir); File jarTarget = new File(toDir, plugin.getNonNullJarFile().getName()); FileUtils.copyFile(plugin.getNonNullJarFile(), jarTarget); ZipUtils.unzip(plugin.getNonNullJarFile(), toDir, newLibFilter()); return explodeFromUnzippedDir(plugin, jarTarget, toDir); } catch (Exception e) { throw new IllegalStateException(String.format( "Fail to unzip plugin [%s] %s to %s", plugin.getKey(), plugin.getNonNullJarFile().getAbsolutePath(), toDir.getAbsolutePath()), e); } } }
2,552
38.276923
138
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/ServerPluginManager.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; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.sonar.api.Startable; import org.sonar.api.Plugin; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.platform.ExplodedPlugin; import org.sonar.core.platform.PluginClassLoader; import org.sonar.core.platform.PluginJarExploder; import org.sonar.core.plugin.PluginType; /** * Entry point to install and load plugins on server startup. It manages * <ul> * <li>installation of new plugins (effective after server startup)</li> * <li>un-installation of plugins (effective after server startup)</li> * <li>cancel pending installations/un-installations</li> * <li>instantiation of plugin entry-points</li> * </ul> */ public class ServerPluginManager implements Startable { private static final Logger LOG = LoggerFactory.getLogger(ServerPluginManager.class); private final PluginJarLoader pluginJarLoader; private final PluginJarExploder pluginJarExploder; private final PluginClassLoader pluginClassLoader; private final ServerPluginRepository pluginRepository; public ServerPluginManager(PluginClassLoader pluginClassLoader, PluginJarExploder pluginJarExploder, PluginJarLoader pluginJarLoader, ServerPluginRepository pluginRepository) { this.pluginClassLoader = pluginClassLoader; this.pluginJarExploder = pluginJarExploder; this.pluginJarLoader = pluginJarLoader; this.pluginRepository = pluginRepository; } @Override public void start() { Collection<ServerPluginInfo> loadedPlugins = pluginJarLoader.loadPlugins(); logInstalledPlugins(loadedPlugins); Collection<ExplodedPlugin> explodedPlugins = extractPlugins(loadedPlugins); Map<String, Plugin> instancesByKey = pluginClassLoader.load(explodedPlugins); Map<String, PluginType> typesByKey = getTypesByKey(loadedPlugins); List<ServerPlugin> plugins = createServerPlugins(explodedPlugins, instancesByKey, typesByKey); pluginRepository.addPlugins(plugins); } private static Map<String, PluginType> getTypesByKey(Collection<ServerPluginInfo> loadedPlugins) { return loadedPlugins.stream().collect(Collectors.toMap(ServerPluginInfo::getKey, ServerPluginInfo::getType)); } @Override public void stop() { pluginClassLoader.unload(pluginRepository.getPluginInstances()); } private static void logInstalledPlugins(Collection<ServerPluginInfo> plugins) { plugins.stream().sorted().forEach(plugin -> LOG.info("Deploy {} / {} / {}", plugin.getName(), plugin.getVersion(), plugin.getImplementationBuild())); } private Collection<ExplodedPlugin> extractPlugins(Collection<ServerPluginInfo> plugins) { return plugins.stream().map(pluginJarExploder::explode).toList(); } private static List<ServerPlugin> createServerPlugins(Collection<ExplodedPlugin> explodedPlugins, Map<String, Plugin> instancesByKey, Map<String, PluginType> typesByKey) { List<ServerPlugin> plugins = new ArrayList<>(); for (ExplodedPlugin p : explodedPlugins) { plugins.add(new ServerPlugin(p.getPluginInfo(), typesByKey.get(p.getKey()), instancesByKey.get(p.getKey()), new PluginFilesAndMd5.FileAndMd5(p.getPluginInfo().getNonNullJarFile()))); } return plugins; } }
4,187
41.734694
173
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/ServerPluginRepository.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; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import org.sonar.api.Plugin; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; import org.sonar.core.plugin.PluginType; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; public class ServerPluginRepository implements PluginRepository { private final Map<String, ServerPlugin> pluginByKey = new HashMap<>(); private final Map<ClassLoader, String> keysByClassLoader = new HashMap<>(); public void addPlugins(List<ServerPlugin> plugins) { pluginByKey.putAll(plugins.stream().collect(Collectors.toMap(p -> p.getPluginInfo().getKey(), p -> p))); for (ServerPlugin p : plugins) { keysByClassLoader.put(p.getClassloader(), p.getPluginInfo().getKey()); } } public void addPlugin(ServerPlugin plugin) { pluginByKey.put(plugin.getPluginInfo().getKey(), plugin); if (plugin.getInstance() != null) { keysByClassLoader.put(plugin.getInstance().getClass().getClassLoader(), plugin.getPluginInfo().getKey()); } } @CheckForNull public String getPluginKey(Object extension) { return keysByClassLoader.get(extension.getClass().getClassLoader()); } @Override public Collection<PluginInfo> getPluginInfos() { return pluginByKey.values().stream().map(ServerPlugin::getPluginInfo).toList(); } @Override public PluginInfo getPluginInfo(String key) { return getPlugin(key).getPluginInfo(); } public ServerPlugin getPlugin(String key) { ServerPlugin plugin = pluginByKey.get(key); if (plugin == null) { throw new IllegalArgumentException(format("Plugin [%s] does not exist", key)); } return plugin; } public Collection<ServerPlugin> getPlugins() { return Collections.unmodifiableCollection(pluginByKey.values()); } public Optional<ServerPlugin> findPlugin(String key) { return Optional.ofNullable(pluginByKey.get(key)); } public Collection<PluginInfo> getPluginsInfoByType(PluginType type){ return pluginByKey.values() .stream() .filter(p -> p.getType() == type) .map(ServerPlugin::getPluginInfo) .toList(); } @Override public Plugin getPluginInstance(String key) { ServerPlugin plugin = pluginByKey.get(key); checkArgument(plugin != null, "Plugin [%s] does not exist", key); return plugin.getInstance(); } @Override public Collection<Plugin> getPluginInstances() { return pluginByKey.values().stream() .map(ServerPlugin::getInstance) .toList(); } @Override public boolean hasPlugin(String key) { return pluginByKey.containsKey(key); } }
3,736
31.495652
111
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/UpdateCenterClient.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; import java.io.InputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.Optional; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.Properties; import org.sonar.api.Property; import org.sonar.api.config.Configuration; import org.sonar.api.utils.UriReader; import org.sonar.process.ProcessProperties; import org.sonar.updatecenter.common.UpdateCenter; import org.sonar.updatecenter.common.UpdateCenterDeserializer; import org.sonar.updatecenter.common.UpdateCenterDeserializer.Mode; /** * HTTP client to load data from the remote update center hosted at https://update.sonarsource.org. * * @since 2.4 */ @Properties({ @Property( key = UpdateCenterClient.URL_PROPERTY, defaultValue = "https://update.sonarsource.org/update-center.properties", name = "Update Center URL", category = "Update Center", // hidden from UI global = false), @Property( key = UpdateCenterClient.CACHE_TTL_PROPERTY, defaultValue = "3600000", name = "Update Center cache time-to-live in milliseconds", category = "Update Center", // hidden from UI global = false) }) public class UpdateCenterClient { private static final Logger LOG = LoggerFactory.getLogger(UpdateCenterClient.class); public static final String URL_PROPERTY = "sonar.updatecenter.url"; public static final String CACHE_TTL_PROPERTY = "sonar.updatecenter.cache.ttl"; private final long periodInMilliseconds; private final URI uri; private final UriReader uriReader; private final boolean isActivated; private UpdateCenter pluginCenter = null; private long lastRefreshDate = 0; public UpdateCenterClient(UriReader uriReader, Configuration config) throws URISyntaxException { this.uriReader = uriReader; this.uri = new URI(config.get(URL_PROPERTY).get()); this.isActivated = config.getBoolean(ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE.getKey()).get(); this.periodInMilliseconds = Long.parseLong(config.get(CACHE_TTL_PROPERTY).get()); LOG.info("Update center: {}", uriReader.description(uri)); } public Optional<UpdateCenter> getUpdateCenter() { return getUpdateCenter(false); } public Optional<UpdateCenter> getUpdateCenter(boolean forceRefresh) { if (!isActivated) { return Optional.empty(); } if (pluginCenter == null || forceRefresh || needsRefresh()) { pluginCenter = init(); lastRefreshDate = System.currentTimeMillis(); } return Optional.ofNullable(pluginCenter); } public Date getLastRefreshDate() { return lastRefreshDate > 0 ? new Date(lastRefreshDate) : null; } private boolean needsRefresh() { return lastRefreshDate + periodInMilliseconds < System.currentTimeMillis(); } private UpdateCenter init() { InputStream input = null; try { String content = uriReader.readString(uri, StandardCharsets.UTF_8); java.util.Properties properties = new java.util.Properties(); input = IOUtils.toInputStream(content, StandardCharsets.UTF_8); properties.load(input); return new UpdateCenterDeserializer(Mode.PROD, true).fromProperties(properties); } catch (Exception e) { LoggerFactory.getLogger(getClass()).error("Fail to connect to update center", e); return null; } finally { IOUtils.closeQuietly(input); } } }
4,348
33.515873
112
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/UpdateCenterMatrixFactory.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; import java.util.Optional; import org.sonar.core.platform.SonarQubeVersion; import org.sonar.updatecenter.common.UpdateCenter; import org.sonar.updatecenter.common.Version; /** * @since 2.4 */ public class UpdateCenterMatrixFactory { private final UpdateCenterClient centerClient; private final SonarQubeVersion sonarQubeVersion; private final InstalledPluginReferentialFactory installedPluginReferentialFactory; public UpdateCenterMatrixFactory(UpdateCenterClient centerClient, SonarQubeVersion sonarQubeVersion, InstalledPluginReferentialFactory installedPluginReferentialFactory) { this.centerClient = centerClient; this.sonarQubeVersion = sonarQubeVersion; this.installedPluginReferentialFactory = installedPluginReferentialFactory; } public Optional<UpdateCenter> getUpdateCenter(boolean refreshUpdateCenter) { Optional<UpdateCenter> updateCenter = centerClient.getUpdateCenter(refreshUpdateCenter); if (updateCenter.isPresent()) { org.sonar.api.utils.Version fullVersion = sonarQubeVersion.get(); org.sonar.api.utils.Version semanticVersion = org.sonar.api.utils.Version.create(fullVersion.major(), fullVersion.minor(), fullVersion.patch()); return Optional.of(updateCenter.get().setInstalledSonarVersion(Version.create(semanticVersion.toString())).registerInstalledPlugins( installedPluginReferentialFactory.getInstalledPluginReferential()) .setDate(centerClient.getLastRefreshDate())); } return Optional.empty(); } }
2,390
41.696429
150
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/WebServerExtensionInstaller.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; import org.sonar.api.SonarRuntime; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.core.platform.PluginRepository; import static java.util.Collections.singleton; @ServerSide public class WebServerExtensionInstaller extends ServerExtensionInstaller { public WebServerExtensionInstaller(Configuration configuration, SonarRuntime sonarRuntime, PluginRepository pluginRepository) { super(configuration, sonarRuntime, pluginRepository, singleton(ServerSide.class)); } }
1,405
39.171429
129
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/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; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/edition/EditionBundledPlugins.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.edition; import java.util.Arrays; import org.sonar.core.platform.PluginInfo; import org.sonar.updatecenter.common.Plugin; public final class EditionBundledPlugins { private static final String SONARSOURCE_ORGANIZATION = "SonarSource"; private static final String[] SONARSOURCE_COMMERCIAL_LICENSES = {"SonarSource", "Commercial"}; private EditionBundledPlugins() { // prevents instantiation } public static boolean isEditionBundled(Plugin plugin) { return SONARSOURCE_ORGANIZATION.equalsIgnoreCase(plugin.getOrganization()) && Arrays.stream(SONARSOURCE_COMMERCIAL_LICENSES).anyMatch(s -> s.equalsIgnoreCase(plugin.getLicense())); } public static boolean isEditionBundled(PluginInfo pluginInfo) { return SONARSOURCE_ORGANIZATION.equalsIgnoreCase(pluginInfo.getOrganizationName()) && Arrays.stream(SONARSOURCE_COMMERCIAL_LICENSES).anyMatch(s -> s.equalsIgnoreCase(pluginInfo.getLicense())); } }
1,814
39.333333
115
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/plugins/edition/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.edition; import javax.annotation.ParametersAreNonnullByDefault;
973
37.96
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/project/DeletedProject.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; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; /** * This record is used to refresh application/portfolio after the deletion of a project / portfolio * @param project could refer to a project or a portfolio deleted * @param mainBranchUuid refer to the main branch of the project deleted, is null when this record is used for a portfolio */ public record DeletedProject(Project project, @Nullable String mainBranchUuid) { public DeletedProject(Project project, String mainBranchUuid) { this.project = checkNotNull(project, "project can't be null"); this.mainBranchUuid = mainBranchUuid; } }
1,538
40.594595
122
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/project/ProjectDefaultVisibility.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; import java.util.Optional; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.property.PropertyDto; public class ProjectDefaultVisibility { private static final String PROJECTS_DEFAULT_VISIBILITY_PROPERTY_NAME = "projects.default.visibility"; private final DbClient dbClient; public ProjectDefaultVisibility(DbClient dbClient) { this.dbClient = dbClient; } public Visibility get(DbSession dbSession) { PropertyDto defaultProjectVisibility = Optional .ofNullable(dbClient.propertiesDao().selectGlobalProperty(dbSession, PROJECTS_DEFAULT_VISIBILITY_PROPERTY_NAME)) .orElseThrow(() -> new IllegalStateException("Could not find default project visibility setting")); return Visibility.parseVisibility(defaultProjectVisibility.getValue()); } public void set(DbSession dbSession, String visibilityLabel) { set(dbSession, Visibility.parseVisibility(visibilityLabel)); } public void set(DbSession dbSession, Visibility visibility) { dbClient.propertiesDao().saveProperty(dbSession, new PropertyDto() .setKey(PROJECTS_DEFAULT_VISIBILITY_PROPERTY_NAME) .setValue(visibility.getLabel())); } }
2,059
38.615385
118
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/project/ProjectLifeCycleListener.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; import java.util.Set; import org.sonar.api.server.ServerSide; @ServerSide public interface ProjectLifeCycleListener { /** * This method is called after the specified projects have been deleted. */ void onProjectsDeleted(Set<DeletedProject> projects); /** * This method is called after the specified projects have been deleted. */ void onProjectBranchesDeleted(Set<Project> projects); /** * This method is called after the specified projects' keys have been modified. */ void onProjectsRekeyed(Set<RekeyedProject> rekeyedProjects); }
1,444
33.404762
81
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/project/ProjectLifeCycleListeners.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; import java.util.Set; public interface ProjectLifeCycleListeners { /** * This method is called after the specified projects have been deleted and will call method * {@link ProjectLifeCycleListener#onProjectsDeleted(Set) onProjectsDeleted(Set)} of all known * {@link ProjectLifeCycleListener} implementations. * <p> * This method ensures all {@link ProjectLifeCycleListener} implementations are called, even if one or more of * them fail with an exception. */ void onProjectsDeleted(Set<DeletedProject> projects); /** * This method is called after the specified project branches have been deleted and will call method * {@link ProjectLifeCycleListener#onProjectBranchesDeleted(Set)} of all known * {@link ProjectLifeCycleListener} implementations. * <p> * This method ensures all {@link ProjectLifeCycleListener} implementations are called, even if one or more of * them fail with an exception. */ void onProjectBranchesDeleted(Set<Project> projects); /** * This method is called after the specified project's key has been changed and will call method * {@link ProjectLifeCycleListener#onProjectsRekeyed(Set) onProjectsRekeyed(Set)} of all known * {@link ProjectLifeCycleListener} implementations. * <p> * This method ensures all {@link ProjectLifeCycleListener} implementations are called, even if one or more of * them fail with an exception. */ void onProjectsRekeyed(Set<RekeyedProject> rekeyedProjects); }
2,367
41.285714
112
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/project/ProjectLifeCycleListenersImpl.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; import java.util.Arrays; import java.util.Set; import java.util.function.Consumer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import static com.google.common.base.Preconditions.checkNotNull; public class ProjectLifeCycleListenersImpl implements ProjectLifeCycleListeners { private static final Logger LOG = LoggerFactory.getLogger(ProjectLifeCycleListenersImpl.class); private final ProjectLifeCycleListener[] listeners; /** * Used by the container when there is no ProjectLifeCycleListener implementation in container. */ @Autowired(required = false) public ProjectLifeCycleListenersImpl() { this.listeners = new ProjectLifeCycleListener[0]; } /** * Used by the container when there is at least one ProjectLifeCycleListener implementation in container. */ @Autowired(required = false) public ProjectLifeCycleListenersImpl(ProjectLifeCycleListener[] listeners) { this.listeners = listeners; } @Override public void onProjectsDeleted(Set<DeletedProject> projects) { checkNotNull(projects, "projects can't be null"); if (projects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectsDeleted(projects))); } @Override public void onProjectBranchesDeleted(Set<Project> projects) { checkNotNull(projects, "projects can't be null"); if (projects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectBranchesDeleted(projects))); } @Override public void onProjectsRekeyed(Set<RekeyedProject> rekeyedProjects) { checkNotNull(rekeyedProjects, "rekeyedProjects can't be null"); if (rekeyedProjects.isEmpty()) { return; } Arrays.stream(listeners) .forEach(safelyCallListener(listener -> listener.onProjectsRekeyed(rekeyedProjects))); } private static Consumer<ProjectLifeCycleListener> safelyCallListener(Consumer<ProjectLifeCycleListener> task) { return listener -> { try { task.accept(listener); } catch (Error | Exception e) { LOG.error("Call on ProjectLifeCycleListener \"{}\" failed", listener.getClass(), e); } }; } }
3,173
32.410526
113
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/project/RekeyedProject.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; import static com.google.common.base.Preconditions.checkNotNull; public record RekeyedProject(Project project, String previousKey) { public RekeyedProject(Project project, String previousKey) { this.project = checkNotNull(project, "project can't be null"); this.previousKey = checkNotNull(previousKey, "previousKey can't be null"); } @Override public String toString() { return "RekeyedProject{" + "project=" + project + ", previousKey='" + previousKey + '\'' + '}'; } }
1,391
35.631579
78
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/project/Visibility.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; import java.util.List; import static java.util.Arrays.stream; public enum Visibility { PRIVATE(true, "private"), PUBLIC(false, "public"); private static final List<String> LABELS = stream(values()).map(Visibility::getLabel).toList(); private final boolean isPrivate; private final String label; Visibility(boolean isPrivate, String label) { this.isPrivate = isPrivate; this.label = label; } public String getLabel() { return label; } public boolean isPrivate() { return isPrivate; } public static String getLabel(boolean isPrivate) { return stream(values()) .filter(v -> v.isPrivate == isPrivate) .map(Visibility::getLabel) .findAny() .orElseThrow(() -> new IllegalStateException("Invalid visibility boolean '" + isPrivate + "'")); } public static boolean isPrivate(String label) { return parseVisibility(label).isPrivate(); } public static Visibility parseVisibility(String label) { return stream(values()) .filter(v -> v.label.equals(label)) .findAny() .orElseThrow(() -> new IllegalStateException("Invalid visibility label '" + label + "'")); } public static List<String> getLabels() { return LABELS; } }
2,110
28.319444
102
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/project/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; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/ProjectsInWarning.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.qualitygate; import static com.google.common.base.Preconditions.checkArgument; /** * Store number of projects in warning in order for the web service api/components/search to know if warning value should be return in the quality gate facet. * The value is updated each time the daemon {@link ProjectsInWarningDaemon} is executed */ public class ProjectsInWarning { private Long projectsInWarning; public void update(long projectsInWarning) { this.projectsInWarning = projectsInWarning; } public long count() { checkArgument(isInitialized(), "Initialization has not be done"); return projectsInWarning; } boolean isInitialized() { return projectsInWarning != null; } }
1,575
34.022222
158
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/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.qualitygate; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/changeevent/ChangedIssueImpl.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.qualitygate.changeevent; import java.util.Objects; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; class ChangedIssueImpl implements QGChangeEventListener.ChangedIssue { private final String key; private final QGChangeEventListener.Status status; private final RuleType type; private final String severity; private final boolean fromAlm; ChangedIssueImpl(DefaultIssue issue) { this(issue, false); } ChangedIssueImpl(DefaultIssue issue, boolean fromAlm) { this.key = issue.key(); this.status = statusOf(issue); this.type = issue.type(); this.severity = issue.severity(); this.fromAlm = fromAlm; } static QGChangeEventListener.Status statusOf(DefaultIssue issue) { switch (issue.status()) { case Issue.STATUS_OPEN: return QGChangeEventListener.Status.OPEN; case Issue.STATUS_CONFIRMED: return QGChangeEventListener.Status.CONFIRMED; case Issue.STATUS_REOPENED: return QGChangeEventListener.Status.REOPENED; case Issue.STATUS_TO_REVIEW: return QGChangeEventListener.Status.TO_REVIEW; case Issue.STATUS_REVIEWED: return QGChangeEventListener.Status.REVIEWED; case Issue.STATUS_RESOLVED: return statusOfResolved(issue); default: throw new IllegalStateException("Unexpected status: " + issue.status()); } } private static QGChangeEventListener.Status statusOfResolved(DefaultIssue issue) { String resolution = issue.resolution(); Objects.requireNonNull(resolution, "A resolved issue should have a resolution"); switch (resolution) { case Issue.RESOLUTION_FALSE_POSITIVE: return QGChangeEventListener.Status.RESOLVED_FP; case Issue.RESOLUTION_WONT_FIX: return QGChangeEventListener.Status.RESOLVED_WF; case Issue.RESOLUTION_FIXED: return QGChangeEventListener.Status.RESOLVED_FIXED; default: throw new IllegalStateException("Unexpected resolution for a resolved issue: " + resolution); } } @Override public String getKey() { return key; } @Override public QGChangeEventListener.Status getStatus() { return status; } @Override public RuleType getType() { return type; } @Override public String getSeverity() { return severity; } @Override public boolean fromAlm() { return fromAlm; } @Override public String toString() { return "ChangedIssueImpl{" + "key='" + key + '\'' + ", status=" + status + ", type=" + type + ", severity=" + severity + ", fromAlm=" + fromAlm + '}'; } }
3,537
29.5
101
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/changeevent/QGChangeEvent.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.qualitygate.changeevent; import java.util.Optional; import java.util.function.Supplier; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.config.Configuration; import org.sonar.api.measures.Metric; import org.sonar.db.component.BranchDto; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.qualitygate.EvaluatedQualityGate; import static java.util.Objects.requireNonNull; @Immutable public class QGChangeEvent { private final ProjectDto project; private final BranchDto branch; private final SnapshotDto analysis; private final Configuration projectConfiguration; private final Metric.Level previousStatus; private final Supplier<Optional<EvaluatedQualityGate>> qualityGateSupplier; public QGChangeEvent(ProjectDto project, BranchDto branch, SnapshotDto analysis, Configuration projectConfiguration, @Nullable Metric.Level previousStatus, Supplier<Optional<EvaluatedQualityGate>> qualityGateSupplier) { this.project = requireNonNull(project, "project can't be null"); this.branch = requireNonNull(branch, "branch can't be null"); this.analysis = requireNonNull(analysis, "analysis can't be null"); this.projectConfiguration = requireNonNull(projectConfiguration, "projectConfiguration can't be null"); this.previousStatus = previousStatus; this.qualityGateSupplier = requireNonNull(qualityGateSupplier, "qualityGateSupplier can't be null"); } public BranchDto getBranch() { return branch; } public ProjectDto getProject() { return project; } public SnapshotDto getAnalysis() { return analysis; } public Configuration getProjectConfiguration() { return projectConfiguration; } public Optional<Metric.Level> getPreviousStatus() { return Optional.ofNullable(previousStatus); } public Supplier<Optional<EvaluatedQualityGate>> getQualityGateSupplier() { return qualityGateSupplier; } @Override public String toString() { return "QGChangeEvent{" + "project=" + toString(project) + ", branch=" + toString(branch) + ", analysis=" + toString(analysis) + ", projectConfiguration=" + projectConfiguration + ", previousStatus=" + previousStatus + ", qualityGateSupplier=" + qualityGateSupplier + '}'; } private static String toString(ProjectDto project) { return project.getUuid() + ":" + project.getKey(); } private static String toString(BranchDto branch) { return branch.getBranchType() + ":" + branch.getUuid() + ":" + branch.getProjectUuid() + ":" + branch.getMergeBranchUuid(); } private static String toString(SnapshotDto analysis) { return analysis.getUuid() + ":" + analysis.getCreatedAt(); } }
3,649
34.784314
127
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/changeevent/QGChangeEventListener.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.qualitygate.changeevent; import java.util.EnumSet; import java.util.Set; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ServerSide; import static org.sonar.api.rules.RuleType.VULNERABILITY; @ServerSide public interface QGChangeEventListener { /** * Called consequently to a change done on one or more issue of a given project. * * @param qualityGateEvent can not be {@code null} * @param changedIssues can not be {@code null} nor empty */ void onIssueChanges(QGChangeEvent qualityGateEvent, Set<ChangedIssue> changedIssues); interface ChangedIssue { String getKey(); Status getStatus(); RuleType getType(); String getSeverity(); default boolean isNotClosed() { return !Status.CLOSED_STATUSES.contains(getStatus()); } default boolean isVulnerability() { return getType() == VULNERABILITY; } default boolean fromAlm() { return false; } } enum Status { OPEN, CONFIRMED, REOPENED, RESOLVED_FP, RESOLVED_WF, RESOLVED_FIXED, TO_REVIEW, IN_REVIEW, REVIEWED; protected static final Set<Status> CLOSED_STATUSES = EnumSet.of(CONFIRMED, RESOLVED_FIXED, RESOLVED_FP, RESOLVED_WF); } }
2,098
26.25974
121
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/changeevent/QGChangeEventListeners.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.qualitygate.changeevent; import java.util.Collection; import java.util.List; import org.sonar.core.issue.DefaultIssue; public interface QGChangeEventListeners { /** * Broadcast events after issues were updated * * @param fromAlm: true if issues changes were initiated by an ALM. */ void broadcastOnIssueChange(List<DefaultIssue> changedIssues, Collection<QGChangeEvent> qgChangeEvents, boolean fromAlm); }
1,294
34.972222
123
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/changeevent/QGChangeEventListenersImpl.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.qualitygate.changeevent; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.util.stream.MoreCollectors; import org.sonar.server.qualitygate.changeevent.QGChangeEventListener.ChangedIssue; import static com.google.common.collect.ImmutableSet.toImmutableSet; import static java.lang.String.format; /** * Broadcast a given collection of {@link QGChangeEvent} for a specific trigger to all the registered * {@link QGChangeEventListener} in the ioc container. * * This class ensures that an {@link Exception} occurring calling one of the {@link QGChangeEventListener} doesn't * prevent from calling the others. */ public class QGChangeEventListenersImpl implements QGChangeEventListeners { private static final Logger LOG = LoggerFactory.getLogger(QGChangeEventListenersImpl.class); private final Set<QGChangeEventListener> listeners; public QGChangeEventListenersImpl(Set<QGChangeEventListener> listeners) { this.listeners = listeners; } @Override public void broadcastOnIssueChange(List<DefaultIssue> issues, Collection<QGChangeEvent> changeEvents, boolean fromAlm) { if (listeners.isEmpty() || issues.isEmpty() || changeEvents.isEmpty()) { return; } try { broadcastChangeEventsToBranches(issues, changeEvents, fromAlm); } catch (Error e) { LOG.warn(format("Broadcasting to listeners failed for %s events", changeEvents.size()), e); } } private void broadcastChangeEventsToBranches(List<DefaultIssue> issues, Collection<QGChangeEvent> changeEvents, boolean fromAlm) { Multimap<String, QGChangeEvent> eventsByBranchUuid = changeEvents.stream() .collect(MoreCollectors.index(qgChangeEvent -> qgChangeEvent.getBranch().getUuid())); Multimap<String, DefaultIssue> issueByBranchUuid = issues.stream() .collect(MoreCollectors.index(DefaultIssue::projectUuid)); issueByBranchUuid.asMap().forEach( (branchUuid, branchIssues) -> broadcastChangeEventsToBranch(branchIssues, eventsByBranchUuid.get(branchUuid), fromAlm)); } private void broadcastChangeEventsToBranch(Collection<DefaultIssue> branchIssues, Collection<QGChangeEvent> branchQgChangeEvents, boolean fromAlm) { Set<ChangedIssue> changedIssues = toChangedIssues(branchIssues, fromAlm); branchQgChangeEvents.forEach(changeEvent -> broadcastChangeEventToListeners(changedIssues, changeEvent)); } private static ImmutableSet<ChangedIssue> toChangedIssues(Collection<DefaultIssue> defaultIssues, boolean fromAlm) { return defaultIssues.stream() .map(defaultIssue -> new ChangedIssueImpl(defaultIssue, fromAlm)) .collect(toImmutableSet()); } private void broadcastChangeEventToListeners(Set<ChangedIssue> changedIssues, QGChangeEvent changeEvent) { listeners.forEach(listener -> broadcastChangeEventToListener(changedIssues, changeEvent, listener)); } private static void broadcastChangeEventToListener(Set<ChangedIssue> changedIssues, QGChangeEvent changeEvent, QGChangeEventListener listener) { try { LOG.trace("calling onChange() on listener {} for events {}...", listener.getClass().getName(), changeEvent); listener.onIssueChanges(changeEvent, changedIssues); } catch (Exception e) { LOG.warn(format("onChange() call failed on listener %s for events %s", listener.getClass().getName(), changeEvent), e); } } }
4,444
43.009901
150
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/changeevent/Trigger.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.qualitygate.changeevent; public enum Trigger { ISSUE_CHANGE }
933
36.36
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualitygate/changeevent/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.qualitygate.changeevent; import javax.annotation.ParametersAreNonnullByDefault;
980
39.875
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualityprofile/BulkChangeResult.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.qualityprofile; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class BulkChangeResult { private final List<String> errors = new ArrayList<>(); private int succeeded = 0; private int failed = 0; private final List<ActiveRuleChange> changes = new ArrayList<>(); public List<String> getErrors() { return errors; } public int countSucceeded() { return succeeded; } public int countFailed() { return failed; } void incrementSucceeded() { succeeded++; } void incrementFailed() { failed++; } void addChanges(Collection<ActiveRuleChange> c) { this.changes.addAll(c); } public List<ActiveRuleChange> getChanges() { return changes; } }
1,608
25.377049
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualityprofile/QProfileRules.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.qualityprofile; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; import org.sonar.db.DbSession; import org.sonar.db.qualityprofile.QProfileDto; import org.sonar.db.rule.RuleDto; import org.sonar.server.rule.index.RuleQuery; /** * Operations related to activation and deactivation of rules on user profiles. */ @ServerSide public interface QProfileRules { /** * Activate multiple rules at once on a Quality profile. * Db session is committed and Elasticsearch indices are updated. * If an activation fails to be executed, then all others are * canceled, db session is not committed and an exception is * thrown. */ List<ActiveRuleChange> activateAndCommit(DbSession dbSession, QProfileDto profile, Collection<RuleActivation> activations); /** * Same as {@link #activateAndCommit(DbSession, QProfileDto, Collection)} except * that: * - rules are loaded from search engine * - rules are activated with default parameters * - an activation failure does not break others. No exception is thrown. */ BulkChangeResult bulkActivateAndCommit(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery, @Nullable String severity); List<ActiveRuleChange> deactivateAndCommit(DbSession dbSession, QProfileDto profile, Collection<String> ruleUuids); BulkChangeResult bulkDeactivateAndCommit(DbSession dbSession, QProfileDto profile, RuleQuery ruleQuery); /** * Delete a rule from all Quality profiles. Db session is not committed. As a * consequence Elasticsearch indices are NOT updated. */ List<ActiveRuleChange> deleteRule(DbSession dbSession, RuleDto rule); }
2,569
38.538462
131
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualityprofile/RuleActivation.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.qualityprofile; import com.google.common.base.Strings; import java.util.HashMap; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.rule.Severity; /** * The request for activation. */ @Immutable public class RuleActivation { private final String ruleUuid; private final boolean reset; private final String severity; private final Map<String, String> parameters = new HashMap<>(); private RuleActivation(String ruleUuid, boolean reset, @Nullable String severity, @Nullable Map<String, String> parameters) { this.ruleUuid = ruleUuid; this.reset = reset; this.severity = severity; if (severity != null && !Severity.ALL.contains(severity)) { throw new IllegalArgumentException("Unknown severity: " + severity); } if (parameters != null) { for (Map.Entry<String, String> entry : parameters.entrySet()) { this.parameters.put(entry.getKey(), Strings.emptyToNull(entry.getValue())); } } } public static RuleActivation createReset(String ruleUuid) { return new RuleActivation(ruleUuid, true, null, null); } public static RuleActivation create(String ruleUuid, @Nullable String severity, @Nullable Map<String, String> parameters) { return new RuleActivation(ruleUuid, false, severity, parameters); } public static RuleActivation create(String ruleUuid) { return create(ruleUuid, null, null); } /** * Optional severity. Use the parent severity or default rule severity if null. */ @CheckForNull public String getSeverity() { return severity; } public String getRuleUuid() { return ruleUuid; } @CheckForNull public String getParameter(String key) { return parameters.get(key); } public boolean hasParameter(String key) { return parameters.containsKey(key); } public boolean isReset() { return reset; } }
2,826
29.728261
127
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/qualityprofile/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.qualityprofile; import javax.annotation.ParametersAreNonnullByDefault;
971
39.5
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/rule/CachingRuleFinder.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.rule; import com.google.common.collect.Ordering; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RuleFinder; import org.sonar.api.rules.RulePriority; import org.sonar.api.rules.RuleQuery; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleParamDto; import static java.util.Collections.emptyList; import static java.util.Collections.unmodifiableMap; /** * A {@link RuleFinder} implementation that retrieves all rule definitions and their parameter when instantiated, cache * them in memory and provide implementation of {@link RuleFinder}'s method which only read from this data in memory. */ public class CachingRuleFinder implements ServerRuleFinder { private static final Ordering<Map.Entry<RuleDto, Rule>> FIND_BY_QUERY_ORDER = Ordering.natural().reverse().onResultOf(entry -> entry.getKey().getUpdatedAt()); private final Map<RuleKey, RuleDto> ruleDtosByKey; private final Map<String, RuleDto> ruleDtosByUuid; private final Map<RuleDto, Rule> ruleByRuleDto; private final Map<RuleKey, Rule> rulesByKey; private final RuleDescriptionFormatter ruleDescriptionFormatter; public CachingRuleFinder(DbClient dbClient, RuleDescriptionFormatter ruleDescriptionFormatter) { this.ruleDescriptionFormatter = ruleDescriptionFormatter; try (DbSession dbSession = dbClient.openSession(false)) { List<RuleDto> dtos = dbClient.ruleDao().selectAll(dbSession); this.ruleDtosByKey = dtos.stream().collect(Collectors.toMap(RuleDto::getKey, d -> d)); this.ruleDtosByUuid = dtos.stream().collect(Collectors.toMap(RuleDto::getUuid, d -> d)); this.ruleByRuleDto = buildRulesByRuleDefinitionDto(dbClient, dbSession, dtos); this.rulesByKey = this.ruleByRuleDto.entrySet().stream() .collect(Collectors.toMap(entry -> entry.getKey().getKey(), Map.Entry::getValue)); } } private Map<RuleDto, Rule> buildRulesByRuleDefinitionDto(DbClient dbClient, DbSession dbSession, List<RuleDto> dtos) { Map<String, List<RuleParamDto>> ruleParamsByRuleUuid = retrieveRuleParameters(dbClient, dbSession); Map<RuleDto, Rule> rulesByDefinition = new HashMap<>(dtos.size()); for (RuleDto definition : dtos) { rulesByDefinition.put(definition, toRule(definition, ruleParamsByRuleUuid.getOrDefault(definition.getUuid(), emptyList()))); } return unmodifiableMap(rulesByDefinition); } private static Map<String, List<RuleParamDto>> retrieveRuleParameters(DbClient dbClient, DbSession dbSession) { return dbClient.ruleDao().selectAllRuleParams(dbSession).stream() .collect(Collectors.groupingBy(RuleParamDto::getRuleUuid)); } @Override @CheckForNull public Rule findByKey(@Nullable String repositoryKey, @Nullable String key) { if (repositoryKey == null || key == null) { return null; } return findByKey(RuleKey.of(repositoryKey, key)); } @Override @CheckForNull public Rule findByKey(@Nullable RuleKey key) { return rulesByKey.get(key); } @Override @CheckForNull public Rule find(@Nullable RuleQuery query) { if (query == null) { return null; } return ruleByRuleDto.entrySet().stream() .filter(entry -> matchQuery(entry.getKey(), query)) .sorted(FIND_BY_QUERY_ORDER) .map(Map.Entry::getValue) .findFirst() .orElse(null); } @Override public Collection<Rule> findAll(@Nullable RuleQuery query) { if (query == null) { return Collections.emptyList(); } return ruleByRuleDto.entrySet().stream() .filter(entry -> matchQuery(entry.getKey(), query)) .sorted(FIND_BY_QUERY_ORDER) .map(Map.Entry::getValue) .toList(); } private static boolean matchQuery(RuleDto ruleDto, RuleQuery ruleQuery) { if (RuleStatus.REMOVED.equals(ruleDto.getStatus())) { return false; } String repositoryKey = ruleQuery.getRepositoryKey(); if (ruleQuery.getRepositoryKey() != null && !repositoryKey.equals(ruleDto.getRepositoryKey())) { return false; } String key = ruleQuery.getKey(); if (key != null && !key.equals(ruleDto.getRuleKey())) { return false; } String configKey = ruleQuery.getConfigKey(); return configKey == null || configKey.equals(ruleDto.getConfigKey()); } private Rule toRule(RuleDto ruleDto, List<RuleParamDto> params) { String severity = ruleDto.getSeverityString(); Rule apiRule = Rule.create() .setName(ruleDto.getName()) .setKey(ruleDto.getRuleKey()) .setConfigKey(ruleDto.getConfigKey()) .setIsTemplate(ruleDto.isTemplate()) .setCreatedAt(new Date(ruleDto.getCreatedAt())) .setUpdatedAt(new Date(ruleDto.getUpdatedAt())) .setRepositoryKey(ruleDto.getRepositoryKey()) .setSeverity(severity != null ? RulePriority.valueOf(severity) : null) .setStatus(ruleDto.getStatus().name()) .setSystemTags(ruleDto.getSystemTags().toArray(new String[ruleDto.getSystemTags().size()])) .setTags(new String[0]); Optional.ofNullable(ruleDescriptionFormatter.getDescriptionAsHtml(ruleDto)).ifPresent(apiRule::setDescription); Optional.ofNullable(ruleDto.getLanguage()).ifPresent(apiRule::setLanguage); List<org.sonar.api.rules.RuleParam> apiParams = new ArrayList<>(); for (RuleParamDto param : params) { apiParams.add(new org.sonar.api.rules.RuleParam(apiRule, param.getName(), param.getDescription(), param.getType()) .setDefaultValue(param.getDefaultValue())); } apiRule.setParams(apiParams); return apiRule; } @Override public Optional<RuleDto> findDtoByKey(RuleKey key) { return Optional.ofNullable(this.ruleDtosByKey.get(key)); } @Override public Optional<RuleDto> findDtoByUuid(String uuid) { return Optional.ofNullable(this.ruleDtosByUuid.get(uuid)); } @Override public Collection<RuleDto> findAll() { return ruleDtosByUuid.values(); } }
7,203
36.717277
160
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/rule/WebServerRuleFinder.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.rule; /** * {@link ServerRuleFinder} implementation that supports caching used by the Web Server. * <p> * Caching is enabled right after loading of rules is done (see {@link RegisterRules}) and disabled * once all startup tasks are done (see {@link org.sonar.server.platform.platformlevel.PlatformLevelStartup}). * </p> */ public interface WebServerRuleFinder extends ServerRuleFinder { /** * Enable caching. */ void startCaching(); /** * Disable caching. */ void stopCaching(); }
1,381
33.55
112
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/rule/WebServerRuleFinderImpl.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.rule; import com.google.common.annotations.VisibleForTesting; import java.util.Collection; import java.util.Optional; import javax.annotation.CheckForNull; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.Rule; import org.sonar.api.rules.RuleQuery; import org.sonar.db.DbClient; import org.sonar.db.rule.RuleDto; public class WebServerRuleFinderImpl implements WebServerRuleFinder { private final DbClient dbClient; private final ServerRuleFinder defaultFinder; private final RuleDescriptionFormatter ruleDescriptionFormatter; @VisibleForTesting ServerRuleFinder delegate; public WebServerRuleFinderImpl(DbClient dbClient, RuleDescriptionFormatter ruleDescriptionFormatter) { this.dbClient = dbClient; this.ruleDescriptionFormatter = ruleDescriptionFormatter; this.defaultFinder = new DefaultRuleFinder(dbClient, ruleDescriptionFormatter); this.delegate = this.defaultFinder; } @Override public void startCaching() { this.delegate = new CachingRuleFinder(dbClient, ruleDescriptionFormatter); } @Override public void stopCaching() { this.delegate = this.defaultFinder; } @Override @CheckForNull public Rule findByKey(String repositoryKey, String key) { return delegate.findByKey(repositoryKey, key); } @Override @CheckForNull public Rule findByKey(RuleKey key) { return delegate.findByKey(key); } @Override @CheckForNull public Rule find(RuleQuery query) { return delegate.find(query); } @Override public Collection<Rule> findAll(RuleQuery query) { return delegate.findAll(query); } @Override public Optional<RuleDto> findDtoByKey(RuleKey key) { return delegate.findDtoByKey(key); } @Override public Optional<RuleDto> findDtoByUuid(String uuid) { return delegate.findDtoByUuid(uuid); } @Override public Collection<RuleDto> findAll() { return delegate.findAll(); } }
2,785
28.326316
104
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/rule/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.rule; import javax.annotation.ParametersAreNonnullByDefault;
962
37.52
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/setting/SettingsChangeNotifier.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.setting; import com.google.common.annotations.VisibleForTesting; import org.sonar.api.config.GlobalPropertyChangeHandler; import javax.annotation.Nullable; import org.springframework.beans.factory.annotation.Autowired; public class SettingsChangeNotifier { @VisibleForTesting GlobalPropertyChangeHandler[] changeHandlers; @Autowired(required = false) public SettingsChangeNotifier(GlobalPropertyChangeHandler[] changeHandlers) { this.changeHandlers = changeHandlers; } @Autowired(required = false) public SettingsChangeNotifier() { this(new GlobalPropertyChangeHandler[0]); } public void onGlobalPropertyChange(String key, @Nullable String value) { GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create(key, value); for (GlobalPropertyChangeHandler changeHandler : changeHandlers) { changeHandler.onChange(change); } } }
1,790
34.82
118
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/setting/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.setting; import javax.annotation.ParametersAreNonnullByDefault;
964
39.208333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/telemetry/LicenseReader.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.telemetry; import java.util.Optional; import org.sonar.api.server.ServerSide; @ServerSide public interface LicenseReader { Optional<License> read(); interface License { String getType(); Boolean isValidLicense(); } }
1,102
31.441176
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/telemetry/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.telemetry; import javax.annotation.ParametersAreNonnullByDefault;
966
39.291667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/BooleanTypeValidation.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.util; import java.util.List; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.PropertyType; import static org.sonar.server.exceptions.BadRequestException.checkRequest; public class BooleanTypeValidation implements TypeValidation { @Override public String key() { return PropertyType.BOOLEAN.name(); } @Override public void validate(String value, @Nullable List<String> options) { checkRequest(StringUtils.equalsIgnoreCase(value, "true") || StringUtils.equalsIgnoreCase(value, "false"), "Value '%s' must be one of \"true\" or \"false\".", value); } }
1,500
33.906977
109
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/FloatTypeValidation.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.util; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.PropertyType; import org.sonar.server.exceptions.BadRequestException; import static java.lang.String.format; public class FloatTypeValidation implements TypeValidation { @Override public String key() { return PropertyType.FLOAT.name(); } @Override public void validate(String value, @Nullable List<String> options) { try { Double.parseDouble(value); } catch (NumberFormatException e) { throw BadRequestException.create(format("Value '%s' must be an floating point number.", value)); } } }
1,487
31.347826
102
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/GlobalLockManager.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.util; import org.sonar.db.property.InternalPropertiesDao; public interface GlobalLockManager { int LOCK_NAME_MAX_LENGTH = InternalPropertiesDao.LOCK_NAME_MAX_LENGTH; int DEFAULT_LOCK_DURATION_SECONDS = 180; /** * Try to acquire a lock on the given name for the {@link #DEFAULT_LOCK_DURATION_SECONDS default duration}, * using the generic locking mechanism of {@see org.sonar.db.property.InternalPropertiesDao}. * * @throws IllegalArgumentException if name's length is > {@link #LOCK_NAME_MAX_LENGTH} or empty */ boolean tryLock(String name); /** * Try to acquire a lock on the given name for the specified duration, * using the generic locking mechanism of {@see org.sonar.db.property.InternalPropertiesDao}. * * @throws IllegalArgumentException if name's length is > {@link #LOCK_NAME_MAX_LENGTH} or empty */ boolean tryLock(String name, int durationSecond); }
1,777
38.511111
109
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/GlobalLockManagerImpl.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.util; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import static org.sonar.api.utils.Preconditions.checkArgument; /** * Provide a simple mechanism to manage global locks across multiple nodes running in a cluster. * In the target use case multiple nodes try to execute something at around the same time, * and only the first should succeed, and the rest do nothing. */ @ComputeEngineSide @ServerSide public class GlobalLockManagerImpl implements GlobalLockManager { private final DbClient dbClient; public GlobalLockManagerImpl(DbClient dbClient) { this.dbClient = dbClient; } @Override public boolean tryLock(String name) { return tryLock(name, DEFAULT_LOCK_DURATION_SECONDS); } @Override public boolean tryLock(String name, int durationSecond) { checkArgument( !name.isEmpty() && name.length() <= LOCK_NAME_MAX_LENGTH, "name's length must be > 0 and <= %s: '%s'", LOCK_NAME_MAX_LENGTH, name); checkArgument(durationSecond > 0, "duration must be > 0: %s", durationSecond); try (DbSession dbSession = dbClient.openSession(false)) { boolean success = dbClient.internalPropertiesDao().tryLock(dbSession, name, durationSecond); dbSession.commit(); return success; } } }
2,218
34.222222
98
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/IntegerTypeValidation.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.util; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.PropertyType; import org.sonar.server.exceptions.BadRequestException; import static java.lang.String.format; public class IntegerTypeValidation implements TypeValidation { @Override public String key() { return PropertyType.INTEGER.name(); } @Override public void validate(String value, @Nullable List<String> options) { try { Integer.parseInt(value); } catch (NumberFormatException e) { throw BadRequestException.create(format("Value '%s' must be an integer.", value)); } } }
1,475
31.086957
88
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/LongTypeValidation.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.util; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.PropertyType; import org.sonar.server.exceptions.BadRequestException; import static java.lang.String.format; public class LongTypeValidation implements TypeValidation { @Override public String key() { return PropertyType.LONG.name(); } @Override public void validate(String value, @Nullable List<String> options) { try { Long.parseLong(value); } catch (NumberFormatException e) { throw BadRequestException.create(format("Value '%s' must be a long.", value)); } } }
1,461
32.227273
84
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/MetricLevelTypeValidation.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.util; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.PropertyType; import org.sonar.api.measures.Metric; import org.sonar.server.exceptions.BadRequestException; import static java.lang.String.format; public class MetricLevelTypeValidation implements TypeValidation { @Override public String key() { return PropertyType.METRIC_LEVEL.name(); } @Override public void validate(String value, @Nullable List<String> options) { try { Metric.Level.valueOf(value); } catch (IllegalArgumentException e) { throw BadRequestException.create(format("Value '%s' must be one of \"OK\", \"ERROR\".", value)); } } }
1,541
33.266667
102
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/StringListTypeValidation.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.util; import java.util.List; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.PropertyType; import static org.sonar.server.exceptions.BadRequestException.checkRequest; public class StringListTypeValidation implements TypeValidation { @Override public String key() { return PropertyType.SINGLE_SELECT_LIST.name(); } @Override public void validate(String value, @Nullable List<String> options) { checkRequest(options == null || options.contains(value), "Value '%s' must be one of : %s.", value, StringUtils.join(options, ", ")); } }
1,475
34.142857
136
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/StringTypeValidation.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.util; import org.sonar.api.PropertyType; import javax.annotation.Nullable; import java.util.List; public class StringTypeValidation implements TypeValidation { @Override public String key() { return PropertyType.STRING.name(); } @Override public void validate(String value, @Nullable List<String> options) { // Nothing to do } }
1,224
28.878049
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/TextTypeValidation.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.util; import org.sonar.api.PropertyType; import javax.annotation.Nullable; import java.util.List; public class TextTypeValidation implements TypeValidation { @Override public String key() { return PropertyType.TEXT.name(); } @Override public void validate(String value, @Nullable List<String> options) { // Nothing to do } }
1,220
28.780488
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/TypeValidation.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.util; import org.sonar.api.server.ServerSide; import javax.annotation.Nullable; import java.util.List; @ServerSide public interface TypeValidation { String key(); void validate(String value, @Nullable List<String> options); }
1,104
30.571429
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/TypeValidationModule.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.util; import org.sonar.core.platform.Module; public class TypeValidationModule extends Module { @Override protected void configureModule() { add( TypeValidations.class, IntegerTypeValidation.class, FloatTypeValidation.class, BooleanTypeValidation.class, TextTypeValidation.class, StringTypeValidation.class, StringListTypeValidation.class, LongTypeValidation.class, MetricLevelTypeValidation.class ); } }
1,343
32.6
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/TypeValidations.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.util; import java.util.List; import javax.annotation.Nullable; import org.sonar.api.server.ServerSide; import org.sonar.server.exceptions.BadRequestException; import static java.lang.String.format; @ServerSide public class TypeValidations { private final List<TypeValidation> typeValidationList; public TypeValidations(List<TypeValidation> typeValidationList) { this.typeValidationList = typeValidationList; } public void validate(List<String> values, String type, List<String> options) { TypeValidation typeValidation = findByKey(type); for (String value : values) { typeValidation.validate(value, options); } } public void validate(String value, String type, @Nullable List<String> options) { TypeValidation typeValidation = findByKey(type); typeValidation.validate(value, options); } private TypeValidation findByKey(String key) { return typeValidationList.stream().filter(input -> input.key().equals(key)).findFirst() .orElseThrow(() -> BadRequestException.create(format("Type '%s' is not valid.", key))); } }
1,948
34.436364
93
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/Validation.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.util; public class Validation { public static final String CANT_BE_EMPTY_MESSAGE = "%s can't be empty"; public static final String IS_TOO_SHORT_MESSAGE = "%s is too short (minimum is %s characters)"; public static final String IS_TOO_LONG_MESSAGE = "%s is too long (maximum is %s characters)"; public static final String IS_ALREADY_USED_MESSAGE = "%s has already been taken"; private Validation() { // only static methods } }
1,314
37.676471
97
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/main/java/org/sonar/server/util/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.util; import javax.annotation.ParametersAreNonnullByDefault;
962
37.52
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/app/ProcessCommandWrapperImplTest.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.app; import java.io.File; import java.io.IOException; import java.util.Random; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.MapSettings; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX; import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH; public class ProcessCommandWrapperImplTest { private static final int PROCESS_NUMBER = 2; @Rule public TemporaryFolder temp = new TemporaryFolder(); private MapSettings settings = new MapSettings(); @Test public void requestSQRestart_throws_IAE_if_process_index_property_not_set() { ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); assertThatThrownBy(processCommandWrapper::requestSQRestart) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Property process.index is not set"); } @Test public void requestSQRestart_throws_IAE_if_process_shared_path_property_not_set() { settings.setProperty(PROPERTY_PROCESS_INDEX, 1); ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); assertThatThrownBy(processCommandWrapper::requestSQRestart) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Property process.sharedDir is not set"); } @Test public void requestSQRestart_updates_shareMemory_file() throws IOException { File tmpDir = temp.newFolder().getAbsoluteFile(); settings.setProperty(PROPERTY_SHARED_PATH, tmpDir.getAbsolutePath()); settings.setProperty(PROPERTY_PROCESS_INDEX, PROCESS_NUMBER); ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings.asConfig()); underTest.requestSQRestart(); try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(tmpDir, PROCESS_NUMBER)) { assertThat(processCommands.askedForRestart()).isTrue(); } } @Test public void requestSQStop_throws_IAE_if_process_shared_path_property_not_set() { settings.setProperty(PROPERTY_PROCESS_INDEX, 1); ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); assertThatThrownBy(processCommandWrapper::requestHardStop) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Property process.sharedDir is not set"); } @Test public void requestSQStop_updates_shareMemory_file() throws IOException { File tmpDir = temp.newFolder().getAbsoluteFile(); settings.setProperty(PROPERTY_SHARED_PATH, tmpDir.getAbsolutePath()); settings.setProperty(PROPERTY_PROCESS_INDEX, PROCESS_NUMBER); ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings.asConfig()); underTest.requestHardStop(); try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(tmpDir, PROCESS_NUMBER)) { assertThat(processCommands.askedForHardStop()).isTrue(); } } @Test public void notifyOperational_throws_IAE_if_process_sharedDir_property_not_set() { settings.setProperty(PROPERTY_PROCESS_INDEX, 1); ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); assertThatThrownBy(processCommandWrapper::notifyOperational) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Property process.sharedDir is not set"); } @Test public void notifyOperational_throws_IAE_if_process_index_property_not_set() { ProcessCommandWrapperImpl processCommandWrapper = new ProcessCommandWrapperImpl(settings.asConfig()); assertThatThrownBy(processCommandWrapper::notifyOperational) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Property process.index is not set"); } @Test public void notifyOperational_updates_shareMemory_file() throws IOException { File tmpDir = temp.newFolder().getAbsoluteFile(); settings.setProperty(PROPERTY_SHARED_PATH, tmpDir.getAbsolutePath()); settings.setProperty(PROPERTY_PROCESS_INDEX, PROCESS_NUMBER); ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings.asConfig()); underTest.notifyOperational(); try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(tmpDir, PROCESS_NUMBER)) { assertThat(processCommands.isOperational()).isTrue(); } } @Test public void isCeOperational_reads_shared_memory_operational_flag_in_location_3() throws IOException { File tmpDir = temp.newFolder().getAbsoluteFile(); settings.setProperty(PROPERTY_SHARED_PATH, tmpDir.getAbsolutePath()); boolean expected = new Random().nextBoolean(); if (expected) { try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(tmpDir, 3)) { processCommands.setOperational(); } } ProcessCommandWrapperImpl underTest = new ProcessCommandWrapperImpl(settings.asConfig()); assertThat(underTest.isCeOperational()).isEqualTo(expected); } }
6,093
39.092105
109
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/branch/BranchFeatureProxyImplTest.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.branch; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class BranchFeatureProxyImplTest { private BranchFeatureExtension branchFeatureExtension = mock(BranchFeatureExtension.class); @Test public void return_false_when_no_extension() { assertThat(new BranchFeatureProxyImpl(null).isEnabled()).isFalse(); } @Test public void return_false_when_extension_returns_false() { when(branchFeatureExtension.isAvailable()).thenReturn(false); assertThat(new BranchFeatureProxyImpl(branchFeatureExtension).isEnabled()).isFalse(); } @Test public void return_true_when_extension_returns_ftrue() { when(branchFeatureExtension.isAvailable()).thenReturn(true); assertThat(new BranchFeatureProxyImpl(branchFeatureExtension).isEnabled()).isTrue(); } }
1,768
35.102041
93
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/BadConfigurationExceptionTest.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.exceptions; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class BadConfigurationExceptionTest { @Test public void testMethods() { BadConfigurationException ex = new BadConfigurationException("my-scope", "error"); assertThat(ex.scope()).isEqualTo("my-scope"); assertThat(ex).hasToString("BadConfigurationException{scope=my-scope, errors=[error]}"); } }
1,286
33.783784
92
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/BadRequestExceptionTest.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.exceptions; import java.util.Collections; import org.junit.Test; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class BadRequestExceptionTest { @Test public void text_error() { BadRequestException exception = BadRequestException.create("error"); assertThat(exception.getMessage()).isEqualTo("error"); } @Test public void create_exception_from_list() { BadRequestException underTest = BadRequestException.create(asList("error1", "error2")); assertThat(underTest.errors()).containsOnly("error1", "error2"); } @Test public void create_exception_from_var_args() { BadRequestException underTest = BadRequestException.create("error1", "error2"); assertThat(underTest.errors()).containsOnly("error1", "error2"); } @Test public void getMessage_return_first_error() { BadRequestException underTest = BadRequestException.create(asList("error1", "error2")); assertThat(underTest.getMessage()).isEqualTo("error1"); } @Test public void fail_when_creating_exception_with_empty_list() { assertThatThrownBy(() -> BadRequestException.create(Collections.emptyList())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("At least one error message is required"); } @Test public void fail_when_creating_exception_with_one_empty_element() { assertThatThrownBy(() -> BadRequestException.create(asList("error", ""))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Message cannot be empty"); } @Test public void fail_when_creating_exception_with_one_null_element() { assertThatThrownBy(() -> BadRequestException.create(asList("error", null))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Message cannot be empty"); } }
2,753
34.307692
91
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/MessageTest.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.exceptions; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MessageTest { @Test public void create_message() { Message message = Message.of("key1 %s", "param1"); assertThat(message.getMessage()).isEqualTo("key1 param1"); } @Test public void create_message_without_params() { Message message = Message.of("key1"); assertThat(message.getMessage()).isEqualTo("key1"); } @Test public void fail_when_message_is_null() { assertThatThrownBy(() -> Message.of(null)) .isInstanceOf(IllegalArgumentException.class); } @Test public void fail_when_message_is_empty() { assertThatThrownBy(() -> Message.of("")) .isInstanceOf(IllegalArgumentException.class); } @Test public void test_equals_and_hashcode() { Message message1 = Message.of("key1%s", "param1"); Message message2 = Message.of("key2%s", "param2"); Message message3 = Message.of("key1"); Message message4 = Message.of("key1%s", "param2"); Message sameAsMessage1 = Message.of("key1%s", "param1"); assertThat(message1) .isEqualTo(message1) .isNotEqualTo(message2) .isNotEqualTo(message3) .isNotEqualTo(message4) .isEqualTo(sameAsMessage1) .isNotNull() .isNotEqualTo(new Object()) .hasSameHashCodeAs(message1) .hasSameHashCodeAs(sameAsMessage1); assertThat(message1.hashCode()) .isNotEqualTo(message2.hashCode()) .isNotEqualTo(message3.hashCode()) .isNotEqualTo(message4.hashCode()); } @Test public void to_string() { assertThat(Message.of("key1 %s", "param1")).hasToString("key1 param1"); assertThat(Message.of("key1")).hasToString("key1"); assertThat(Message.of("key1", (Object[])null)).hasToString("key1"); } }
2,731
31.52381
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/NotFoundExceptionTest.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.exceptions; import java.util.Optional; import org.junit.Test; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.exceptions.NotFoundException.checkFoundWithOptional; public class NotFoundExceptionTest { @Test public void http_code_is_404() { NotFoundException underTest = new NotFoundException(randomAlphabetic(12)); assertThat(underTest.httpCode()).isEqualTo(404); } @Test public void message_is_constructor_argument() { String message = randomAlphabetic(12); NotFoundException underTest = new NotFoundException(message); assertThat(underTest.getMessage()).isEqualTo(message); } @Test public void checkFound_type_throws_NotFoundException_if_parameter_is_null() { String message = randomAlphabetic(12); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> checkFound(null, message)) .withMessage(message); } @Test public void checkFound_type_throws_NotFoundException_if_parameter_is_null_and_formats_message() { String message = "foo %s"; assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> checkFound(null, message, "bar")) .withMessage("foo bar"); } @Test public void checkFound_return_parameter_if_parameter_is_not_null() { String message = randomAlphabetic(12); Object o = new Object(); assertThat(checkFound(o, message)).isSameAs(o); } @Test public void checkFoundWithOptional_throws_NotFoundException_if_empty() { String message = randomAlphabetic(12); assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> checkFoundWithOptional(Optional.empty(), message)) .withMessage(message); } @Test public void checkFoundWithOptional_throws_NotFoundException_if_empty_and_formats_message() { String message = "foo %s"; assertThatExceptionOfType(NotFoundException.class) .isThrownBy(() -> checkFoundWithOptional(Optional.empty(), message, "bar")) .withMessage("foo bar"); } @Test public void checkFoundWithOptional_return_content_of_if_not_empty() { String message = randomAlphabetic(12); Object o = new Object(); assertThat(checkFoundWithOptional(Optional.of(o), message)).isSameAs(o); } }
3,345
34.221053
99
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/ServerExceptionTest.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.exceptions; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ServerExceptionTest { @Test public void should_create_exception_with_status() { ServerException exception = new ServerException(400, "error!"); assertThat(exception.httpCode()).isEqualTo(400); } @Test public void should_create_exception_with_status_and_message() { ServerException exception = new ServerException(404, "Not found"); assertThat(exception.httpCode()).isEqualTo(404); assertThat(exception.getMessage()).isEqualTo("Not found"); } }
1,455
34.512195
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/exceptions/TemplateMatchingKeyExceptionTest.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.exceptions; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class TemplateMatchingKeyExceptionTest { @Test public void testMethods() { TemplateMatchingKeyException ex = new TemplateMatchingKeyException("error"); assertThat(ex).hasToString("TemplateMatchingKeyException{errors=[error]}"); } }
1,220
32.916667
80
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/http/JavaxHttpRequestTest.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.http; import java.io.BufferedReader; import java.io.IOException; import java.util.Collections; import java.util.Enumeration; import javax.servlet.http.HttpServletRequest; import org.junit.Test; import org.sonar.api.server.http.Cookie; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class JavaxHttpRequestTest { @Test public void delegate_methods() throws IOException { HttpServletRequest requestMock = mock(HttpServletRequest.class); Enumeration<String> enumeration = Collections.enumeration(Collections.emptySet()); when(requestMock.getHeaderNames()).thenReturn(enumeration); when(requestMock.getRemoteAddr()).thenReturn("192.168.0.1"); when(requestMock.getServletPath()).thenReturn("/servlet-path"); BufferedReader bufferedReader = mock(BufferedReader.class); when(requestMock.getReader()).thenReturn(bufferedReader); javax.servlet.http.Cookie[] cookies = new javax.servlet.http.Cookie[0]; when(requestMock.getCookies()).thenReturn(cookies); when(requestMock.getServerPort()).thenReturn(80); when(requestMock.isSecure()).thenReturn(true); when(requestMock.getScheme()).thenReturn("https"); when(requestMock.getServerName()).thenReturn("hostname"); when(requestMock.getRequestURL()).thenReturn(new StringBuffer("https://hostname:80/path")); when(requestMock.getRequestURI()).thenReturn("/path"); when(requestMock.getQueryString()).thenReturn("param1=value1"); when(requestMock.getContextPath()).thenReturn("/path"); when(requestMock.getMethod()).thenReturn("POST"); when(requestMock.getParameter("param1")).thenReturn("value1"); when(requestMock.getParameterValues("param1")).thenReturn(new String[] {"value1"}); when(requestMock.getHeader("header1")).thenReturn("hvalue1"); Enumeration<String> headers = mock(Enumeration.class); when(requestMock.getHeaders("header1")).thenReturn(headers); JavaxHttpRequest underTest = new JavaxHttpRequest(requestMock); assertThat(underTest.getDelegate()).isSameAs(requestMock); assertThat(underTest.getServerPort()).isEqualTo(80); assertThat(underTest.isSecure()).isTrue(); assertThat(underTest.getScheme()).isEqualTo("https"); assertThat(underTest.getServerName()).isEqualTo("hostname"); assertThat(underTest.getRequestURL()).isEqualTo("https://hostname:80/path"); assertThat(underTest.getRequestURI()).isEqualTo("/path"); assertThat(underTest.getQueryString()).isEqualTo("param1=value1"); assertThat(underTest.getContextPath()).isEqualTo("/path"); assertThat(underTest.getMethod()).isEqualTo("POST"); assertThat(underTest.getParameter("param1")).isEqualTo("value1"); assertThat(underTest.getParameterValues("param1")).containsExactly("value1"); assertThat(underTest.getHeader("header1")).isEqualTo("hvalue1"); assertThat(underTest.getHeaders("header1")).isEqualTo(headers); assertThat(underTest.getHeaderNames()).isEqualTo(enumeration); assertThat(underTest.getRemoteAddr()).isEqualTo("192.168.0.1"); assertThat(underTest.getServletPath()).isEqualTo("/servlet-path"); assertThat(underTest.getReader()).isEqualTo(bufferedReader); assertThat(underTest.getCookies()).isEqualTo(cookies); underTest.setAttribute("name", "value"); verify(requestMock).setAttribute("name", "value"); } @Test public void delegate_methods_for_cookie() { javax.servlet.http.Cookie mockCookie = new javax.servlet.http.Cookie("name", "value"); mockCookie.setSecure(true); mockCookie.setPath("path"); mockCookie.setHttpOnly(true); mockCookie.setMaxAge(100); Cookie cookie = new JavaxHttpRequest.JavaxCookie(mockCookie); assertThat(cookie.getName()).isEqualTo("name"); assertThat(cookie.getValue()).isEqualTo("value"); assertThat(cookie.getPath()).isEqualTo("path"); assertThat(cookie.isSecure()).isTrue(); assertThat(cookie.isHttpOnly()).isTrue(); assertThat(cookie.getMaxAge()).isEqualTo(100); } }
4,979
45.542056
95
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/http/JavaxHttpResponseTest.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.http; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.sonar.api.server.http.Cookie; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class JavaxHttpResponseTest { @Test public void delegate_methods() throws IOException { HttpServletResponse responseMock = mock(HttpServletResponse.class); when(responseMock.getHeader("h1")).thenReturn("hvalue1"); when(responseMock.getHeaders("h1")).thenReturn(List.of("hvalue1")); when(responseMock.getStatus()).thenReturn(200); ServletOutputStream outputStream = mock(ServletOutputStream.class); when(responseMock.getOutputStream()).thenReturn(outputStream); PrintWriter writer = mock(PrintWriter.class); when(responseMock.getWriter()).thenReturn(writer); JavaxHttpResponse underTest = new JavaxHttpResponse(responseMock); assertThat(underTest.getDelegate()).isSameAs(responseMock); assertThat(underTest.getHeader("h1")).isEqualTo("hvalue1"); assertThat(underTest.getHeaders("h1")).asList().containsExactly("hvalue1"); assertThat(underTest.getStatus()).isEqualTo(200); assertThat(underTest.getWriter()).isEqualTo(writer); assertThat(underTest.getOutputStream()).isEqualTo(outputStream); underTest.addHeader("h2", "hvalue2"); underTest.setHeader("h3", "hvalue3"); underTest.setStatus(201); underTest.setContentType("text/plain"); underTest.sendRedirect("http://redirect"); underTest.setCharacterEncoding("UTF-8"); Cookie cookie = mock(Cookie.class); when(cookie.getName()).thenReturn("name"); when(cookie.getValue()).thenReturn("value"); underTest.addCookie(cookie); verify(responseMock).addHeader("h2", "hvalue2"); verify(responseMock).setHeader("h3", "hvalue3"); verify(responseMock).setStatus(201); verify(responseMock).setContentType("text/plain"); verify(responseMock).sendRedirect("http://redirect"); verify(responseMock).setCharacterEncoding("UTF-8"); verify(responseMock).addCookie(any(javax.servlet.http.Cookie.class)); } }
3,230
40.423077
79
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginConsentVerifierTest.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; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.core.extension.PluginRiskConsent; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.property.PropertyDto; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.config.CorePropertyDefinitions.PLUGINS_RISK_CONSENT; import static org.sonar.core.extension.PluginRiskConsent.ACCEPTED; import static org.sonar.core.extension.PluginRiskConsent.NOT_ACCEPTED; import static org.sonar.core.extension.PluginRiskConsent.REQUIRED; import static org.sonar.core.plugin.PluginType.BUNDLED; import static org.sonar.core.plugin.PluginType.EXTERNAL; public class PluginConsentVerifierTest { @Rule public DbTester db = DbTester.create(System2.INSTANCE); @Rule public LogTester logTester = new LogTester(); private final DbClient dbClient = db.getDbClient(); private final ServerPluginRepository pluginRepository = mock(ServerPluginRepository.class); private final PluginConsentVerifier underTest = new PluginConsentVerifier(pluginRepository, dbClient); @Test public void require_consent_when_exist_external_plugins_and_not_accepted() { setupExternalPluginConsent(NOT_ACCEPTED); setupExternalPlugin(); underTest.start(); assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT)) .extracting(PropertyDto::getValue) .isEqualTo(REQUIRED.name()); } @Test public void require_consent_when_exist_external_plugins_and_consent_property_not_exist() { setupExternalPlugin(); underTest.start(); assertThat(logTester.logs(Level.WARN)).contains("Plugin(s) detected. Plugins are not provided by SonarSource" + " and are therefore installed at your own risk. A SonarQube administrator needs to acknowledge this risk once logged in."); assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT)) .extracting(PropertyDto::getValue) .isEqualTo(REQUIRED.name()); } @Test public void consent_does_not_change_when_value_is_accepted() { setupExternalPluginConsent(ACCEPTED); setupExternalPlugin(); underTest.start(); assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT)) .extracting(PropertyDto::getValue) .isEqualTo(ACCEPTED.name()); } @Test public void consent_does_not_change_when_value_is_required() { setupExternalPluginConsent(REQUIRED); setupExternalPlugin(); underTest.start(); assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT)) .extracting(PropertyDto::getValue) .isEqualTo(REQUIRED.name()); } @Test public void consent_should_be_not_accepted_when_there_is_no_external_plugin_and_never_been_accepted() { setupExternalPluginConsent(REQUIRED); setupBundledPlugin(); underTest.start(); assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT)).isNull(); } @Test public void do_nothing_when_there_is_no_external_plugin() { setupExternalPluginConsent(NOT_ACCEPTED); setupBundledPlugin(); underTest.start(); assertThat(dbClient.propertiesDao().selectGlobalProperty(PLUGINS_RISK_CONSENT)) .extracting(PropertyDto::getValue) .isEqualTo(NOT_ACCEPTED.name()); } private void setupExternalPluginConsent(PluginRiskConsent pluginRiskConsent) { dbClient.propertiesDao().saveProperty(new PropertyDto() .setKey(PLUGINS_RISK_CONSENT) .setValue(pluginRiskConsent.name())); } private void setupExternalPlugin() { ServerPlugin plugin = mock(ServerPlugin.class); when(plugin.getType()).thenReturn(EXTERNAL); when(pluginRepository.getPlugins()).thenReturn(asList(plugin)); } private void setupBundledPlugin() { ServerPlugin plugin = mock(ServerPlugin.class); when(plugin.getType()).thenReturn(BUNDLED); when(pluginRepository.getPlugins()).thenReturn(asList(plugin)); } }
5,063
34.412587
133
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginDownloaderTest.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; import java.io.File; import java.net.URI; import java.util.Optional; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.ArgumentMatcher; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.sonar.api.utils.HttpDownloader; import org.sonar.core.platform.PluginInfo; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.platform.ServerFileSystem; import org.sonar.updatecenter.common.Plugin; import org.sonar.updatecenter.common.Release; import org.sonar.updatecenter.common.UpdateCenter; import org.sonar.updatecenter.common.Version; import static com.google.common.collect.Lists.newArrayList; import static org.apache.commons.io.FileUtils.copyFileToDirectory; import static org.apache.commons.io.FileUtils.touch; import static org.apache.commons.io.FilenameUtils.separatorsToUnix; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.updatecenter.common.Version.create; public class PluginDownloaderTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); private File downloadDir; private UpdateCenterMatrixFactory updateCenterMatrixFactory; private UpdateCenter updateCenter; private HttpDownloader httpDownloader; private PluginDownloader pluginDownloader; @Before public void before() throws Exception { updateCenterMatrixFactory = mock(UpdateCenterMatrixFactory.class); updateCenter = mock(UpdateCenter.class); when(updateCenterMatrixFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.of(updateCenter)); httpDownloader = mock(HttpDownloader.class); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock inv) throws Throwable { File toFile = (File) inv.getArguments()[1]; touch(toFile); return null; } }).when(httpDownloader).download(any(URI.class), any(File.class)); ServerFileSystem fs = mock(ServerFileSystem.class); downloadDir = testFolder.newFolder("downloads"); when(fs.getDownloadedPluginsDir()).thenReturn(downloadDir); pluginDownloader = new PluginDownloader(updateCenterMatrixFactory, httpDownloader, fs); } @After public void stop() { pluginDownloader.stop(); } @Test public void clean_temporary_files_at_startup() throws Exception { touch(new File(downloadDir, "sonar-php.jar")); touch(new File(downloadDir, "sonar-js.jar.tmp")); assertThat(downloadDir.listFiles()).hasSize(2); pluginDownloader.start(); File[] files = downloadDir.listFiles(); assertThat(files).hasSize(1); assertThat(files[0].getName()).isEqualTo("sonar-php.jar"); } @Test public void download_from_url() { Plugin test = Plugin.factory("test"); Release test10 = new Release(test, "1.0").setDownloadUrl("http://server/test-1.0.jar"); test.addRelease(test10); when(updateCenter.findInstallablePlugins("foo", create("1.0"))).thenReturn(newArrayList(test10)); pluginDownloader.start(); pluginDownloader.download("foo", create("1.0")); // SONAR-4523: do not corrupt JAR files when restarting the server while a plugin is being downloaded. // The JAR file is downloaded in a temp file verify(httpDownloader).download(any(URI.class), argThat(new HasFileName("test-1.0.jar.tmp"))); assertThat(new File(downloadDir, "test-1.0.jar")).exists(); assertThat(new File(downloadDir, "test-1.0.jar.tmp")).doesNotExist(); } @Test public void download_when_update_center_is_unavailable_with_no_exception_thrown() { when(updateCenterMatrixFactory.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty()); Plugin test = Plugin.factory("test"); Release test10 = new Release(test, "1.0").setDownloadUrl("http://server/test-1.0.jar"); test.addRelease(test10); pluginDownloader.start(); pluginDownloader.download("foo", create("1.0")); } /** * SONAR-4685 */ @Test public void download_from_redirect_url() { Plugin test = Plugin.factory("plugintest"); Release test10 = new Release(test, "1.0").setDownloadUrl("http://server/redirect?r=release&g=test&a=test&v=1.0&e=jar"); test.addRelease(test10); when(updateCenter.findInstallablePlugins("foo", create("1.0"))).thenReturn(newArrayList(test10)); pluginDownloader.start(); pluginDownloader.download("foo", create("1.0")); // SONAR-4523: do not corrupt JAR files when restarting the server while a plugin is being downloaded. // The JAR file is downloaded in a temp file verify(httpDownloader).download(any(URI.class), argThat(new HasFileName("plugintest-1.0.jar.tmp"))); assertThat(new File(downloadDir, "plugintest-1.0.jar")).exists(); assertThat(new File(downloadDir, "plugintest-1.0.jar.tmp")).doesNotExist(); } @Test public void throw_exception_if_download_dir_is_invalid() throws Exception { ServerFileSystem fs = mock(ServerFileSystem.class); // download dir is a file instead of being a directory File downloadDir = testFolder.newFile(); when(fs.getDownloadedPluginsDir()).thenReturn(downloadDir); pluginDownloader = new PluginDownloader(updateCenterMatrixFactory, httpDownloader, fs); try { pluginDownloader.start(); fail(); } catch (IllegalStateException e) { // ok } } @Test public void fail_if_no_compatible_plugin_found() { assertThatThrownBy(() -> pluginDownloader.download("foo", create("1.0"))) .isInstanceOf(BadRequestException.class); } @Test public void download_from_file() throws Exception { Plugin test = Plugin.factory("test"); File file = testFolder.newFile("test-1.0.jar"); file.createNewFile(); Release test10 = new Release(test, "1.0").setDownloadUrl("file://" + separatorsToUnix(file.getAbsolutePath())); test.addRelease(test10); when(updateCenter.findInstallablePlugins("foo", create("1.0"))).thenReturn(newArrayList(test10)); pluginDownloader.start(); pluginDownloader.download("foo", create("1.0")); verify(httpDownloader, never()).download(any(URI.class), any(File.class)); assertThat(noDownloadedFiles()).isPositive(); } @Test public void throw_exception_if_could_not_download() { Plugin test = Plugin.factory("test"); Release test10 = new Release(test, "1.0").setDownloadUrl("file://not_found"); test.addRelease(test10); when(updateCenter.findInstallablePlugins("foo", create("1.0"))).thenReturn(newArrayList(test10)); pluginDownloader.start(); try { pluginDownloader.download("foo", create("1.0")); fail(); } catch (IllegalStateException e) { // ok } } @Test public void throw_exception_if_download_fail() { Plugin test = Plugin.factory("test"); Release test10 = new Release(test, "1.0").setDownloadUrl("http://server/test-1.0.jar"); test.addRelease(test10); when(updateCenter.findInstallablePlugins("foo", create("1.0"))).thenReturn(newArrayList(test10)); doThrow(new RuntimeException()).when(httpDownloader).download(any(URI.class), any(File.class)); pluginDownloader.start(); try { pluginDownloader.download("foo", create("1.0")); fail(); } catch (IllegalStateException e) { // ok } } @Test public void read_download_folder() throws Exception { pluginDownloader.start(); assertThat(noDownloadedFiles()).isZero(); copyFileToDirectory(TestProjectUtils.jarOf("test-base-plugin"), downloadDir); assertThat(pluginDownloader.getDownloadedPlugins()).hasSize(1); PluginInfo info = pluginDownloader.getDownloadedPlugins().iterator().next(); assertThat(info.getKey()).isEqualTo("testbase"); assertThat(info.getName()).isEqualTo("Base Plugin"); assertThat(info.getVersion()).isEqualTo(Version.create("0.1-SNAPSHOT")); assertThat(info.getMainClass()).isEqualTo("BasePlugin"); } @Test public void getDownloadedPluginFilenames_reads_plugin_info_of_files_in_download_folder() throws Exception { pluginDownloader.start(); assertThat(pluginDownloader.getDownloadedPlugins()).isEmpty(); File file1 = new File(downloadDir, "file1.jar"); file1.createNewFile(); File file2 = new File(downloadDir, "file2.jar"); file2.createNewFile(); assertThat(noDownloadedFiles()).isEqualTo(2); } @Test public void cancel_downloads() throws Exception { File file1 = new File(downloadDir, "file1.jar"); file1.createNewFile(); File file2 = new File(downloadDir, "file2.jar"); file2.createNewFile(); pluginDownloader.start(); assertThat(noDownloadedFiles()).isPositive(); pluginDownloader.cancelDownloads(); assertThat(noDownloadedFiles()).isZero(); } private int noDownloadedFiles() { return downloadDir.listFiles((file, name) -> name.endsWith(".jar")).length; } // SONAR-5011 @Test public void download_common_transitive_dependency() { Plugin test1 = Plugin.factory("test1"); Release test1R = new Release(test1, "1.0").setDownloadUrl("http://server/test1-1.0.jar"); test1.addRelease(test1R); Plugin test2 = Plugin.factory("test2"); Release test2R = new Release(test2, "1.0").setDownloadUrl("http://server/test2-1.0.jar"); test2.addRelease(test2R); Plugin testDep = Plugin.factory("testdep"); Release testDepR = new Release(testDep, "1.0").setDownloadUrl("http://server/testdep-1.0.jar"); testDep.addRelease(testDepR); when(updateCenter.findInstallablePlugins("test1", create("1.0"))).thenReturn(newArrayList(test1R, testDepR)); when(updateCenter.findInstallablePlugins("test2", create("1.0"))).thenReturn(newArrayList(test2R, testDepR)); pluginDownloader.start(); pluginDownloader.download("test1", create("1.0")); pluginDownloader.download("test2", create("1.0")); assertThat(new File(downloadDir, "test1-1.0.jar")).exists(); assertThat(new File(downloadDir, "test2-1.0.jar")).exists(); assertThat(new File(downloadDir, "testdep-1.0.jar")).exists(); } static class HasFileName implements ArgumentMatcher<File> { private final String name; HasFileName(String name) { this.name = name; } @Override public boolean matches(File file) { return file.getName().equals(name); } } }
11,726
35.646875
123
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginFilesAndMd5Test.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; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; public class PluginFilesAndMd5Test { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void getters() throws IOException { File jarFile = temp.newFile(); Files.write(jarFile.toPath(), "f1".getBytes(StandardCharsets.UTF_8)); File jarFileCompressed = temp.newFile(); Files.write(jarFileCompressed.toPath(), "f1compressed".getBytes(StandardCharsets.UTF_8)); PluginFilesAndMd5.FileAndMd5 jar = new PluginFilesAndMd5.FileAndMd5(jarFile); PluginFilesAndMd5.FileAndMd5 jarCompressed = new PluginFilesAndMd5.FileAndMd5(jarFileCompressed); PluginFilesAndMd5 underTest = new PluginFilesAndMd5(jar, jarCompressed); assertThat(underTest.getCompressedJar().getFile()).isEqualTo(jarFileCompressed); assertThat(underTest.getCompressedJar().getMd5()).isEqualTo("a0d076c0fc9f11ec68740fed5aa3ce38"); assertThat(underTest.getLoadedJar().getFile()).isEqualTo(jarFile); assertThat(underTest.getLoadedJar().getMd5()).isEqualTo("bd19836ddb62c11c55ab251ccaca5645"); } @Test public void fail_if_cant_get_md5() throws IOException { File jarFile = new File("nonexisting"); Assert.assertThrows("Fail to compute md5", IllegalStateException.class, () -> new PluginFilesAndMd5.FileAndMd5(jarFile)); } }
2,437
37.698413
125
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginJarLoaderTest.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; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.HashSet; import java.util.Set; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import javax.annotation.Nullable; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.SonarRuntime; import org.sonar.api.utils.MessageException; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.platform.PluginInfo; import org.sonar.server.platform.ServerFileSystem; import org.sonar.updatecenter.common.PluginManifest; import static java.util.jar.Attributes.Name.MANIFEST_VERSION; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PluginJarLoaderTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Rule public LogTester logs = new LogTester(); private final ServerFileSystem fs = mock(ServerFileSystem.class); private final Set<String> blacklisted = new HashSet<>(); private final SonarRuntime sonarRuntime = mock(SonarRuntime.class); private final PluginJarLoader underTest = new PluginJarLoader(fs, sonarRuntime, blacklisted); @Before public void setUp() throws IOException { when(sonarRuntime.getApiVersion()).thenReturn(org.sonar.api.utils.Version.parse("5.2")); when(fs.getDeployedPluginsDir()).thenReturn(temp.newFolder("deployed")); when(fs.getDownloadedPluginsDir()).thenReturn(temp.newFolder("downloaded")); when(fs.getHomeDir()).thenReturn(temp.newFolder("home")); when(fs.getInstalledExternalPluginsDir()).thenReturn(temp.newFolder("external")); when(fs.getInstalledBundledPluginsDir()).thenReturn(temp.newFolder("bundled")); when(fs.getTempDir()).thenReturn(temp.newFolder("temp")); } @Test public void load_installed_bundled_and_external_plugins() throws Exception { copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); copyTestPluginTo("test-extend-plugin", fs.getInstalledBundledPluginsDir()); Collection<ServerPluginInfo> loadedPlugins = underTest.loadPlugins(); assertThat(loadedPlugins).extracting(PluginInfo::getKey).containsOnly("testbase", "testextend"); } @Test public void dont_fail_if_directories_dont_exist() { FileUtils.deleteQuietly(fs.getInstalledExternalPluginsDir()); FileUtils.deleteQuietly(fs.getInstalledBundledPluginsDir()); FileUtils.deleteQuietly(fs.getDownloadedPluginsDir()); Collection<ServerPluginInfo> loadedPlugins = underTest.loadPlugins(); assertThat(loadedPlugins).extracting(PluginInfo::getKey).isEmpty(); } @Test public void update_downloaded_plugin() throws IOException { File jar = createJar(fs.getDownloadedPluginsDir(), "plugin1", "main", null, "2.0"); createJar(fs.getInstalledExternalPluginsDir(), "plugin1", "main", null, "1.0"); underTest.loadPlugins(); assertThat(logs.logs()).contains("Plugin plugin1 [plugin1] updated to version 2.0"); assertThat(Files.list(fs.getInstalledExternalPluginsDir().toPath())).extracting(Path::getFileName).containsOnly(jar.toPath().getFileName()); } @Test public void move_downloaded_plugins_to_external() throws Exception { copyTestPluginTo("test-base-plugin", fs.getDownloadedPluginsDir()); copyTestPluginTo("test-extend-plugin", fs.getInstalledExternalPluginsDir()); assertThat(Files.list(fs.getInstalledExternalPluginsDir().toPath())).hasSize(1); Collection<ServerPluginInfo> loadedPlugins = underTest.loadPlugins(); assertThat(loadedPlugins).extracting(PluginInfo::getKey).containsOnly("testbase", "testextend"); assertThat(fs.getDownloadedPluginsDir()).isEmptyDirectory(); assertThat(Files.list(fs.getInstalledExternalPluginsDir().toPath())).hasSize(2); } @Test public void no_plugins_at_startup() { assertThat(underTest.loadPlugins()).isEmpty(); } @Test public void test_plugin_requirements_at_startup() throws Exception { copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); copyTestPluginTo("test-require-plugin", fs.getInstalledExternalPluginsDir()); assertThat(underTest.loadPlugins()).extracting(PluginInfo::getKey).containsOnly("testbase", "testrequire"); } @Test public void plugin_is_ignored_if_required_plugin_is_missing_at_startup() throws Exception { copyTestPluginTo("test-require-plugin", fs.getInstalledExternalPluginsDir()); // plugin is not installed as test-base-plugin is missing assertThat(underTest.loadPlugins()).isEmpty(); assertThat(logs.logs()).contains("Plugin Test Require Plugin [testrequire] is ignored because the required plugin [testbase] is not installed"); } @Test public void install_plugin_and_its_extension_plugins_at_startup() throws Exception { copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); copyTestPluginTo("test-extend-plugin", fs.getInstalledExternalPluginsDir()); // both plugins are installed assertThat(underTest.loadPlugins()).extracting(PluginInfo::getKey).containsOnly("testbase", "testextend"); } /** * Some plugins can only extend the classloader of base plugin, without declaring new extensions. */ @Test public void plugin_is_compatible_if_no_entry_point_class_but_extend_other_plugin() throws IOException { createJar(fs.getInstalledExternalPluginsDir(), "base", "org.bar.Bar", null); createJar(fs.getInstalledExternalPluginsDir(), "foo", null, "base"); assertThat(underTest.loadPlugins()).extracting(PluginInfo::getKey).containsOnly("base", "foo"); } @Test public void extension_plugin_is_ignored_if_base_plugin_is_missing_at_startup() throws Exception { copyTestPluginTo("test-extend-plugin", fs.getInstalledExternalPluginsDir()); assertThat(underTest.loadPlugins()).isEmpty(); assertThat(logs.logs()).contains("Plugin Test Extend Plugin [testextend] is ignored because its base plugin [testbase] is not installed"); } @Test public void plugin_is_ignored_if_required_plugin_is_too_old_at_startup() throws Exception { copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); copyTestPluginTo("test-requirenew-plugin", fs.getInstalledExternalPluginsDir()); // the plugin "requirenew" is not installed as it requires base 0.2+ to be installed. assertThat(underTest.loadPlugins()).extracting(PluginInfo::getKey).containsOnly("testbase"); assertThat(logs.logs()).contains("Plugin Test Require New Plugin [testrequire] is ignored because the version 0.2 of required plugin [testbase] is not installed"); } @Test public void blacklisted_plugin_is_automatically_deleted() throws Exception { blacklisted.add("testbase"); blacklisted.add("issuesreport"); File jar = copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); Collection<ServerPluginInfo> loadedPlugins = underTest.loadPlugins(); // plugin is not installed and file is deleted assertThat(loadedPlugins).isEmpty(); assertThat(jar).doesNotExist(); } @Test public void warn_if_plugin_has_no_entry_point_class() throws IOException { createJar(fs.getInstalledExternalPluginsDir(), "test", null, null); assertThat(underTest.loadPlugins()).isEmpty(); assertThat(logs.logs()).contains("Plugin test [test] is ignored because entry point class is not defined"); } @Test public void fail_if_external_plugin_has_same_key_has_bundled_plugin() throws IOException { File jar = createJar(fs.getInstalledExternalPluginsDir(), "plugin1", "main", null); createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledExternalPluginsDir()); assertThatThrownBy(() -> underTest.loadPlugins()) .isInstanceOf(MessageException.class) .hasMessageContaining("Found a plugin 'plugin1' in the directory '" + dir + "' with the same key [plugin1] as a built-in feature 'plugin1'. " + "Please remove '" + new File(dir, jar.getName()) + "'"); } @Test public void fail_if_downloaded_plugin_has_same_key_has_bundled() throws IOException { File downloaded = createJar(fs.getDownloadedPluginsDir(), "plugin1", "main", null); createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getDownloadedPluginsDir()); assertThatThrownBy(() -> underTest.loadPlugins()) .isInstanceOf(MessageException.class) .hasMessage("Fail to update plugin: plugin1. Built-in feature with same key already exists: plugin1. " + "Move or delete plugin from " + dir + " directory"); } @Test public void fail_if_external_plugins_have_same_key() throws IOException { File jar1 = createJar(fs.getInstalledExternalPluginsDir(), "plugin1", "main", null); File jar2 = createJar(fs.getInstalledExternalPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledExternalPluginsDir()); assertThatThrownBy(() -> underTest.loadPlugins()) .isInstanceOf(MessageException.class) .hasMessageContaining("Found two versions of the plugin 'plugin1' [plugin1] in the directory '" + dir + "'. Please remove ") .hasMessageContaining(jar2.getName()) .hasMessageContaining(jar1.getName()); } @Test public void fail_if_bundled_plugins_have_same_key() throws IOException { File jar1 = createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); File jar2 = createJar(fs.getInstalledBundledPluginsDir(), "plugin1", "main", null); String dir = getDirName(fs.getInstalledBundledPluginsDir()); assertThatThrownBy(() -> underTest.loadPlugins()) .isInstanceOf(MessageException.class) .hasMessageContaining("Found two versions of the plugin plugin1 [plugin1] in the directory " + dir + ". Please remove one of ") .hasMessageContaining(jar2.getName()) .hasMessageContaining(jar1.getName()); } @Test public void fail_when_sqale_plugin_is_installed() throws Exception { copyTestPluginTo("fake-sqale-plugin", fs.getInstalledExternalPluginsDir()); assertThatThrownBy(() -> underTest.loadPlugins()) .isInstanceOf(MessageException.class) .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'sqale'"); } @Test public void fail_when_incompatible_plugins_are_installed() throws Exception { createJar(fs.getInstalledExternalPluginsDir(), "sqale", "main", null); createJar(fs.getInstalledExternalPluginsDir(), "scmgit", "main", null); createJar(fs.getInstalledExternalPluginsDir(), "scmsvn", "main", null); assertThatThrownBy(() -> underTest.loadPlugins()) .isInstanceOf(MessageException.class) .hasMessage("The following plugins are no longer compatible with this version of SonarQube: 'scmgit', 'scmsvn', 'sqale'"); } @Test public void fail_when_report_is_installed() throws Exception { copyTestPluginTo("fake-report-plugin", fs.getInstalledExternalPluginsDir()); assertThatThrownBy(() -> underTest.loadPlugins()) .isInstanceOf(MessageException.class) .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'report'"); } @Test public void fail_when_views_is_installed() throws Exception { copyTestPluginTo("fake-views-plugin", fs.getInstalledExternalPluginsDir()); assertThatThrownBy(() -> underTest.loadPlugins()) .isInstanceOf(MessageException.class) .hasMessage("The following plugin is no longer compatible with this version of SonarQube: 'views'"); } @Test public void fail_if_plugin_does_not_support_plugin_api_version() throws Exception { when(sonarRuntime.getApiVersion()).thenReturn(org.sonar.api.utils.Version.parse("1.0")); copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); assertThatThrownBy(() -> underTest.loadPlugins()) .hasMessage("Plugin Base Plugin [testbase] requires at least Sonar Plugin API version 4.5.4 (current: 1.0)"); } private static File copyTestPluginTo(String testPluginName, File toDir) throws IOException { File jar = TestProjectUtils.jarOf(testPluginName); // file is copied because it's supposed to be moved by the test FileUtils.copyFileToDirectory(jar, toDir); return new File(toDir, jar.getName()); } private static String getDirName(File dir) { Path path = dir.toPath(); return new File(path.getName(path.getNameCount() - 2).toString(), path.getName(path.getNameCount() - 1).toString()).toString(); } private static File createJar(File dir, String key, @Nullable String mainClass, @Nullable String basePlugin) throws IOException { return createJar(dir, key, mainClass, basePlugin, null); } private static File createJar(File dir, String key, @Nullable String mainClass, @Nullable String basePlugin, @Nullable String version) throws IOException { Manifest manifest = new Manifest(); manifest.getMainAttributes().putValue(PluginManifest.KEY, key); manifest.getMainAttributes().putValue(PluginManifest.NAME, key); if (version != null) { manifest.getMainAttributes().putValue(PluginManifest.VERSION, version); } if (mainClass != null) { manifest.getMainAttributes().putValue(PluginManifest.MAIN_CLASS, mainClass); } if (basePlugin != null) { manifest.getMainAttributes().putValue(PluginManifest.BASE_PLUGIN, basePlugin); } manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0"); File jarFile = File.createTempFile(key, ".jar", dir); try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(jarFile), manifest)) { // nothing else to add } return jarFile; } }
14,875
43.672673
167
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/PluginUninstallerTest.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; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.Arrays; import java.util.Collections; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.Plugin; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.platform.PluginInfo; import org.sonar.core.plugin.PluginType; import org.sonar.server.platform.ServerFileSystem; import org.sonar.updatecenter.common.Version; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.plugin.PluginType.BUNDLED; import static org.sonar.core.plugin.PluginType.EXTERNAL; public class PluginUninstallerTest { @Rule public TemporaryFolder testFolder = new TemporaryFolder(); @Rule public LogTester logs = new LogTester(); private File uninstallDir; private ServerFileSystem fs = mock(ServerFileSystem.class); private ServerPluginRepository serverPluginRepository = new ServerPluginRepository(); private PluginUninstaller underTest = new PluginUninstaller(fs, serverPluginRepository); @Before public void setUp() throws IOException { uninstallDir = testFolder.newFolder("uninstall"); when(fs.getUninstalledPluginsDir()).thenReturn(uninstallDir); when(fs.getInstalledExternalPluginsDir()).thenReturn(testFolder.newFolder("external")); } @Test public void create_uninstall_dir() { File dir = new File(testFolder.getRoot(), "dir"); when(fs.getUninstalledPluginsDir()).thenReturn(dir); assertThat(dir).doesNotExist(); underTest.start(); assertThat(dir).isDirectory(); } @Test public void fail_uninstall_if_plugin_doesnt_exist() { underTest.start(); assertThatThrownBy(() -> underTest.uninstall("plugin")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Plugin [plugin] is not installed"); } @Test public void fail_uninstall_if_plugin_is_bundled() { underTest.start(); serverPluginRepository.addPlugin(newPlugin("plugin", BUNDLED, "plugin.jar")); assertThatThrownBy(() -> underTest.uninstall("plugin")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Plugin [plugin] is not installed"); } @Test public void uninstall() throws Exception { File installedJar = copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); serverPluginRepository.addPlugin(newPlugin("testbase", EXTERNAL, installedJar.getName())); underTest.start(); assertThat(installedJar).exists(); underTest.uninstall("testbase"); assertThat(installedJar).doesNotExist(); assertThat(uninstallDir.list()).containsOnly(installedJar.getName()); } @Test public void uninstall_ignores_non_existing_files() { underTest.start(); serverPluginRepository.addPlugin(newPlugin("test", EXTERNAL, "nonexisting.jar")); underTest.uninstall("test"); assertThat(uninstallDir).isEmptyDirectory(); assertThat(logs.logs()).contains("Plugin already uninstalled: test [test]"); } @Test public void uninstall_dependents() throws IOException { File baseJar = copyTestPluginTo("test-base-plugin", fs.getInstalledExternalPluginsDir()); File requirejar = copyTestPluginTo("test-require-plugin", fs.getInstalledExternalPluginsDir()); ServerPlugin base = newPlugin("test-base-plugin", EXTERNAL, baseJar.getName()); ServerPlugin extension = newPlugin("test-require-plugin", EXTERNAL, requirejar.getName(), new PluginInfo.RequiredPlugin("test-base-plugin", Version.create("1.0"))); serverPluginRepository.addPlugins(Arrays.asList(base, extension)); underTest.start(); underTest.uninstall("test-base-plugin"); assertThat(Files.list(uninstallDir.toPath())).extracting(p -> p.getFileName().toString()).containsOnly(baseJar.getName(), requirejar.getName()); assertThat(fs.getInstalledExternalPluginsDir()).isEmptyDirectory(); } @Test public void cancel() throws IOException { File file = copyTestPluginTo("test-base-plugin", uninstallDir); assertThat(Files.list(uninstallDir.toPath())).extracting(p -> p.getFileName().toString()).containsOnly(file.getName()); underTest.cancelUninstalls(); } @Test public void list_uninstalled_plugins() throws IOException { new File(uninstallDir, "file1").createNewFile(); copyTestPluginTo("test-base-plugin", uninstallDir); assertThat(underTest.getUninstalledPlugins()).extracting("key").containsOnly("testbase"); } private static ServerPlugin newPlugin(String key, PluginType type, String jarFile, PluginInfo.RequiredPlugin requiredPlugin) { ServerPluginInfo pluginInfo = newPluginInfo(key, type, jarFile); when(pluginInfo.getRequiredPlugins()).thenReturn(Collections.singleton(requiredPlugin)); return newPlugin(pluginInfo); } private static ServerPlugin newPlugin(String key, PluginType type, String jarFile) { return newPlugin(newPluginInfo(key, type, jarFile)); } private static ServerPluginInfo newPluginInfo(String key, PluginType type, String jarFile) { ServerPluginInfo pluginInfo = mock(ServerPluginInfo.class); when(pluginInfo.getKey()).thenReturn(key); when(pluginInfo.getName()).thenReturn(key); when(pluginInfo.getType()).thenReturn(type); when(pluginInfo.getNonNullJarFile()).thenReturn(new File(jarFile)); return pluginInfo; } private static ServerPlugin newPlugin(ServerPluginInfo pluginInfo) { return new ServerPlugin(pluginInfo, pluginInfo.getType(), mock(Plugin.class), mock(PluginFilesAndMd5.FileAndMd5.class), mock(ClassLoader.class)); } private File copyTestPluginTo(String testPluginName, File toDir) throws IOException { File jar = TestProjectUtils.jarOf(testPluginName); // file is copied because it's supposed to be moved by the test FileUtils.copyFileToDirectory(jar, toDir); return new File(toDir, jar.getName()); } }
6,970
38.834286
168
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/ServerPluginInfoTest.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; import org.junit.Test; import org.sonar.core.plugin.PluginType; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.core.plugin.PluginType.BUNDLED; import static org.sonar.core.plugin.PluginType.EXTERNAL; public class ServerPluginInfoTest { @Test public void equals_returns_false_with_different_types() { ServerPluginInfo info1 = new ServerPluginInfo("key1").setType(EXTERNAL); ServerPluginInfo info2 = new ServerPluginInfo("key1").setType(PluginType.BUNDLED); ServerPluginInfo info3 = new ServerPluginInfo("key1").setType(EXTERNAL); assertThat(info1).isNotEqualTo(info2) .isEqualTo(info3) .hasSameHashCodeAs(info3.hashCode()); assertThat(info1.hashCode()).isNotEqualTo(info2.hashCode()); } @Test public void set_and_get_type() { ServerPluginInfo info = new ServerPluginInfo("key1").setType(EXTERNAL); assertThat(info.getType()).isEqualTo(EXTERNAL); info.setType(BUNDLED); assertThat(info.getType()).isEqualTo(BUNDLED); } }
1,897
36.215686
86
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/ServerPluginJarExploderTest.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; import java.io.File; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.core.platform.ExplodedPlugin; import org.sonar.core.platform.PluginInfo; import org.sonar.server.platform.ServerFileSystem; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ServerPluginJarExploderTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private ServerFileSystem fs = mock(ServerFileSystem.class); private ServerPluginJarExploder underTest = new ServerPluginJarExploder(fs); @Test public void copy_all_classloader_files_to_dedicated_directory() throws Exception { File deployDir = temp.newFolder(); when(fs.getDeployedPluginsDir()).thenReturn(deployDir); File sourceJar = TestProjectUtils.jarOf("test-libs-plugin"); PluginInfo info = PluginInfo.create(sourceJar); ExplodedPlugin exploded = underTest.explode(info); // all the files loaded by classloaders (JAR + META-INF/libs/*.jar) are copied to the dedicated directory // web/deploy/{pluginKey} File pluginDeployDir = new File(deployDir, "testlibs"); assertThat(exploded.getKey()).isEqualTo("testlibs"); assertThat(exploded.getMain()).isFile().exists().hasParent(pluginDeployDir); assertThat(exploded.getLibs()).extracting("name").containsOnly("commons-daemon-1.0.15.jar", "commons-email-20030310.165926.jar"); for (File lib : exploded.getLibs()) { assertThat(lib).exists().isFile(); assertThat(lib.getCanonicalPath()).startsWith(pluginDeployDir.getCanonicalPath()); } File targetJar = new File(fs.getDeployedPluginsDir(), "testlibs/test-libs-plugin-0.1-SNAPSHOT.jar"); } }
2,644
39.692308
133
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/ServerPluginManagerTest.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; import com.google.common.collect.ImmutableMap; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Map; import org.junit.After; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.Plugin; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.platform.ExplodedPlugin; import org.sonar.core.platform.PluginClassLoader; import org.sonar.core.platform.PluginJarExploder; import org.sonar.server.plugins.PluginFilesAndMd5.FileAndMd5; import org.sonar.updatecenter.common.Version; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.plugin.PluginType.EXTERNAL; public class ServerPluginManagerTest { @Rule public LogTester logTester = new LogTester(); @Rule public TemporaryFolder temp = new TemporaryFolder(); private PluginClassLoader pluginClassLoader = mock(PluginClassLoader.class); private PluginJarExploder jarExploder = mock(PluginJarExploder.class); private PluginJarLoader jarLoader = mock(PluginJarLoader.class); private ServerPluginRepository pluginRepository = new ServerPluginRepository(); private ServerPluginManager underTest = new ServerPluginManager(pluginClassLoader, jarExploder, jarLoader, pluginRepository); @After public void tearDown() { underTest.stop(); } @Test public void load_plugins() throws IOException { ServerPluginInfo p1 = newPluginInfo("p1"); ServerPluginInfo p2 = newPluginInfo("p2"); when(jarLoader.loadPlugins()).thenReturn(Arrays.asList(p1, p2)); when(jarExploder.explode(p1)).thenReturn(new ExplodedPlugin(p1, "p1", new File("p1Exploded.jar"), Collections.singletonList(new File("libP1.jar")))); when(jarExploder.explode(p2)).thenReturn(new ExplodedPlugin(p2, "p2", new File("p2Exploded.jar"), Collections.singletonList(new File("libP2.jar")))); Map<String, Plugin> instances = ImmutableMap.of("p1", mock(Plugin.class), "p2", mock(Plugin.class)); when(pluginClassLoader.load(anyList())).thenReturn(instances); underTest.start(); assertEquals(2, pluginRepository.getPlugins().size()); assertEquals(p1, pluginRepository.getPlugin("p1").getPluginInfo()); assertEquals(newFileAndMd5(p1.getNonNullJarFile()).getFile(), pluginRepository.getPlugin("p1").getJar().getFile()); assertEquals(newFileAndMd5(p1.getNonNullJarFile()).getMd5(), pluginRepository.getPlugin("p1").getJar().getMd5()); assertEquals(instances.get("p1"), pluginRepository.getPlugin("p1").getInstance()); assertEquals(p2, pluginRepository.getPlugin("p2").getPluginInfo()); assertEquals(newFileAndMd5(p2.getNonNullJarFile()).getFile(), pluginRepository.getPlugin("p2").getJar().getFile()); assertEquals(newFileAndMd5(p2.getNonNullJarFile()).getMd5(), pluginRepository.getPlugin("p2").getJar().getMd5()); assertEquals(instances.get("p2"), pluginRepository.getPlugin("p2").getInstance()); assertThat(pluginRepository.getPlugins()).extracting(ServerPlugin::getPluginInfo) .allMatch(p -> logTester.logs().contains(String.format("Deploy %s / %s / %s", p.getName(), p.getVersion(), p.getImplementationBuild()))); } private ServerPluginInfo newPluginInfo(String key) throws IOException { ServerPluginInfo pluginInfo = mock(ServerPluginInfo.class); when(pluginInfo.getKey()).thenReturn(key); when(pluginInfo.getType()).thenReturn(EXTERNAL); when(pluginInfo.getNonNullJarFile()).thenReturn(temp.newFile(key + ".jar")); when(pluginInfo.getName()).thenReturn(key + "_name"); Version version = mock(Version.class); when(version.getName()).thenReturn(key + "_version"); when(pluginInfo.getVersion()).thenReturn(version); when(pluginInfo.getImplementationBuild()).thenReturn(key + "_implementationBuild"); return pluginInfo; } private static FileAndMd5 newFileAndMd5(File file) { return new PluginFilesAndMd5.FileAndMd5(file); } }
5,020
44.234234
153
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/ServerPluginRepositoryTest.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; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.junit.Assert; import org.junit.Test; import org.sonar.api.Plugin; import org.sonar.core.platform.PluginInfo; import org.sonar.core.plugin.PluginType; import org.sonar.server.plugins.PluginFilesAndMd5.FileAndMd5; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.core.plugin.PluginType.BUNDLED; import static org.sonar.core.plugin.PluginType.EXTERNAL; public class ServerPluginRepositoryTest { private ServerPluginRepository repository = new ServerPluginRepository(); @Test public void get_plugin_data() { ServerPlugin plugin1 = newPlugin("plugin1", EXTERNAL); ServerPlugin plugin2 = newPlugin("plugin2", EXTERNAL); repository.addPlugins(Collections.singletonList(plugin1)); repository.addPlugin(plugin2); assertThat(repository.getPluginInfos()).containsOnly(plugin1.getPluginInfo(), plugin2.getPluginInfo()); assertThat(repository.getPluginInstance("plugin1")).isEqualTo(plugin1.getInstance()); assertThat(repository.getPluginInstances()).containsOnly(plugin1.getInstance(), plugin2.getInstance()); assertThat(repository.getPlugins()).containsOnly(plugin1, plugin2); assertThat(repository.getPlugin("plugin2")).isEqualTo(plugin2); assertThat(repository.findPlugin("plugin2")).contains(plugin2); assertThat(repository.hasPlugin("plugin2")).isTrue(); assertThat(repository.findPlugin("nonexisting")).isEmpty(); assertThat(repository.hasPlugin("nonexisting")).isFalse(); } @Test public void fail_getPluginInstance_if_plugin_doesnt_exist() { ServerPlugin plugin1 = newPlugin("plugin1", EXTERNAL); ServerPlugin plugin2 = newPlugin("plugin2", EXTERNAL); repository.addPlugins(Arrays.asList(plugin1, plugin2)); Assert.assertThrows("asd", IllegalArgumentException.class, () -> repository.getPluginInstance("plugin3")); } @Test public void fail_getPluginInfo_if_plugin_doesnt_exist() { ServerPlugin plugin1 = newPlugin("plugin1", EXTERNAL); ServerPlugin plugin2 = newPlugin("plugin2", EXTERNAL); repository.addPlugins(Arrays.asList(plugin1, plugin2)); Assert.assertThrows("asd", IllegalArgumentException.class, () -> repository.getPluginInfo("plugin3")); } @Test public void getPluginsInfoByTypeExternal_given1ExternalPlugin_return1ExternalPlugin(){ //given ServerPlugin externalPlugin = newPlugin("plugin1", EXTERNAL); repository.addPlugin(externalPlugin); PluginInfo expectedPluginInfo = externalPlugin.getPluginInfo(); //when Collection<PluginInfo> pluginInfos = repository.getPluginsInfoByType(EXTERNAL); //then assertThat(pluginInfos).containsOnly(expectedPluginInfo); } @Test public void getPluginsInfoByTypeExternal_given1ExternalAnd1BundledPlugin_return1ExternalPlugin(){ //given ServerPlugin externalPlugin = newPlugin("plugin1", EXTERNAL); ServerPlugin bundledPlugin = newPlugin("plugin2", BUNDLED); repository.addPlugin(externalPlugin); repository.addPlugin(bundledPlugin); PluginInfo expectedPluginInfo = externalPlugin.getPluginInfo(); //when Collection<PluginInfo> pluginInfos = repository.getPluginsInfoByType(EXTERNAL); //then assertThat(pluginInfos).containsOnly(expectedPluginInfo); } @Test public void getPluginsInfoByTypeBundled_given2BundledPlugins_return2BundledPlugins(){ //given ServerPlugin bundledPlugin = newPlugin("plugin1", BUNDLED); ServerPlugin bundledPlugin2 = newPlugin("plugin2", BUNDLED); repository.addPlugin(bundledPlugin); repository.addPlugin(bundledPlugin2); PluginInfo expectedPluginInfo = bundledPlugin.getPluginInfo(); PluginInfo expectedPluginInfo2 = bundledPlugin2.getPluginInfo(); //when Collection<PluginInfo> pluginInfos = repository.getPluginsInfoByType(BUNDLED); //then assertThat(pluginInfos).containsOnly(expectedPluginInfo, expectedPluginInfo2); } private PluginInfo newPluginInfo(String key) { PluginInfo pluginInfo = mock(PluginInfo.class); when(pluginInfo.getKey()).thenReturn(key); return pluginInfo; } private ServerPlugin newPlugin(String key, PluginType type) { return new ServerPlugin(newPluginInfo(key), type, mock(Plugin.class), mock(FileAndMd5.class), mock(ClassLoader.class)); } }
5,308
37.194245
123
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/TestPluginA.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; import org.sonar.api.Plugin; public class TestPluginA implements Plugin { @Override public void define(Context context) { } }
1,012
32.766667
75
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/TestProjectUtils.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; import java.io.File; import java.util.Collection; import org.apache.commons.io.FileUtils; public class TestProjectUtils { /** * Get the artifact of plugins stored in src/test/projects */ public static File jarOf(String dirName) { File target = FileUtils.toFile(TestProjectUtils.class.getResource(String.format("/%s/target/", dirName))); Collection<File> jars = FileUtils.listFiles(target, new String[] {"jar"}, false); if (jars == null || jars.size() != 1) { throw new IllegalArgumentException("Test project is badly defined: " + dirName); } return jars.iterator().next(); } }
1,495
36.4
110
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/UpdateCenterClientTest.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; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import org.junit.Before; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.SonarException; import org.sonar.api.utils.UriReader; import org.sonar.process.ProcessProperties; import org.sonar.updatecenter.common.UpdateCenter; import org.sonar.updatecenter.common.Version; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class UpdateCenterClientTest { private static final String BASE_URL = "https://update.sonarsource.org"; private static final String DEFAULT_CACHE_TTL = "3600000"; private UriReader reader = mock(UriReader.class); private MapSettings settings = new MapSettings(); private UpdateCenterClient underTest; @Before public void startServer() throws Exception { reader = mock(UriReader.class); settings.setProperty(UpdateCenterClient.URL_PROPERTY, BASE_URL); settings.setProperty(ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE.getKey(), true); settings.setProperty(UpdateCenterClient.CACHE_TTL_PROPERTY, DEFAULT_CACHE_TTL); underTest = new UpdateCenterClient(reader, settings.asConfig()); } @Test public void downloadUpdateCenter() throws URISyntaxException { when(reader.readString(new URI(BASE_URL), StandardCharsets.UTF_8)).thenReturn("publicVersions=2.2,2.3"); UpdateCenter plugins = underTest.getUpdateCenter().get(); verify(reader, times(1)).readString(new URI(BASE_URL), StandardCharsets.UTF_8); assertThat(plugins.getSonar().getVersions()).containsOnly(Version.create("2.2"), Version.create("2.3")); assertThat(underTest.getLastRefreshDate()).isNotNull(); } @Test public void not_available_before_initialization() { assertThat(underTest.getLastRefreshDate()).isNull(); } @Test public void ignore_connection_errors() { when(reader.readString(any(URI.class), eq(StandardCharsets.UTF_8))).thenThrow(new SonarException()); assertThat(underTest.getUpdateCenter()).isEmpty(); } @Test public void cache_data() throws Exception { when(reader.readString(new URI(BASE_URL), StandardCharsets.UTF_8)).thenReturn("sonar.versions=2.2,2.3"); underTest.getUpdateCenter(); underTest.getUpdateCenter(); verify(reader, times(1)).readString(new URI(BASE_URL), StandardCharsets.UTF_8); } @Test public void forceRefresh() throws Exception { when(reader.readString(new URI(BASE_URL), StandardCharsets.UTF_8)).thenReturn("sonar.versions=2.2,2.3"); underTest.getUpdateCenter(); underTest.getUpdateCenter(true); verify(reader, times(2)).readString(new URI(BASE_URL), StandardCharsets.UTF_8); } @Test public void update_center_is_null_when_property_is_false() { settings.setProperty(ProcessProperties.Property.SONAR_UPDATECENTER_ACTIVATE.getKey(), false); assertThat(underTest.getUpdateCenter()).isEmpty(); } }
4,071
37.415094
108
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/UpdateCenterMatrixFactoryTest.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; import java.util.Optional; import org.junit.Test; import org.sonar.core.platform.SonarQubeVersion; import org.sonar.updatecenter.common.UpdateCenter; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class UpdateCenterMatrixFactoryTest { private UpdateCenterMatrixFactory underTest; @Test public void return_absent_update_center() { UpdateCenterClient updateCenterClient = mock(UpdateCenterClient.class); when(updateCenterClient.getUpdateCenter(anyBoolean())).thenReturn(Optional.empty()); underTest = new UpdateCenterMatrixFactory(updateCenterClient, mock(SonarQubeVersion.class), mock(InstalledPluginReferentialFactory.class)); Optional<UpdateCenter> updateCenter = underTest.getUpdateCenter(false); assertThat(updateCenter).isEmpty(); } }
1,805
36.625
143
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/UpdateCenterServlet.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; import java.io.IOException; import java.util.Properties; import javax.servlet.GenericServlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class UpdateCenterServlet extends GenericServlet { int count = 0; @Override public void service(ServletRequest request, ServletResponse response) throws IOException { count++; Properties props = new Properties(); props.setProperty("count", String.valueOf(count)); props.setProperty("agent", ((HttpServletRequest)request).getHeader("User-Agent")); props.store(response.getOutputStream(), null); } }
1,530
34.604651
92
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/plugins/edition/EditionBundledPluginsTest.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.edition; import java.util.Random; import org.junit.Test; import org.sonar.core.platform.PluginInfo; import org.sonar.updatecenter.common.Plugin; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EditionBundledPluginsTest { private final Random random = new Random(); @Test public void isEditionBundled_on_Plugin_fails_with_NPE_if_arg_is_null() { assertThatThrownBy(() -> EditionBundledPlugins.isEditionBundled((Plugin) null)) .isInstanceOf(NullPointerException.class); } @Test public void isEditionBundled_on_Plugin_returns_false_for_SonarSource_and_non_commercial_license() { Plugin plugin = newPlugin(randomizeCase("SonarSource"), randomAlphanumeric(3)); assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse(); } @Test public void isEditionBundled_on_Plugin_returns_false_for_license_SonarSource_and_non_SonarSource_organization() { Plugin plugin = newPlugin(randomAlphanumeric(3), randomizeCase("SonarSource")); assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse(); } @Test public void isEditionBundled_on_Plugin_returns_false_for_license_Commercial_and_non_SonarSource_organization() { Plugin plugin = newPlugin(randomAlphanumeric(3), randomizeCase("Commercial")); assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isFalse(); } @Test public void isEditionBundled_on_Plugin_returns_true_for_organization_SonarSource_and_license_SonarSource_case_insensitive() { Plugin plugin = newPlugin(randomizeCase("SonarSource"), randomizeCase("SonarSource")); assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isTrue(); } @Test public void isEditionBundled_on_Plugin_returns_true_for_organization_SonarSource_and_license_Commercial_case_insensitive() { Plugin plugin = newPlugin(randomizeCase("SonarSource"), randomizeCase("Commercial")); assertThat(EditionBundledPlugins.isEditionBundled(plugin)).isTrue(); } @Test public void isEditionBundled_on_PluginInfo_fails_with_NPE_if_arg_is_null() { assertThatThrownBy(() -> EditionBundledPlugins.isEditionBundled((PluginInfo) null)) .isInstanceOf(NullPointerException.class); } @Test public void isEditionBundled_on_PluginInfo_returns_false_for_SonarSource_and_non_commercial_license() { PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), randomAlphanumeric(3)); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse(); } @Test public void isEditionBundled_on_PluginInfo_returns_false_for_license_SonarSource_and_non_SonarSource_organization() { PluginInfo pluginInfo = newPluginInfo(randomAlphanumeric(3), randomizeCase("SonarSource")); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse(); } @Test public void isEditionBundled_on_PluginInfo_returns_false_for_license_Commercial_and_non_SonarSource_organization() { PluginInfo pluginInfo = newPluginInfo(randomAlphanumeric(3), randomizeCase("Commercial")); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isFalse(); } @Test public void isEditionBundled_on_PluginInfo_returns_true_for_organization_SonarSource_and_license_SonarSource_case_insensitive() { PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), randomizeCase("SonarSource")); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isTrue(); } @Test public void isEditionBundled_on_PluginINfo_returns_true_for_organization_SonarSource_and_license_Commercial_case_insensitive() { PluginInfo pluginInfo = newPluginInfo(randomizeCase("SonarSource"), randomizeCase("Commercial")); assertThat(EditionBundledPlugins.isEditionBundled(pluginInfo)).isTrue(); } private String randomizeCase(String s) { return s.chars() .map(c -> random.nextBoolean() ? Character.toUpperCase(c) : Character.toLowerCase(c)) .collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append) .toString(); } private PluginInfo newPluginInfo(String organization, String license) { PluginInfo pluginInfo = new PluginInfo(randomAlphanumeric(2)); if (random.nextBoolean()) { pluginInfo.setName(randomAlphanumeric(3)); } if (random.nextBoolean()) { pluginInfo.setOrganizationUrl(randomAlphanumeric(4)); } if (random.nextBoolean()) { pluginInfo.setIssueTrackerUrl(randomAlphanumeric(5)); } if (random.nextBoolean()) { pluginInfo.setIssueTrackerUrl(randomAlphanumeric(6)); } if (random.nextBoolean()) { pluginInfo.setBasePlugin(randomAlphanumeric(7)); } if (random.nextBoolean()) { pluginInfo.setHomepageUrl(randomAlphanumeric(8)); } return pluginInfo .setOrganizationName(organization) .setLicense(license); } private Plugin newPlugin(String organization, String license) { Plugin plugin = Plugin.factory(randomAlphanumeric(2)); if (random.nextBoolean()) { plugin.setName(randomAlphanumeric(3)); } if (random.nextBoolean()) { plugin.setOrganizationUrl(randomAlphanumeric(4)); } if (random.nextBoolean()) { plugin.setTermsConditionsUrl(randomAlphanumeric(5)); } if (random.nextBoolean()) { plugin.setIssueTrackerUrl(randomAlphanumeric(6)); } if (random.nextBoolean()) { plugin.setCategory(randomAlphanumeric(7)); } if (random.nextBoolean()) { plugin.setHomepageUrl(randomAlphanumeric(8)); } return plugin .setLicense(license) .setOrganization(organization); } }
6,613
37.011494
131
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/project/ProjectDefaultVisibilityTest.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; import org.junit.Rule; import org.junit.Test; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ProjectDefaultVisibilityTest { @Rule public final DbTester db = DbTester.create(); private final ProjectDefaultVisibility underTest = new ProjectDefaultVisibility(db.getDbClient()); @Test public void fail_if_project_visibility_property_not_exist() { DbSession dbSession = db.getSession(); assertThatThrownBy(() -> underTest.get(dbSession)) .isInstanceOf(IllegalStateException.class) .hasMessage("Could not find default project visibility setting"); } @Test public void set_default_project_visibility() { underTest.set(db.getSession(), Visibility.PUBLIC); assertThat(underTest.get(db.getSession())).isEqualTo(Visibility.PUBLIC); underTest.set(db.getSession(), Visibility.PRIVATE); assertThat(underTest.get(db.getSession())).isEqualTo(Visibility.PRIVATE); } @Test public void set_default_project_visibility_by_string() { underTest.set(db.getSession(), "private"); assertThat(underTest.get(db.getSession())).isEqualTo(Visibility.PRIVATE); underTest.set(db.getSession(), "public"); assertThat(underTest.get(db.getSession())).isEqualTo(Visibility.PUBLIC); } }
2,263
34.375
100
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/project/ProjectLifeCycleListenersImplTest.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; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Collections; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mockito; import static java.util.Collections.singleton; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; @RunWith(DataProviderRunner.class) public class ProjectLifeCycleListenersImplTest { private final ProjectLifeCycleListener listener1 = mock(ProjectLifeCycleListener.class); private final ProjectLifeCycleListener listener2 = mock(ProjectLifeCycleListener.class); private final ProjectLifeCycleListener listener3 = mock(ProjectLifeCycleListener.class); private final ProjectLifeCycleListenersImpl underTestNoListeners = new ProjectLifeCycleListenersImpl(); private final ProjectLifeCycleListenersImpl underTestWithListeners = new ProjectLifeCycleListenersImpl( new ProjectLifeCycleListener[] {listener1, listener2, listener3}); @Test public void onProjectsDeleted_throws_NPE_if_set_is_null() { assertThatThrownBy(() -> underTestWithListeners.onProjectsDeleted(null)) .isInstanceOf(NullPointerException.class) .hasMessage("projects can't be null"); } @Test public void onProjectsDeleted_throws_NPE_if_set_is_null_even_if_no_listeners() { assertThatThrownBy(() -> underTestNoListeners.onProjectsDeleted(null)) .isInstanceOf(NullPointerException.class) .hasMessage("projects can't be null"); } @Test public void onProjectsDeleted_has_no_effect_if_set_is_empty() { underTestNoListeners.onProjectsDeleted(Collections.emptySet()); underTestWithListeners.onProjectsDeleted(Collections.emptySet()); verifyNoInteractions(listener1, listener2, listener3); } @Test @UseDataProvider("oneOrManyDeletedProjects") public void onProjectsDeleted_does_not_fail_if_there_is_no_listener(Set<DeletedProject> projects) { assertThatCode(() -> underTestNoListeners.onProjectsDeleted(projects)).doesNotThrowAnyException(); } @Test @UseDataProvider("oneOrManyDeletedProjects") public void onProjectsDeleted_calls_all_listeners_in_order_of_addition_to_constructor(Set<DeletedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); underTestWithListeners.onProjectsDeleted(projects); inOrder.verify(listener1).onProjectsDeleted(same(projects)); inOrder.verify(listener2).onProjectsDeleted(same(projects)); inOrder.verify(listener3).onProjectsDeleted(same(projects)); inOrder.verifyNoMoreInteractions(); } @Test @UseDataProvider("oneOrManyDeletedProjects") public void onProjectsDeleted_calls_all_listeners_even_if_one_throws_an_Exception(Set<DeletedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new RuntimeException("Faking listener2 throwing an exception")) .when(listener2) .onProjectsDeleted(any()); underTestWithListeners.onProjectsDeleted(projects); inOrder.verify(listener1).onProjectsDeleted(same(projects)); inOrder.verify(listener2).onProjectsDeleted(same(projects)); inOrder.verify(listener3).onProjectsDeleted(same(projects)); inOrder.verifyNoMoreInteractions(); } @Test @UseDataProvider("oneOrManyDeletedProjects") public void onProjectsDeleted_calls_all_listeners_even_if_one_throws_an_Error(Set<DeletedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new Error("Faking listener2 throwing an Error")) .when(listener2) .onProjectsDeleted(any()); underTestWithListeners.onProjectsDeleted(projects); inOrder.verify(listener1).onProjectsDeleted(same(projects)); inOrder.verify(listener2).onProjectsDeleted(same(projects)); inOrder.verify(listener3).onProjectsDeleted(same(projects)); inOrder.verifyNoMoreInteractions(); } @Test public void onProjectBranchesDeleted_throws_NPE_if_set_is_null() { assertThatThrownBy(() -> underTestWithListeners.onProjectBranchesDeleted(null)) .isInstanceOf(NullPointerException.class) .hasMessage("projects can't be null"); } @Test public void onProjectBranchesDeleted_throws_NPE_if_set_is_null_even_if_no_listeners() { assertThatThrownBy(() -> underTestNoListeners.onProjectBranchesDeleted(null)) .isInstanceOf(NullPointerException.class) .hasMessage("projects can't be null"); } @Test public void onProjectBranchesDeleted_has_no_effect_if_set_is_empty() { underTestNoListeners.onProjectBranchesDeleted(Collections.emptySet()); underTestWithListeners.onProjectBranchesDeleted(Collections.emptySet()); verifyNoInteractions(listener1, listener2, listener3); } @Test @UseDataProvider("oneOrManyProjects") public void onProjectBranchesDeleted_does_not_fail_if_there_is_no_listener(Set<Project> projects) { underTestNoListeners.onProjectBranchesDeleted(projects); } @Test @UseDataProvider("oneOrManyProjects") public void onProjectBranchesDeleted_calls_all_listeners_in_order_of_addition_to_constructor(Set<Project> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); underTestWithListeners.onProjectBranchesDeleted(projects); inOrder.verify(listener1).onProjectBranchesDeleted(same(projects)); inOrder.verify(listener2).onProjectBranchesDeleted(same(projects)); inOrder.verify(listener3).onProjectBranchesDeleted(same(projects)); inOrder.verifyNoMoreInteractions(); } @Test @UseDataProvider("oneOrManyProjects") public void onProjectBranchesDeleted_calls_all_listeners_even_if_one_throws_an_Exception(Set<Project> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new RuntimeException("Faking listener2 throwing an exception")) .when(listener2) .onProjectBranchesDeleted(any()); underTestWithListeners.onProjectBranchesDeleted(projects); inOrder.verify(listener1).onProjectBranchesDeleted(same(projects)); inOrder.verify(listener2).onProjectBranchesDeleted(same(projects)); inOrder.verify(listener3).onProjectBranchesDeleted(same(projects)); inOrder.verifyNoMoreInteractions(); } @Test @UseDataProvider("oneOrManyProjects") public void onProjectBranchesDeleted_calls_all_listeners_even_if_one_throws_an_Error(Set<Project> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new Error("Faking listener2 throwing an Error")) .when(listener2) .onProjectBranchesDeleted(any()); underTestWithListeners.onProjectBranchesDeleted(projects); inOrder.verify(listener1).onProjectBranchesDeleted(same(projects)); inOrder.verify(listener2).onProjectBranchesDeleted(same(projects)); inOrder.verify(listener3).onProjectBranchesDeleted(same(projects)); inOrder.verifyNoMoreInteractions(); } @DataProvider public static Object[][] oneOrManyProjects() { return new Object[][] { {singleton(newUniqueProject())}, {IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> newUniqueProject()).collect(Collectors.toSet())} }; } @DataProvider public static Object[][] oneOrManyDeletedProjects() { return new Object[][] { {singleton(newUniqueProject())}, {IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> new DeletedProject(newUniqueProject(), "branch_" + i)) .collect(Collectors.toSet())} }; } @Test public void onProjectsRekeyed_throws_NPE_if_set_is_null() { assertThatThrownBy(() -> underTestWithListeners.onProjectsRekeyed(null)) .isInstanceOf(NullPointerException.class) .hasMessage("rekeyedProjects can't be null"); } @Test public void onProjectsRekeyed_throws_NPE_if_set_is_null_even_if_no_listeners() { assertThatThrownBy(() -> underTestNoListeners.onProjectsRekeyed(null)) .isInstanceOf(NullPointerException.class) .hasMessage("rekeyedProjects can't be null"); } @Test public void onProjectsRekeyed_has_no_effect_if_set_is_empty() { underTestNoListeners.onProjectsRekeyed(Collections.emptySet()); underTestWithListeners.onProjectsRekeyed(Collections.emptySet()); verifyNoInteractions(listener1, listener2, listener3); } @Test @UseDataProvider("oneOrManyRekeyedProjects") public void onProjectsRekeyed_does_not_fail_if_there_is_no_listener(Set<RekeyedProject> projects) { underTestNoListeners.onProjectsRekeyed(projects); } @Test @UseDataProvider("oneOrManyRekeyedProjects") public void onProjectsRekeyed_calls_all_listeners_in_order_of_addition_to_constructor(Set<RekeyedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); underTestWithListeners.onProjectsRekeyed(projects); inOrder.verify(listener1).onProjectsRekeyed(same(projects)); inOrder.verify(listener2).onProjectsRekeyed(same(projects)); inOrder.verify(listener3).onProjectsRekeyed(same(projects)); inOrder.verifyNoMoreInteractions(); } @Test @UseDataProvider("oneOrManyRekeyedProjects") public void onProjectsRekeyed_calls_all_listeners_even_if_one_throws_an_Exception(Set<RekeyedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new RuntimeException("Faking listener2 throwing an exception")) .when(listener2) .onProjectsRekeyed(any()); underTestWithListeners.onProjectsRekeyed(projects); inOrder.verify(listener1).onProjectsRekeyed(same(projects)); inOrder.verify(listener2).onProjectsRekeyed(same(projects)); inOrder.verify(listener3).onProjectsRekeyed(same(projects)); inOrder.verifyNoMoreInteractions(); } @Test @UseDataProvider("oneOrManyRekeyedProjects") public void onProjectsRekeyed_calls_all_listeners_even_if_one_throws_an_Error(Set<RekeyedProject> projects) { InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); doThrow(new Error("Faking listener2 throwing an Error")) .when(listener2) .onProjectsRekeyed(any()); underTestWithListeners.onProjectsRekeyed(projects); inOrder.verify(listener1).onProjectsRekeyed(same(projects)); inOrder.verify(listener2).onProjectsRekeyed(same(projects)); inOrder.verify(listener3).onProjectsRekeyed(same(projects)); inOrder.verifyNoMoreInteractions(); } @DataProvider public static Object[][] oneOrManyRekeyedProjects() { return new Object[][] { {singleton(newUniqueRekeyedProject())}, {IntStream.range(0, 1 + new Random().nextInt(10)).mapToObj(i -> newUniqueRekeyedProject()).collect(Collectors.toSet())} }; } private static Project newUniqueProject() { return Project.from(newPrivateProjectDto()); } private static int counter = 3_989; private static RekeyedProject newUniqueRekeyedProject() { int base = counter++; Project project = Project.from(newPrivateProjectDto()); return new RekeyedProject(project, base + "_old_key"); } }
12,472
38.977564
125
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/project/RekeyedProjectTest.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; import org.junit.Test; import static java.util.Collections.emptyList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; public class RekeyedProjectTest { @Test public void constructor_throws_NPE_if_project_is_null() { assertThatThrownBy(() -> new RekeyedProject(null, randomAlphanumeric(3))) .isInstanceOf(NullPointerException.class) .hasMessage("project can't be null"); } @Test public void constructor_throws_NPE_if_previousKey_is_null() { assertThatThrownBy(() -> new RekeyedProject(newRandomProject(), null)) .isInstanceOf(NullPointerException.class) .hasMessage("previousKey can't be null"); } @Test public void verify_getters() { Project project = newRandomProject(); String previousKey = randomAlphanumeric(6); RekeyedProject underTest = new RekeyedProject(project, previousKey); assertThat(underTest.project()).isSameAs(project); assertThat(underTest.previousKey()).isEqualTo(previousKey); } @Test public void equals_is_based_on_project_and_previousKey() { Project project = newRandomProject(); String previousKey = randomAlphanumeric(6); RekeyedProject underTest = new RekeyedProject(project, previousKey); assertThat(underTest) .isEqualTo(underTest) .isEqualTo(new RekeyedProject(project, previousKey)) .isNotEqualTo(new RekeyedProject(project, randomAlphanumeric(11))) .isNotEqualTo(new RekeyedProject(newRandomProject(), previousKey)) .isNotEqualTo(new Object()) .isNotNull(); } @Test public void hashCode_is_based_on_project_and_previousKey() { Project project = newRandomProject(); String previousKey = randomAlphanumeric(6); RekeyedProject underTest = new RekeyedProject(project, previousKey); assertThat(underTest) .hasSameHashCodeAs(underTest) .hasSameHashCodeAs(new RekeyedProject(project, previousKey)); assertThat(underTest.hashCode()) .isNotEqualTo(new RekeyedProject(project, randomAlphanumeric(11)).hashCode()) .isNotEqualTo(new RekeyedProject(newRandomProject(), previousKey).hashCode()) .isNotEqualTo(new Object().hashCode()); } @Test public void verify_toString() { Project project = new Project("A", "B", "C", "D", emptyList()); String previousKey = "E"; RekeyedProject underTest = new RekeyedProject(project, previousKey); assertThat(underTest).hasToString("RekeyedProject{project=Project{uuid='A', key='B', name='C', description='D'}, previousKey='E'}"); } private static Project newRandomProject() { return Project.from(newPrivateProjectDto()); } }
3,710
36.484848
136
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventListenersImplTest.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.qualitygate.changeevent; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Random; import java.util.Set; import java.util.stream.Stream; import org.apache.commons.lang.RandomStringUtils; import org.assertj.core.groups.Tuple; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.Mockito; import org.slf4j.event.Level; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.component.BranchDto; import org.sonar.server.qualitygate.changeevent.QGChangeEventListener.ChangedIssue; import static java.util.Collections.emptyList; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class QGChangeEventListenersImplTest { @Rule public LogTester logTester = new LogTester(); private final QGChangeEventListener listener1 = mock(QGChangeEventListener.class); private final QGChangeEventListener listener2 = mock(QGChangeEventListener.class); private final QGChangeEventListener listener3 = mock(QGChangeEventListener.class); private final List<QGChangeEventListener> listeners = Arrays.asList(listener1, listener2, listener3); private final String project1Uuid = RandomStringUtils.randomAlphabetic(6); private final BranchDto project1 = newBranchDto(project1Uuid); private final DefaultIssue component1Issue = newDefaultIssue(project1Uuid); private final List<DefaultIssue> oneIssueOnComponent1 = singletonList(component1Issue); private final QGChangeEvent component1QGChangeEvent = newQGChangeEvent(project1); private final InOrder inOrder = Mockito.inOrder(listener1, listener2, listener3); private final QGChangeEventListenersImpl underTest = new QGChangeEventListenersImpl(new LinkedHashSet<>(List.of(listener1, listener2, listener3))); @Before public void before() { logTester.setLevel(Level.TRACE); } @Test public void broadcastOnIssueChange_has_no_effect_when_issues_are_empty() { underTest.broadcastOnIssueChange(emptyList(), singletonList(component1QGChangeEvent), false); verifyNoInteractions(listener1, listener2, listener3); } @Test public void broadcastOnIssueChange_has_no_effect_when_no_changeEvent() { underTest.broadcastOnIssueChange(oneIssueOnComponent1, emptySet(), false); verifyNoInteractions(listener1, listener2, listener3); } @Test public void broadcastOnIssueChange_passes_same_arguments_to_all_listeners_in_order_of_addition_to_constructor() { underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false); ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor(); inOrder.verify(listener1).onIssueChanges(same(component1QGChangeEvent), changedIssuesCaptor.capture()); Set<ChangedIssue> changedIssues = changedIssuesCaptor.getValue(); inOrder.verify(listener2).onIssueChanges(same(component1QGChangeEvent), same(changedIssues)); inOrder.verify(listener3).onIssueChanges(same(component1QGChangeEvent), same(changedIssues)); inOrder.verifyNoMoreInteractions(); } @Test public void broadcastOnIssueChange_calls_all_listeners_even_if_one_throws_an_exception() { QGChangeEventListener failingListener = new QGChangeEventListener[] {listener1, listener2, listener3}[new Random().nextInt(3)]; doThrow(new RuntimeException("Faking an exception thrown by onChanges")) .when(failingListener) .onIssueChanges(any(), any()); underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false); ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor(); inOrder.verify(listener1).onIssueChanges(same(component1QGChangeEvent), changedIssuesCaptor.capture()); Set<ChangedIssue> changedIssues = changedIssuesCaptor.getValue(); inOrder.verify(listener2).onIssueChanges(same(component1QGChangeEvent), same(changedIssues)); inOrder.verify(listener3).onIssueChanges(same(component1QGChangeEvent), same(changedIssues)); inOrder.verifyNoMoreInteractions(); assertThat(logTester.logs()).hasSize(4); assertThat(logTester.logs(Level.WARN)).hasSize(1); } @Test public void broadcastOnIssueChange_stops_calling_listeners_when_one_throws_an_ERROR() { doThrow(new Error("Faking an error thrown by a listener")) .when(listener2) .onIssueChanges(any(), any()); underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false); ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor(); inOrder.verify(listener1).onIssueChanges(same(component1QGChangeEvent), changedIssuesCaptor.capture()); Set<ChangedIssue> changedIssues = changedIssuesCaptor.getValue(); inOrder.verify(listener2).onIssueChanges(same(component1QGChangeEvent), same(changedIssues)); inOrder.verifyNoMoreInteractions(); assertThat(logTester.logs()).hasSize(3); assertThat(logTester.logs(Level.WARN)).hasSize(1); } @Test public void broadcastOnIssueChange_logs_each_listener_call_at_TRACE_level() { underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false); assertThat(logTester.logs()).hasSize(3); List<String> traceLogs = logTester.logs(Level.TRACE); assertThat(traceLogs).hasSize(3) .containsOnly( "calling onChange() on listener " + listener1.getClass().getName() + " for events " + component1QGChangeEvent + "...", "calling onChange() on listener " + listener2.getClass().getName() + " for events " + component1QGChangeEvent + "...", "calling onChange() on listener " + listener3.getClass().getName() + " for events " + component1QGChangeEvent + "..."); } @Test public void broadcastOnIssueChange_passes_immutable_set_of_ChangedIssues() { QGChangeEventListenersImpl underTest = new QGChangeEventListenersImpl(Set.of(listener1)); underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false); ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor(); inOrder.verify(listener1).onIssueChanges(same(component1QGChangeEvent), changedIssuesCaptor.capture()); assertThat(changedIssuesCaptor.getValue()).isInstanceOf(ImmutableSet.class); } @Test public void broadcastOnIssueChange_has_no_effect_when_no_listener() { QGChangeEventListenersImpl underTest = new QGChangeEventListenersImpl(Set.of()); underTest.broadcastOnIssueChange(oneIssueOnComponent1, singletonList(component1QGChangeEvent), false); verifyNoInteractions(listener1, listener2, listener3); } @Test public void broadcastOnIssueChange_calls_listener_for_each_component_uuid_with_at_least_one_QGChangeEvent() { // branch has multiple issues BranchDto component2 = newBranchDto(project1Uuid + "2"); DefaultIssue[] component2Issues = {newDefaultIssue(component2.getUuid()), newDefaultIssue(component2.getUuid())}; QGChangeEvent component2QGChangeEvent = newQGChangeEvent(component2); // branch 3 has multiple QGChangeEvent and only one issue BranchDto component3 = newBranchDto(project1Uuid + "3"); DefaultIssue component3Issue = newDefaultIssue(component3.getUuid()); QGChangeEvent[] component3QGChangeEvents = {newQGChangeEvent(component3), newQGChangeEvent(component3)}; // branch 4 has multiple QGChangeEvent and multiples issues BranchDto component4 = newBranchDto(project1Uuid + "4"); DefaultIssue[] component4Issues = {newDefaultIssue(component4.getUuid()), newDefaultIssue(component4.getUuid())}; QGChangeEvent[] component4QGChangeEvents = {newQGChangeEvent(component4), newQGChangeEvent(component4)}; // branch 5 has no QGChangeEvent but one issue BranchDto component5 = newBranchDto(project1Uuid + "5"); DefaultIssue component5Issue = newDefaultIssue(component5.getUuid()); List<DefaultIssue> issues = Stream.of( Stream.of(component1Issue), Arrays.stream(component2Issues), Stream.of(component3Issue), Arrays.stream(component4Issues), Stream.of(component5Issue)) .flatMap(s -> s) .toList(); List<DefaultIssue> changedIssues = randomizedList(issues); List<QGChangeEvent> qgChangeEvents = Stream.of( Stream.of(component1QGChangeEvent), Stream.of(component2QGChangeEvent), Arrays.stream(component3QGChangeEvents), Arrays.stream(component4QGChangeEvents)) .flatMap(s -> s) .toList(); underTest.broadcastOnIssueChange(changedIssues, randomizedList(qgChangeEvents), false); listeners.forEach(listener -> { verifyListenerCalled(listener, component1QGChangeEvent, component1Issue); verifyListenerCalled(listener, component2QGChangeEvent, component2Issues); Arrays.stream(component3QGChangeEvents) .forEach(component3QGChangeEvent -> verifyListenerCalled(listener, component3QGChangeEvent, component3Issue)); Arrays.stream(component4QGChangeEvents) .forEach(component4QGChangeEvent -> verifyListenerCalled(listener, component4QGChangeEvent, component4Issues)); }); verifyNoMoreInteractions(listener1, listener2, listener3); } @Test public void isNotClosed_returns_true_if_issue_in_one_of_opened_states() { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setStatus(Issue.STATUS_REOPENED); defaultIssue.setKey("abc"); defaultIssue.setType(RuleType.BUG); defaultIssue.setSeverity("BLOCKER"); ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue); assertThat(changedIssue.isNotClosed()).isTrue(); } @Test public void isNotClosed_returns_false_if_issue_in_one_of_closed_states() { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setStatus(Issue.STATUS_CONFIRMED); defaultIssue.setKey("abc"); defaultIssue.setType(RuleType.BUG); defaultIssue.setSeverity("BLOCKER"); ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue); assertThat(changedIssue.isNotClosed()).isFalse(); } @Test public void isVulnerability_returns_true_if_issue_is_of_type_vulnerability() { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setStatus(Issue.STATUS_OPEN); defaultIssue.setType(RuleType.VULNERABILITY); ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue); assertThat(changedIssue.isVulnerability()).isTrue(); } @Test public void isVulnerability_returns_false_if_issue_is_not_of_type_vulnerability() { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setStatus(Issue.STATUS_OPEN); defaultIssue.setType(RuleType.BUG); ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue); assertThat(changedIssue.isVulnerability()).isFalse(); } @Test public void fromAlm_returns_false_by_default() { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setStatus(Issue.STATUS_OPEN); ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue); assertThat(changedIssue.fromAlm()).isFalse(); } @Test public void getSeverity_should_returns_default_issue_severity() { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setStatus(Issue.STATUS_OPEN); defaultIssue.setSeverity("BLOCKER"); ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue); assertThat(changedIssue.getSeverity()).isEqualTo(defaultIssue.severity()); } @Test public void test_ChangedIssueImpl_toString() { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setStatus(Issue.STATUS_CONFIRMED); defaultIssue.setKey("abc"); defaultIssue.setType(RuleType.BUG); defaultIssue.setSeverity("BLOCKER"); String expected = "ChangedIssueImpl{key='abc', status=" + Issue.STATUS_CONFIRMED + ", type=" + RuleType.BUG + ", severity=BLOCKER, fromAlm=false}"; ChangedIssue changedIssue = new ChangedIssueImpl(defaultIssue); assertThat(changedIssue).hasToString(expected); } @Test public void test_status_mapping() { assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_OPEN))).isEqualTo(QGChangeEventListener.Status.OPEN); assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_REOPENED))).isEqualTo(QGChangeEventListener.Status.REOPENED); assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_CONFIRMED))).isEqualTo(QGChangeEventListener.Status.CONFIRMED); assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_FALSE_POSITIVE))) .isEqualTo(QGChangeEventListener.Status.RESOLVED_FP); assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_WONT_FIX))) .isEqualTo(QGChangeEventListener.Status.RESOLVED_WF); assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_FIXED))) .isEqualTo(QGChangeEventListener.Status.RESOLVED_FIXED); try { ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_CLOSED)); fail("Expected exception"); } catch (Exception e) { assertThat(e).hasMessage("Unexpected status: CLOSED"); } try { ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED)); fail("Expected exception"); } catch (Exception e) { assertThat(e).hasMessage("A resolved issue should have a resolution"); } try { ChangedIssueImpl.statusOf(new DefaultIssue().setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_REMOVED)); fail("Expected exception"); } catch (Exception e) { assertThat(e).hasMessage("Unexpected resolution for a resolved issue: REMOVED"); } } @Test public void test_status_mapping_on_security_hotspots() { assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_TO_REVIEW))) .isEqualTo(QGChangeEventListener.Status.TO_REVIEW); assertThat(ChangedIssueImpl.statusOf(new DefaultIssue().setType(RuleType.SECURITY_HOTSPOT).setStatus(Issue.STATUS_REVIEWED))) .isEqualTo(QGChangeEventListener.Status.REVIEWED); } private void verifyListenerCalled(QGChangeEventListener listener, QGChangeEvent changeEvent, DefaultIssue... issues) { ArgumentCaptor<Set<ChangedIssue>> changedIssuesCaptor = newSetCaptor(); verify(listener).onIssueChanges(same(changeEvent), changedIssuesCaptor.capture()); Set<ChangedIssue> changedIssues = changedIssuesCaptor.getValue(); Tuple[] expected = Arrays.stream(issues) .map(issue -> tuple(issue.key(), ChangedIssueImpl.statusOf(issue), issue.type())) .toArray(Tuple[]::new); assertThat(changedIssues) .hasSize(issues.length) .extracting(ChangedIssue::getKey, ChangedIssue::getStatus, ChangedIssue::getType) .containsOnly(expected); } private static final String[] POSSIBLE_STATUSES = Stream.of(Issue.STATUS_CONFIRMED, Issue.STATUS_REOPENED, Issue.STATUS_RESOLVED).toArray(String[]::new); private static int issueIdCounter = 0; private static DefaultIssue newDefaultIssue(String projectUuid) { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setKey("issue_" + issueIdCounter++); defaultIssue.setProjectUuid(projectUuid); defaultIssue.setType(RuleType.values()[new Random().nextInt(RuleType.values().length)]); defaultIssue.setStatus(POSSIBLE_STATUSES[new Random().nextInt(POSSIBLE_STATUSES.length)]); String[] possibleResolutions = possibleResolutions(defaultIssue.getStatus()); if (possibleResolutions.length > 0) { defaultIssue.setResolution(possibleResolutions[new Random().nextInt(possibleResolutions.length)]); } return defaultIssue; } private static String[] possibleResolutions(String status) { if (Issue.STATUS_RESOLVED.equals(status)) { return new String[]{Issue.RESOLUTION_FALSE_POSITIVE, Issue.RESOLUTION_WONT_FIX}; } return new String[0]; } private static BranchDto newBranchDto(String uuid) { BranchDto branchDto = new BranchDto(); branchDto.setUuid(uuid); return branchDto; } private static QGChangeEvent newQGChangeEvent(BranchDto branch) { QGChangeEvent res = mock(QGChangeEvent.class); when(res.getBranch()).thenReturn(branch); return res; } private static <T> ArgumentCaptor<Set<T>> newSetCaptor() { Class<Set<T>> clazz = (Class<Set<T>>) (Class) Set.class; return ArgumentCaptor.forClass(clazz); } private static <T> List<T> randomizedList(List<T> issues) { ArrayList<T> res = new ArrayList<>(issues); Collections.shuffle(res); return ImmutableList.copyOf(res); } }
18,496
43.571084
155
java
sonarqube
sonarqube-master/server/sonar-webserver-api/src/test/java/org/sonar/server/qualitygate/changeevent/QGChangeEventTest.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.qualitygate.changeevent; import java.util.Optional; import java.util.Random; import java.util.function.Supplier; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.config.Configuration; import org.sonar.api.measures.Metric; import org.sonar.db.component.BranchDto; import org.sonar.db.component.BranchType; import org.sonar.db.component.SnapshotDto; import org.sonar.db.project.ProjectDto; import org.sonar.server.qualitygate.EvaluatedQualityGate; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QGChangeEventTest { private final ProjectDto project = new ProjectDto() .setKey("foo") .setUuid("bar"); private final BranchDto branch = new BranchDto() .setBranchType(BranchType.BRANCH) .setUuid("bar") .setProjectUuid("doh") .setMergeBranchUuid("zop"); private final SnapshotDto analysis = new SnapshotDto() .setUuid("pto") .setCreatedAt(8_999_999_765L); private final Configuration configuration = Mockito.mock(Configuration.class); private final Metric.Level previousStatus = Metric.Level.values()[new Random().nextInt(Metric.Level.values().length)]; private Supplier<Optional<EvaluatedQualityGate>> supplier = Optional::empty; @Test public void constructor_fails_with_NPE_if_project_is_null() { assertThatThrownBy(() -> new QGChangeEvent(null, branch, analysis, configuration, previousStatus, supplier)) .isInstanceOf(NullPointerException.class) .hasMessage("project can't be null"); } @Test public void constructor_fails_with_NPE_if_branch_is_null() { assertThatThrownBy(() -> new QGChangeEvent(project, null, analysis, configuration, previousStatus, supplier)) .isInstanceOf(NullPointerException.class) .hasMessage("branch can't be null"); } @Test public void constructor_fails_with_NPE_if_analysis_is_null() { assertThatThrownBy(() -> new QGChangeEvent(project, branch, null, configuration, previousStatus, supplier)) .isInstanceOf(NullPointerException.class) .hasMessage("analysis can't be null"); } @Test public void constructor_fails_with_NPE_if_configuration_is_null() { assertThatThrownBy(() -> new QGChangeEvent(project, branch, analysis, null, previousStatus, supplier)) .isInstanceOf(NullPointerException.class) .hasMessage("projectConfiguration can't be null"); } @Test public void constructor_does_not_fail_with_NPE_if_previousStatus_is_null() { assertThatCode(() -> new QGChangeEvent(project, branch, analysis, configuration, null, supplier)).doesNotThrowAnyException(); } @Test public void constructor_fails_with_NPE_if_supplier_is_null() { assertThatThrownBy(() -> new QGChangeEvent(project, branch, analysis, configuration, previousStatus, null)) .isInstanceOf(NullPointerException.class) .hasMessage("qualityGateSupplier can't be null"); } @Test public void verify_getters() { QGChangeEvent underTest = new QGChangeEvent(project, branch, analysis, configuration, previousStatus, supplier); assertThat(underTest.getProject()).isSameAs(project); assertThat(underTest.getBranch()).isSameAs(branch); assertThat(underTest.getAnalysis()).isSameAs(analysis); assertThat(underTest.getProjectConfiguration()).isSameAs(configuration); assertThat(underTest.getPreviousStatus()).contains(previousStatus); assertThat(underTest.getQualityGateSupplier()).isSameAs(supplier); } @Test public void getPreviousStatus_returns_empty_when_previousStatus_is_null() { QGChangeEvent underTest = new QGChangeEvent(project, branch, analysis, configuration, previousStatus, supplier); assertThat(underTest.getPreviousStatus()).contains(previousStatus); } @Test public void overrides_toString() { QGChangeEvent underTest = new QGChangeEvent(project, branch, analysis, configuration, previousStatus, supplier); assertThat(underTest) .hasToString("QGChangeEvent{project=bar:foo, branch=BRANCH:bar:doh:zop, analysis=pto:8999999765" + ", projectConfiguration=" + configuration.toString() + ", previousStatus=" + previousStatus + ", qualityGateSupplier=" + supplier + "}"); } }
5,175
39.755906
129
java