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-ws/src/main/java/org/sonar/server/ws/ServletResponse.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.Collection; import javax.servlet.http.HttpServletResponse; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.server.ws.Response; import org.sonar.api.utils.text.JsonWriter; import org.sonar.api.utils.text.XmlWriter; import org.sonar.server.http.JavaxHttpResponse; import static java.nio.charset.StandardCharsets.UTF_8; import static org.sonarqube.ws.MediaTypes.JSON; import static org.sonarqube.ws.MediaTypes.XML; public class ServletResponse implements Response { private final ServletStream stream; public ServletResponse(HttpResponse response) { HttpServletResponse httpServletResponse = ((JavaxHttpResponse) response).getDelegate(); stream = new ServletStream(httpServletResponse); } public static class ServletStream implements Stream { private final HttpServletResponse response; public ServletStream(HttpServletResponse response) { this.response = response; this.response.setStatus(200); // SONAR-6964 WS should not be cached by browser this.response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); } @Override public ServletStream setMediaType(String s) { this.response.setContentType(s); return this; } @Override public ServletStream setStatus(int httpStatus) { this.response.setStatus(httpStatus); return this; } @Override public OutputStream output() { try { return response.getOutputStream(); } catch (IOException e) { throw new IllegalStateException(e); } } HttpServletResponse response() { return response; } public ServletStream reset() { response.reset(); return this; } public ServletStream flushBuffer() throws IOException { response.flushBuffer(); return this; } public ServletStream setCharacterEncoding(String charset) { response.setCharacterEncoding(charset); return this; } } @Override public JsonWriter newJsonWriter() { stream.setMediaType(JSON); return JsonWriter.of(new CacheWriter(new OutputStreamWriter(stream.output(), StandardCharsets.UTF_8))); } @Override public XmlWriter newXmlWriter() { stream.setMediaType(XML); return XmlWriter.of(new OutputStreamWriter(stream.output(), UTF_8)); } @Override public ServletStream stream() { return stream; } @Override public Response noContent() { stream.setStatus(204); return this; } @Override public Response setHeader(String name, String value) { stream.response().setHeader(name, value); return this; } @Override public Collection<String> getHeaderNames() { return stream.response().getHeaderNames(); } @Override public String getHeader(String name) { return stream.response().getHeader(name); } }
3,862
27.19708
107
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WebServiceEngine.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.google.common.base.Throwables; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Locale; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.catalina.connector.ClientAbortException; import org.sonar.api.Startable; import org.sonar.api.impl.ws.ValidatingRequest; import org.sonar.api.server.ServerSide; import org.sonar.api.server.ws.LocalConnector; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.utils.text.JsonWriter; import org.sonar.server.exceptions.BadConfigurationException; import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ServerException; import org.sonarqube.ws.MediaTypes; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.isNullOrEmpty; import static java.util.Collections.singletonList; import static java.util.Objects.requireNonNull; import static org.apache.commons.lang.StringUtils.substring; import static org.apache.commons.lang.StringUtils.substringAfterLast; import static org.apache.commons.lang.StringUtils.substringBeforeLast; import static org.sonar.server.exceptions.NotFoundException.checkFound; import static org.sonar.server.ws.RequestVerifier.verifyRequest; import static org.sonar.server.ws.ServletRequest.SUPPORTED_MEDIA_TYPES_BY_URL_SUFFIX; /** * @since 4.2 */ @ServerSide public class WebServiceEngine implements LocalConnector, Startable { private static final Logger LOGGER = LoggerFactory.getLogger(WebServiceEngine.class); private final WebService[] webServices; private WebService.Context context; public WebServiceEngine(WebService[] webServices) { this.webServices = webServices; } @Override public void start() { context = new WebService.Context(); for (WebService webService : webServices) { webService.define(context); } } @Override public void stop() { // nothing } private WebService.Context getContext() { return requireNonNull(context, "Web services has not yet been initialized"); } public List<WebService.Controller> controllers() { return getContext().controllers(); } @Override public LocalResponse call(LocalRequest request) { DefaultLocalResponse localResponse = new DefaultLocalResponse(); execute(new LocalRequestAdapter(request), localResponse); return localResponse; } public void execute(Request request, Response response) { try { ActionExtractor actionExtractor = new ActionExtractor(request.getPath()); WebService.Action action = getAction(actionExtractor); checkFound(action, "Unknown url : %s", request.getPath()); if (request instanceof ValidatingRequest validatingRequest) { validatingRequest.setAction(action); validatingRequest.setLocalConnector(this); } checkActionExtension(actionExtractor.getExtension()); verifyRequest(action, request); action.handler().handle(request, response); } catch (IllegalArgumentException e) { sendErrors(request, response, e, 400, singletonList(e.getMessage())); } catch (BadConfigurationException e) { sendErrors(request, response, e, 400, e.errors(), e.scope()); } catch (BadRequestException e) { sendErrors(request, response, e, 400, e.errors()); } catch (ServerException e) { sendErrors(request, response, e, e.httpCode(), singletonList(e.getMessage())); } catch (Exception e) { sendErrors(request, response, e, 500, singletonList("An error has occurred. Please contact your administrator")); } } @CheckForNull private WebService.Action getAction(ActionExtractor actionExtractor) { String controllerPath = actionExtractor.getController(); String actionKey = actionExtractor.getAction(); WebService.Controller controller = getContext().controller(controllerPath); return controller == null ? null : controller.action(actionKey); } private static void sendErrors(Request request, Response response, Exception exception, int status, List<String> errors) { sendErrors(request, response, exception, status, errors, null); } private static void sendErrors(Request request, Response response, Exception exception, int status, List<String> errors, @Nullable String scope) { if (isRequestAbortedByClient(exception)) { // do not pollute logs. We can't do anything -> use DEBUG level // see org.sonar.server.ws.ServletResponse#output() LOGGER.debug(String.format("Request %s has been aborted by client", request), exception); if (!isResponseCommitted(response)) { // can be useful for access.log response.stream().setStatus(299); } return; } if (status == 500) { // Sending exception message into response is a vulnerability. Error must be // displayed only in logs. LOGGER.error("Fail to process request " + request, exception); } Response.Stream stream = response.stream(); if (isResponseCommitted(response)) { // status can't be changed LOGGER.debug(String.format("Request %s failed during response streaming", request), exception); return; } // response is not committed, status and content can be changed to return the error if (stream instanceof ServletResponse.ServletStream servletStream) { servletStream.reset(); } stream.setStatus(status); stream.setMediaType(MediaTypes.JSON); try (JsonWriter json = JsonWriter.of(new OutputStreamWriter(stream.output(), StandardCharsets.UTF_8))) { json.beginObject(); writeScope(scope, json); writeErrors(json, errors); json.endObject(); } catch (Exception e) { // Do not hide the potential exception raised in the try block. throw Throwables.propagate(e); } } private static void writeScope(@Nullable String scope, JsonWriter json) { if (scope != null) { json.prop("scope", scope); } } private static boolean isRequestAbortedByClient(Exception exception) { return Throwables.getCausalChain(exception).stream().anyMatch(t -> t instanceof ClientAbortException); } private static boolean isResponseCommitted(Response response) { Response.Stream stream = response.stream(); // Request has been aborted by the client or the response was partially streamed, nothing can been done as Tomcat has committed the response return stream instanceof ServletResponse.ServletStream servletStream && servletStream.response().isCommitted(); } public static void writeErrors(JsonWriter json, List<String> errorMessages) { if (errorMessages.isEmpty()) { return; } json.name("errors").beginArray(); errorMessages.forEach(message -> { json.beginObject(); json.prop("msg", message); json.endObject(); }); json.endArray(); } private static void checkActionExtension(@Nullable String actionExtension) { if (isNullOrEmpty(actionExtension)) { return; } checkArgument(SUPPORTED_MEDIA_TYPES_BY_URL_SUFFIX.get(actionExtension.toLowerCase(Locale.ENGLISH)) != null, "Unknown action extension: %s", actionExtension); } private static class ActionExtractor { private static final String SLASH = "/"; private static final String POINT = "."; private final String controller; private final String action; private final String extension; private final String path; ActionExtractor(String path) { this.path = path; String pathWithoutExtension = substringBeforeLast(path, POINT); this.controller = extractController(pathWithoutExtension); this.action = substringAfterLast(pathWithoutExtension, SLASH); checkArgument(!action.isEmpty(), "Url is incorrect : '%s'", path); this.extension = substringAfterLast(path, POINT); } private static String extractController(String path) { String controller = substringBeforeLast(path, SLASH); if (controller.startsWith(SLASH)) { return substring(controller, 1); } return controller; } String getController() { return controller; } String getAction() { return action; } @CheckForNull String getExtension() { return extension; } String getPath() { return path; } } }
9,400
35.157692
161
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WsAction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import org.sonar.api.server.ws.Definable; import org.sonar.api.server.ws.RequestHandler; import org.sonar.api.server.ws.WebService; /** * Since 5.2, this interface is the base for Web Service marker interfaces * Convention for naming implementations: <i>web_service_class_name</i>Action. ex: ProjectsWsAction, UsersWsAction */ public interface WsAction extends RequestHandler, Definable<WebService.NewController> { // Marker interface }
1,316
38.909091
114
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WsParameterBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import java.util.Locale; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService; import org.sonar.core.i18n.I18n; import static java.lang.String.format; public class WsParameterBuilder { private static final String PARAM_QUALIFIER = "qualifier"; private static final String PARAM_QUALIFIERS = "qualifiers"; private WsParameterBuilder() { // static methods only } public static WebService.NewParam createRootQualifierParameter(WebService.NewAction action, QualifierParameterContext context) { return action.createParam(PARAM_QUALIFIER) .setDescription("Project qualifier. Filter the results with the specified qualifier. Possible values are:" + buildRootQualifiersDescription(context)) .setPossibleValues(getRootQualifiers(context.getResourceTypes())); } public static WebService.NewParam createRootQualifiersParameter(WebService.NewAction action, QualifierParameterContext context) { return action.createParam(PARAM_QUALIFIERS) .setDescription("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers. " + "Possible values are:" + buildRootQualifiersDescription(context)) .setPossibleValues(getRootQualifiers(context.getResourceTypes())); } public static WebService.NewParam createDefaultTemplateQualifierParameter(WebService.NewAction action, QualifierParameterContext context) { return action.createParam(PARAM_QUALIFIER) .setDescription("Project qualifier. Filter the results with the specified qualifier. Possible values are:" + buildDefaultTemplateQualifiersDescription(context)) .setPossibleValues(getDefaultTemplateQualifiers(context.getResourceTypes())); } public static WebService.NewParam createQualifiersParameter(WebService.NewAction action, QualifierParameterContext context) { return createQualifiersParameter(action, context, getAllQualifiers(context.getResourceTypes())); } public static WebService.NewParam createQualifiersParameter(WebService.NewAction action, QualifierParameterContext context, Set<String> availableQualifiers) { Set<String> filteredQualifiers = getAllQualifiers(context.getResourceTypes()).stream().filter(availableQualifiers::contains) .collect(Collectors.toSet()); return action.createParam(PARAM_QUALIFIERS) .setDescription( "Comma-separated list of component qualifiers. Filter the results with the specified qualifiers. Possible values are:" + buildQualifiersDescription(context, filteredQualifiers)) .setPossibleValues(filteredQualifiers); } private static Set<String> getRootQualifiers(ResourceTypes resourceTypes) { return resourceTypes.getRoots().stream() .map(ResourceType::getQualifier) .collect(Collectors.toCollection(TreeSet::new)); } private static Set<String> getDefaultTemplateQualifiers(ResourceTypes resourceTypes) { return resourceTypes.getRoots().stream() .map(ResourceType::getQualifier) .collect(Collectors.toCollection(TreeSet::new)); } private static Set<String> getAllQualifiers(ResourceTypes resourceTypes) { return resourceTypes.getAll().stream() .filter(r -> !r.getBooleanProperty("ignored")) .map(ResourceType::getQualifier) .collect(Collectors.toCollection(TreeSet::new)); } private static String buildDefaultTemplateQualifiersDescription(QualifierParameterContext context) { return buildQualifiersDescription(context, getDefaultTemplateQualifiers(context.getResourceTypes())); } private static String buildRootQualifiersDescription(QualifierParameterContext context) { return buildQualifiersDescription(context, getRootQualifiers(context.getResourceTypes())); } private static String buildQualifiersDescription(QualifierParameterContext context, Set<String> qualifiers) { StringBuilder description = new StringBuilder(); description.append("<ul>"); String qualifierPattern = "<li>%s - %s</li>"; for (String qualifier : qualifiers) { description.append(format(qualifierPattern, qualifier, qualifierLabel(context, qualifier))); } description.append("</ul>"); return description.toString(); } private static String qualifierLabel(QualifierParameterContext context, String qualifier) { String qualifiersPropertyPrefix = "qualifiers."; return context.getI18n().message(Locale.ENGLISH, qualifiersPropertyPrefix + qualifier, "no description available"); } public static class QualifierParameterContext { private final I18n i18n; private final ResourceTypes resourceTypes; private QualifierParameterContext(I18n i18n, ResourceTypes resourceTypes) { this.i18n = i18n; this.resourceTypes = resourceTypes; } public static QualifierParameterContext newQualifierParameterContext(I18n i18n, ResourceTypes resourceTypes) { return new QualifierParameterContext(i18n, resourceTypes); } public I18n getI18n() { return i18n; } public ResourceTypes getResourceTypes() { return resourceTypes; } } }
6,084
42.464286
166
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/WsUtils.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.google.protobuf.Message; import java.io.OutputStream; import java.io.OutputStreamWriter; import org.apache.commons.io.IOUtils; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.Response; import org.sonar.api.utils.text.JsonWriter; import org.sonar.core.util.ProtobufJsonFormat; import static java.nio.charset.StandardCharsets.UTF_8; import static org.sonarqube.ws.MediaTypes.JSON; import static org.sonarqube.ws.MediaTypes.PROTOBUF; public interface WsUtils { static void writeProtobuf(Message msg, Request request, Response response) { OutputStream output = response.stream().output(); try { if (request.getMediaType().equals(PROTOBUF)) { response.stream().setMediaType(PROTOBUF); msg.writeTo(output); } else { response.stream().setMediaType(JSON); try (JsonWriter writer = JsonWriter.of(new OutputStreamWriter(output, UTF_8))) { ProtobufJsonFormat.write(msg, writer); } } } catch (Exception e) { throw new IllegalStateException("Error while writing protobuf message", e); } finally { IOUtils.closeQuietly(output); } } static String createHtmlExternalLink(String url, String text) { return String.format("<a href=\"%s\" target=\"_blank\" rel=\"noopener noreferrer\">%s</a>", url, text); } }
2,213
35.9
107
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/main/java/org/sonar/server/ws/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.ws; import javax.annotation.ParametersAreNonnullByDefault;
959
39
75
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/CacheWriterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class CacheWriterTest { private Writer writer = new StringWriter(); private CacheWriter underTest = new CacheWriter(writer); @Test public void write_content_when_closing_resource() throws IOException { underTest.write("content"); assertThat(writer.toString()).isEmpty(); underTest.close(); assertThat(writer).hasToString("content"); } @Test public void close_encapsulated_writer_once() throws IOException { writer = mock(Writer.class); underTest = new CacheWriter(writer); underTest.close(); underTest.close(); verify(writer, times(1)).close(); } }
1,773
30.122807
75
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/MessageFormattingUtilsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import org.junit.Test; import org.sonar.db.protobuf.DbIssues; import org.sonarqube.ws.Common; import static org.assertj.core.api.Assertions.assertThat; public class MessageFormattingUtilsTest { @Test public void nullFormattingShouldBeEmptyList() { assertThat(MessageFormattingUtils.dbMessageFormattingToWs(null)).isEmpty(); } @Test public void nullFormattingListShouldBeEmptyList() { assertThat(MessageFormattingUtils.dbMessageFormattingListToWs(null)).isEmpty(); } @Test public void singleEntryShouldBeIdentical() { DbIssues.MessageFormattings formattings = DbIssues.MessageFormattings.newBuilder() .addMessageFormatting(DbIssues.MessageFormatting.newBuilder() .setStart(0) .setEnd(4) .setType(DbIssues.MessageFormattingType.CODE) .build()) .build(); assertThat(MessageFormattingUtils.dbMessageFormattingToWs( formattings).get(0)) .extracting(e -> e.getStart(), e -> e.getEnd(), e -> e.getType()) .containsExactly(0, 4, Common.MessageFormattingType.CODE); } }
1,940
33.660714
86
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/RemovedWebServiceHandlerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.server.exceptions.ServerException; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RemovedWebServiceHandlerTest { @Test public void throw_server_exception() { Request request = mock(Request.class); when(request.getPath()).thenReturn("/api/resources/index"); try { RemovedWebServiceHandler.INSTANCE.handle(request, null); fail(); } catch (ServerException e) { assertThat(e.getMessage()).isEqualTo("The web service '/api/resources/index' doesn't exist anymore, please read its documentation to use alternatives"); assertThat(e.httpCode()).isEqualTo(410); } } }
1,707
34.583333
158
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletRequestTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.google.common.net.HttpHeaders; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.StringReader; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Part; import org.junit.Test; import org.sonar.server.http.JavaxHttpRequest; import org.sonarqube.ws.MediaTypes; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ServletRequestTest { private final HttpServletRequest source = mock(HttpServletRequest.class); private final ServletRequest underTest = new ServletRequest(new JavaxHttpRequest(source)); @Test public void call_method() { underTest.method(); verify(source).getMethod(); } @Test public void getMediaType() { when(source.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaTypes.JSON); when(source.getRequestURI()).thenReturn("/path/to/resource/search"); assertThat(underTest.getMediaType()).isEqualTo(MediaTypes.JSON); } @Test public void default_media_type_is_octet_stream() { when(source.getRequestURI()).thenReturn("/path/to/resource/search"); assertThat(underTest.getMediaType()).isEqualTo(MediaTypes.DEFAULT); } @Test public void media_type_taken_in_url_first() { when(source.getHeader(HttpHeaders.ACCEPT)).thenReturn(MediaTypes.JSON); when(source.getRequestURI()).thenReturn("/path/to/resource/search.protobuf"); assertThat(underTest.getMediaType()).isEqualTo(MediaTypes.PROTOBUF); } @Test public void has_param_from_source() { when(source.getParameterMap()).thenReturn(Map.of("param", new String[] {"value"})); ServletRequest request = new ServletRequest(new JavaxHttpRequest(source)); assertThat(request.hasParam("param")).isTrue(); } @Test public void read_param_from_source() { when(source.getParameter("param")).thenReturn("value"); assertThat(underTest.readParam("param")).isEqualTo("value"); } @Test public void read_multi_param_from_source_with_values() { when(source.getParameterValues("param")).thenReturn(new String[]{"firstValue", "secondValue", "thirdValue"}); List<String> result = underTest.readMultiParam("param"); assertThat(result).containsExactly("firstValue", "secondValue", "thirdValue"); } @Test public void read_multi_param_from_source_with_one_value() { when(source.getParameterValues("param")).thenReturn(new String[]{"firstValue"}); List<String> result = underTest.readMultiParam("param"); assertThat(result).containsExactly("firstValue"); } @Test public void read_multi_param_from_source_without_value() { when(source.getParameterValues("param")).thenReturn(null); List<String> result = underTest.readMultiParam("param"); assertThat(result).isEmpty(); } @Test public void read_input_stream() throws Exception { when(source.getContentType()).thenReturn("multipart/form-data"); InputStream file = mock(InputStream.class); Part part = mock(Part.class); when(part.getInputStream()).thenReturn(file); when(part.getSize()).thenReturn(10L); when(source.getPart("param1")).thenReturn(part); assertThat(underTest.readInputStreamParam("param1")).isEqualTo(file); assertThat(underTest.readInputStreamParam("param2")).isNull(); } @Test public void read_no_input_stream_when_part_size_is_zero() throws Exception { when(source.getContentType()).thenReturn("multipart/form-data"); InputStream file = mock(InputStream.class); Part part = mock(Part.class); when(part.getInputStream()).thenReturn(file); when(part.getSize()).thenReturn(0L); when(source.getPart("param1")).thenReturn(part); assertThat(underTest.readInputStreamParam("param1")).isNull(); } @Test public void return_no_input_stream_when_content_type_is_not_multipart() { when(source.getContentType()).thenReturn("multipart/form-data"); assertThat(underTest.readInputStreamParam("param1")).isNull(); } @Test public void return_no_input_stream_when_content_type_is_null() { when(source.getContentType()).thenReturn(null); assertThat(underTest.readInputStreamParam("param1")).isNull(); } @Test public void returns_null_when_invalid_part() throws Exception { when(source.getContentType()).thenReturn("multipart/form-data"); InputStream file = mock(InputStream.class); Part part = mock(Part.class); when(part.getSize()).thenReturn(0L); when(part.getInputStream()).thenReturn(file); doThrow(IllegalArgumentException.class).when(source).getPart("param1"); assertThat(underTest.readInputStreamParam("param1")).isNull(); } @Test public void getPath() { when(source.getRequestURI()).thenReturn("/sonar/path/to/resource/search"); when(source.getContextPath()).thenReturn("/sonar"); assertThat(underTest.getPath()).isEqualTo("/path/to/resource/search"); } @Test public void to_string() { when(source.getRequestURL()).thenReturn(new StringBuffer("http:localhost:9000/api/issues")); assertThat(underTest).hasToString("http:localhost:9000/api/issues"); when(source.getQueryString()).thenReturn("components=sonar"); assertThat(underTest).hasToString("http:localhost:9000/api/issues?components=sonar"); } @Test public void header_returns_the_value_of_http_header() { when(source.getHeader("Accept")).thenReturn("text/plain"); assertThat(underTest.header("Accept")).hasValue("text/plain"); } @Test public void header_is_empty_if_absent_from_request() { when(source.getHeader("Accept")).thenReturn(null); assertThat(underTest.header("Accept")).isEmpty(); } @Test public void header_has_empty_value_if_present_in_request_without_value() { when(source.getHeader("Accept")).thenReturn(""); assertThat(underTest.header("Accept")).hasValue(""); } @Test public void getReader() throws IOException { BufferedReader reader = new BufferedReader(new StringReader("foo")); when(source.getReader()).thenReturn(reader); assertThat(underTest.getReader()).isEqualTo(reader); } @Test public void startAsync() { underTest.startAsync(); verify(source).startAsync(); } }
7,249
31.80543
113
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/ServletResponseTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import java.io.IOException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.sonar.server.http.JavaxHttpResponse; import static org.assertj.core.api.Assertions.assertThat; 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.sonarqube.ws.MediaTypes.JSON; import static org.sonarqube.ws.MediaTypes.XML; public class ServletResponseTest { private final ServletOutputStream output = mock(ServletOutputStream.class); private final HttpServletResponse response = mock(HttpServletResponse.class); private final ServletResponse underTest = new ServletResponse(new JavaxHttpResponse(response)); @Before public void setUp() throws Exception { when(response.getOutputStream()).thenReturn(output); } @Test public void test_default_header() { verify(response).setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); } @Test public void set_header() { underTest.setHeader("header", "value"); verify(response).setHeader("header", "value"); } @Test public void get_header() { underTest.getHeader("header"); verify(response).getHeader("header"); } @Test public void get_header_names() { underTest.getHeaderNames(); verify(response).getHeaderNames(); } @Test public void test_default_status() { verify(response).setStatus(200); } @Test public void set_status() { underTest.stream().setStatus(404); verify(response).setStatus(404); } @Test public void setCharacterEncoding_encodingIsSet() { underTest.stream().setCharacterEncoding("UTF-8"); verify(response).setCharacterEncoding("UTF-8"); } @Test public void flushBuffer_bufferIsFlushed() throws IOException { underTest.stream().flushBuffer(); verify(response).flushBuffer(); } @Test public void test_output() { assertThat(underTest.stream().output()).isEqualTo(output); } @Test public void test_reset() { underTest.stream().reset(); verify(response).reset(); } @Test public void test_newJsonWriter() throws Exception { underTest.newJsonWriter(); verify(response).setContentType(JSON); verify(response).getOutputStream(); } @Test public void test_newXmlWriter() throws Exception { underTest.newXmlWriter(); verify(response).setContentType(XML); verify(response).getOutputStream(); } @Test public void test_noContent() throws Exception { underTest.noContent(); verify(response).setStatus(204); verify(response, never()).getOutputStream(); } }
3,612
25.181159
97
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WebServiceEngineTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.function.Consumer; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.connector.ClientAbortException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.slf4j.event.Level; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.RequestHandler; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.server.exceptions.BadConfigurationException; import org.sonar.server.exceptions.BadRequestException; import org.sonarqube.ws.MediaTypes; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.lang.StringUtils.substringAfterLast; import static org.apache.commons.lang.StringUtils.substringBeforeLast; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class WebServiceEngineTest { @Rule public LogTester logTester = new LogTester(); @Before public void setup() { logTester.setLevel(Level.DEBUG); } @Test public void load_ws_definitions_at_startup() { WebServiceEngine underTest = new WebServiceEngine(new WebService[]{ newWs("api/foo/index", a -> { }), newWs("api/bar/index", a -> { }) }); underTest.start(); try { assertThat(underTest.controllers()) .extracting(WebService.Controller::path) .containsExactlyInAnyOrder("api/foo", "api/bar"); } finally { underTest.stop(); } } @DataProvider public static Object[][] responseData() { return new Object[][]{ {"/api/ping", "pong", 200}, {"api/ping", "pong", 200}, {"api/ping.json", "pong", 200}, {"xxx/ping", "{\"errors\":[{\"msg\":\"Unknown url : xxx/ping\"}]}", 404}, {"api/xxx", "{\"errors\":[{\"msg\":\"Unknown url : api/xxx\"}]}", 404} }; } @Test @UseDataProvider("responseData") public void ws_returns_successful_response(String path, String output, int statusCode) { Request request = new TestRequest().setPath(path); DumbResponse response = run(request, newPingWs(a -> { })); assertThat(response.stream().outputAsString()).isEqualTo(output); assertThat(response.status()).isEqualTo(statusCode); } @Test public void bad_request_if_action_suffix_is_not_supported() { Request request = new TestRequest().setPath("/api/ping.bat"); DumbResponse response = run(request, newPingWs(a -> { })); assertThat(response.status()).isEqualTo(400); assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"Unknown action extension: bat\"}]}"); } @Test public void test_response_with_no_content() { Request request = new TestRequest().setPath("api/foo"); RequestHandler handler = (req, resp) -> resp.noContent(); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler(handler))); assertThat(response.stream().outputAsString()).isEmpty(); assertThat(response.status()).isEqualTo(204); } @Test public void fail_if_method_GET_is_not_allowed() { Request request = new TestRequest().setMethod("GET").setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setPost(true))); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"HTTP method POST is required\"}]}"); assertThat(response.status()).isEqualTo(405); } @Test public void fail_if_method_POST_is_not_allowed() { Request request = new TestRequest().setMethod("POST").setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setPost(false))); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"HTTP method GET is required\"}]}"); assertThat(response.status()).isEqualTo(405); } @DataProvider public static String[] verbs() { return new String[]{ "PUT", "DELETE", "HEAD", "PATCH", "CONNECT", "OPTIONS", "TRACE" }; } @Test @UseDataProvider("verbs") public void method_is_not_allowed(String verb) { Request request = new TestRequest().setMethod(verb).setPath("/api/ping"); DumbResponse response = run(request, newPingWs(a -> { })); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"HTTP method " + verb + " is not allowed\"}]}"); assertThat(response.status()).isEqualTo(405); } @Test public void method_POST_is_required() { Request request = new TestRequest().setMethod("POST").setPath("api/ping"); DumbResponse response = run(request, newPingWs(a -> a.setPost(true))); assertThat(response.stream().outputAsString()).isEqualTo("pong"); assertThat(response.status()).isEqualTo(200); } @Test public void fail_if_reading_an_undefined_parameter() { Request request = new TestRequest().setPath("api/foo").setParam("unknown", "Unknown"); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler((req, resp) -> request.param("unknown")))); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"BUG - parameter \\u0027unknown\\u0027 is undefined for action \\u0027foo\\u0027\"}]}"); assertThat(response.status()).isEqualTo(400); } @Test public void fail_if_request_does_not_have_required_parameter() { Request request = new TestRequest().setPath("api/foo").setParam("unknown", "Unknown"); DumbResponse response = run(request, newWs("api/foo", a -> { a.createParam("bar").setRequired(true); a.setHandler((req, resp) -> request.mandatoryParam("bar")); })); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"The \\u0027bar\\u0027 parameter is missing\"}]}"); assertThat(response.status()).isEqualTo(400); } @Test public void fail_if_request_does_not_have_required_parameter_even_if_handler_does_not_require_it() { Request request = new TestRequest().setPath("api/foo").setParam("unknown", "Unknown"); DumbResponse response = run(request, newWs("api/foo", a -> { a.createParam("bar").setRequired(true); // do not use mandatoryParam("bar") a.setHandler((req, resp) -> request.param("bar")); })); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"The \\u0027bar\\u0027 parameter is missing\"}]}"); assertThat(response.status()).isEqualTo(400); } @Test public void use_default_value_of_optional_parameter() { Request request = new TestRequest().setPath("api/print"); DumbResponse response = run(request, newWs("api/print", a -> { a.createParam("message").setDefaultValue("hello"); a.setHandler((req, resp) -> resp.stream().output().write(req.param("message").getBytes(UTF_8))); })); assertThat(response.stream().outputAsString()).isEqualTo("hello"); assertThat(response.status()).isEqualTo(200); } @Test public void use_request_parameter_on_parameter_with_default_value() { Request request = new TestRequest().setPath("api/print").setParam("message", "bar"); DumbResponse response = run(request, newWs("api/print", a -> { a.createParam("message").setDefaultValue("default_value"); a.setHandler((req, resp) -> resp.stream().output().write(req.param("message").getBytes(UTF_8))); })); assertThat(response.stream().outputAsString()).isEqualTo("bar"); assertThat(response.status()).isEqualTo(200); } @Test public void accept_parameter_value_within_defined_possible_values() { Request request = new TestRequest().setPath("api/foo").setParam("format", "json"); DumbResponse response = run(request, newWs("api/foo", a -> { a.createParam("format").setPossibleValues("json", "xml"); a.setHandler((req, resp) -> resp.stream().output().write(req.mandatoryParam("format").getBytes(UTF_8))); })); assertThat(response.stream().outputAsString()).isEqualTo("json"); assertThat(response.status()).isEqualTo(200); } @Test public void fail_if_parameter_value_is_not_in_defined_possible_values() { Request request = new TestRequest().setPath("api/foo").setParam("format", "yml"); DumbResponse response = run(request, newWs("api/foo", a -> { a.createParam("format").setPossibleValues("json", "xml"); a.setHandler((req, resp) -> resp.stream().output().write(req.mandatoryParam("format").getBytes(UTF_8))); })); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"Value of parameter \\u0027format\\u0027 (yml) must be one of: [json, xml]\"}]}"); assertThat(response.status()).isEqualTo(400); } @Test public void return_500_on_internal_error() { Request request = new TestRequest().setPath("api/foo"); DumbResponse response = run(request, newFailWs()); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"An error has occurred. Please contact your administrator\"}]}"); assertThat(response.status()).isEqualTo(500); assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON); assertThat(logTester.logs(Level.ERROR)).filteredOn(l -> l.contains("Fail to process request api/foo")).isNotEmpty(); } @Test public void return_400_on_BadRequestException_with_single_message() { Request request = new TestRequest().setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler((req, resp) -> { throw BadRequestException.create("Bad request !"); }))); assertThat(response.stream().outputAsString()).isEqualTo( "{\"errors\":[{\"msg\":\"Bad request !\"}]}"); assertThat(response.status()).isEqualTo(400); assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON); assertThat(logTester.logs(Level.ERROR)).isEmpty(); } @Test public void return_400_on_BadRequestException_with_multiple_messages() { Request request = new TestRequest().setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler((req, resp) -> { throw BadRequestException.create("one", "two", "three"); }))); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[" + "{\"msg\":\"one\"}," + "{\"msg\":\"two\"}," + "{\"msg\":\"three\"}" + "]}"); assertThat(response.status()).isEqualTo(400); assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON); assertThat(logTester.logs(Level.ERROR)).isEmpty(); } @Test public void return_400_on_BadConfigurationException_with_single_message_and_scope() { Request request = new TestRequest().setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler((req, resp) -> { throw new BadConfigurationException("PROJECT", "Bad request !"); }))); assertThat(response.stream().outputAsString()).isEqualTo( "{\"scope\":\"PROJECT\",\"errors\":[{\"msg\":\"Bad request !\"}]}"); assertThat(response.status()).isEqualTo(400); assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON); assertThat(logTester.logs(Level.ERROR)).isEmpty(); } @Test public void return_error_message_containing_character_percent() { Request request = new TestRequest().setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler((req, resp) -> { throw new IllegalArgumentException("this should not fail %s"); }))); assertThat(response.stream().outputAsString()).isEqualTo("{\"errors\":[{\"msg\":\"this should not fail %s\"}]}"); assertThat(response.status()).isEqualTo(400); assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON); } @Test public void send_response_headers() { Request request = new TestRequest().setPath("api/foo"); DumbResponse response = run(request, newWs("api/foo", a -> a.setHandler((req, resp) -> resp.setHeader("Content-Disposition", "attachment; filename=foo.zip")))); assertThat(response.getHeader("Content-Disposition")).isEqualTo("attachment; filename=foo.zip"); } @Test public void support_aborted_request_when_response_is_already_committed() { Request request = new TestRequest().setPath("api/foo"); Response response = mockServletResponse(true); run(request, response, newClientAbortWs()); // response is committed (status is already sent), so status can't be changed verify(response.stream(), never()).setStatus(anyInt()); assertThat(logTester.logs(Level.DEBUG)).contains("Request api/foo has been aborted by client"); } @Test public void support_aborted_request_when_response_is_not_committed() { Request request = new TestRequest().setPath("api/foo"); Response response = mockServletResponse(false); run(request, response, newClientAbortWs()); verify(response.stream()).setStatus(299); assertThat(logTester.logs(Level.DEBUG)).contains("Request api/foo has been aborted by client"); } @Test public void internal_error_when_response_is_already_committed() { Request request = new TestRequest().setPath("api/foo"); Response response = mockServletResponse(true); run(request, response, newFailWs()); // response is committed (status is already sent), so status can't be changed verify(response.stream(), never()).setStatus(anyInt()); assertThat(logTester.logs(Level.ERROR)).contains("Fail to process request api/foo"); } @Test public void internal_error_when_response_is_not_committed() { Request request = new TestRequest().setPath("api/foo"); Response response = mockServletResponse(false); run(request, response, newFailWs()); verify(response.stream()).setStatus(500); assertThat(logTester.logs(Level.ERROR)).contains("Fail to process request api/foo"); } @Test public void fail_when_start_in_not_called() { Request request = new TestRequest().setPath("/api/ping"); DumbResponse response = new DumbResponse(); WebServiceEngine underTest = new WebServiceEngine(new WebService[]{newPingWs(a -> { })}); underTest.execute(request, response); assertThat(logTester.logs(Level.ERROR)).contains("Fail to process request /api/ping"); } private static WebService newWs(String path, Consumer<WebService.NewAction> consumer) { return context -> { WebService.NewController controller = context.createController(substringBeforeLast(path, "/")); WebService.NewAction action = createNewDefaultAction(controller, substringAfterLast(path, "/")); action.setHandler((request, response) -> { }); consumer.accept(action); controller.done(); }; } private static WebService newPingWs(Consumer<WebService.NewAction> consumer) { return newWs("api/ping", a -> { a.setHandler((request, response) -> response.stream().output().write("pong".getBytes(UTF_8))); consumer.accept(a); }); } private static WebService newFailWs() { return newWs("api/foo", a -> a.setHandler((req, resp) -> { throw new IllegalStateException("BOOM"); })); } private static DumbResponse run(Request request, WebService... webServices) { DumbResponse response = new DumbResponse(); return (DumbResponse) run(request, response, webServices); } private static Response run(Request request, Response response, WebService... webServices) { WebServiceEngine underTest = new WebServiceEngine(webServices); underTest.start(); try { underTest.execute(request, response); return response; } finally { underTest.stop(); } } private static Response mockServletResponse(boolean committed) { Response response = mock(Response.class, Mockito.RETURNS_DEEP_STUBS); ServletResponse.ServletStream servletStream = mock(ServletResponse.ServletStream.class, Mockito.RETURNS_DEEP_STUBS); when(response.stream()).thenReturn(servletStream); HttpServletResponse httpServletResponse = mock(HttpServletResponse.class, Mockito.RETURNS_DEEP_STUBS); when(httpServletResponse.isCommitted()).thenReturn(committed); when(servletStream.response()).thenReturn(httpServletResponse); return response; } private static WebService newClientAbortWs() { return newWs("api/foo", a -> a.setHandler((req, resp) -> { throw new ClientAbortException(); })); } private static WebService.NewAction createNewDefaultAction(WebService.NewController controller, String key) { return controller .createAction(key) .setDescription("Dummy Description") .setSince("5.3") .setResponseExample(WebServiceEngineTest.class.getResource("web-service-engine-test.txt")); } }
18,031
37.284501
173
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsParameterBuilderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.google.common.collect.Sets; import java.util.Collection; import org.junit.Test; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.server.ws.WebService.NewAction; import org.sonar.api.server.ws.WebService.NewParam; import org.sonar.core.i18n.I18n; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.startsWith; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.server.ws.WsParameterBuilder.QualifierParameterContext.newQualifierParameterContext; import static org.sonarqube.ws.client.component.ComponentsWsParameters.PARAM_QUALIFIERS; import static org.sonarqube.ws.client.permission.PermissionsWsParameters.PARAM_QUALIFIER; public class WsParameterBuilderTest { private ResourceTypes resourceTypes = mock(ResourceTypes.class); private static final ResourceType Q1 = ResourceType.builder("Q1").build(); private static final ResourceType Q2 = ResourceType.builder("Q2").build(); private I18n i18n = mock(I18n.class); private NewAction newAction = mock(NewAction.class); private NewParam newParam = mock(NewParam.class); @Test public void test_createRootQualifierParameter() { when(resourceTypes.getRoots()).thenReturn(asList(Q1, Q2)); when(newAction.createParam(PARAM_QUALIFIER)).thenReturn(newParam); when(newParam.setDescription(startsWith("Project qualifier. Filter the results with the specified qualifier. " + "Possible values are:" + "<ul><li>Q1 - null</li>" + "<li>Q2 - null</li></ul>"))).thenReturn(newParam); when(newParam.setPossibleValues(any(Collection.class))).thenReturn(newParam); NewParam newParam = WsParameterBuilder .createRootQualifierParameter(newAction, newQualifierParameterContext(i18n, resourceTypes)); assertThat(newParam).isNotNull(); } @Test public void test_createRootQualifiersParameter() { when(resourceTypes.getRoots()).thenReturn(asList(Q1, Q2)); when(newAction.createParam(PARAM_QUALIFIERS)).thenReturn(newParam); when(newParam.setDescription(startsWith("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers. " + "Possible values are:" + "<ul><li>Q1 - null</li>" + "<li>Q2 - null</li></ul>"))).thenReturn(newParam); when(newParam.setPossibleValues(any(Collection.class))).thenReturn(newParam); NewParam newParam = WsParameterBuilder .createRootQualifiersParameter(newAction, newQualifierParameterContext(i18n, resourceTypes)); assertThat(newParam).isNotNull(); } @Test public void test_createDefaultTemplateQualifierParameter() { when(resourceTypes.getRoots()).thenReturn(asList(Q1, Q2)); when(newAction.createParam(PARAM_QUALIFIER)).thenReturn(newParam); when(newParam.setDescription(startsWith("Project qualifier. Filter the results with the specified qualifier. " + "Possible values are:" + "<ul><li>Q1 - null</li>" + "<li>Q2 - null</li></ul>"))).thenReturn(newParam); when(newParam.setPossibleValues(any(Collection.class))).thenReturn(newParam); NewParam newParam = WsParameterBuilder .createDefaultTemplateQualifierParameter(newAction, newQualifierParameterContext(i18n, resourceTypes)); assertThat(newParam).isNotNull(); } @Test public void test_createQualifiersParameter() { when(resourceTypes.getAll()).thenReturn(asList(Q1, Q2)); when(newAction.createParam(PARAM_QUALIFIERS)).thenReturn(newParam); when(newParam.setDescription(startsWith("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers. " + "Possible values are:" + "<ul><li>Q1 - null</li>" + "<li>Q2 - null</li></ul>"))).thenReturn(newParam); when(newParam.setPossibleValues(any(Collection.class))).thenReturn(newParam); NewParam newParam = WsParameterBuilder .createQualifiersParameter(newAction, newQualifierParameterContext(i18n, resourceTypes)); assertThat(newParam).isNotNull(); } @Test public void test_createQualifiersParameter_with_filter() { when(resourceTypes.getAll()).thenReturn(asList(Q1, Q2)); when(newAction.createParam(PARAM_QUALIFIERS)).thenReturn(newParam); when(newParam.setDescription(startsWith("Comma-separated list of component qualifiers. Filter the results with the specified qualifiers. " + "Possible values are:" + "<ul><li>Q1 - null</li></ul>"))).thenReturn(newParam); when(newParam.setPossibleValues(any(Collection.class))).thenReturn(newParam); NewParam newParam = WsParameterBuilder .createQualifiersParameter(newAction, newQualifierParameterContext(i18n, resourceTypes), Sets.newHashSet(Q1.getQualifier())); assertThat(newParam).isNotNull(); } @Test public void createQualifiersParameter_whenIgnoreIsSetToTrue_shouldNotReturnQualifier(){ when(resourceTypes.getAll()).thenReturn(asList(Q1, Q2,ResourceType.builder("Q3").setProperty("ignored", true).build())); when(newAction.createParam(PARAM_QUALIFIERS)).thenReturn(newParam); when(newParam.setPossibleValues(any(Collection.class))).thenReturn(newParam); when(newParam.setDescription(any())).thenReturn(newParam); NewParam newParam = WsParameterBuilder .createQualifiersParameter(newAction, newQualifierParameterContext(i18n, resourceTypes)); verify(newParam).setPossibleValues(Sets.newHashSet(Q1.getQualifier(), Q2.getQualifier())); } @Test public void createQualifiersParameter_whenIgnoreIsSetToFalse_shouldReturnQualifier(){ ResourceType q3Qualifier = ResourceType.builder("Q3").setProperty("ignored", false).build(); when(resourceTypes.getAll()).thenReturn(asList(Q1, Q2, q3Qualifier)); when(newAction.createParam(PARAM_QUALIFIERS)).thenReturn(newParam); when(newParam.setPossibleValues(any(Collection.class))).thenReturn(newParam); when(newParam.setDescription(any())).thenReturn(newParam); NewParam newParam = WsParameterBuilder .createQualifiersParameter(newAction, newQualifierParameterContext(i18n, resourceTypes)); verify(newParam).setPossibleValues(Sets.newHashSet(Q1.getQualifier(), Q2.getQualifier(), q3Qualifier.getQualifier())); } }
7,263
46.477124
144
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/test/java/org/sonar/server/ws/WsUtilsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.server.exceptions.BadRequestException; import org.sonarqube.ws.Issues; import org.sonarqube.ws.MediaTypes; import org.sonarqube.ws.Permissions; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class WsUtilsTest { @Rule public LogTester logger = new LogTester(); @Test public void write_json_by_default() { TestRequest request = new TestRequest(); DumbResponse response = new DumbResponse(); Issues.Issue msg = Issues.Issue.newBuilder().setKey("I1").build(); WsUtils.writeProtobuf(msg, request, response); assertThat(response.mediaType()).isEqualTo(MediaTypes.JSON); assertThat(response.outputAsString()) .startsWith("{") .contains("\"key\":\"I1\"") .endsWith("}"); } @Test public void write_protobuf() throws Exception { TestRequest request = new TestRequest(); request.setMediaType(MediaTypes.PROTOBUF); DumbResponse response = new DumbResponse(); Issues.Issue msg = Issues.Issue.newBuilder().setKey("I1").build(); WsUtils.writeProtobuf(msg, request, response); assertThat(response.mediaType()).isEqualTo(MediaTypes.PROTOBUF); assertThat(Issues.Issue.parseFrom(response.getFlushedOutput()).getKey()).isEqualTo("I1"); } @Test public void rethrow_error_as_ISE_when_error_writing_message() { TestRequest request = new TestRequest(); request.setMediaType(MediaTypes.PROTOBUF); Permissions.Permission message = Permissions.Permission.newBuilder().setName("permission-name").build(); // provoke NullPointerException assertThatThrownBy(() -> WsUtils.writeProtobuf(message, null, new DumbResponse())) .isInstanceOf(IllegalStateException.class) .hasCauseInstanceOf(NullPointerException.class) .hasMessageContaining("Error while writing protobuf message"); } @Test public void checkRequest_ok() { BadRequestException.checkRequest(true, "Missing param: %s", "foo"); // do not fail } @Test public void create_safe_external_link_tag() { assertThat(WsUtils.createHtmlExternalLink("http://google.com", "Google")) .isEqualTo("<a href=\"http://google.com\" target=\"_blank\" rel=\"noopener noreferrer\">Google</a>"); } @Test public void checkRequest_ko() { assertThatThrownBy(() -> BadRequestException.checkRequest(false, "Missing param: %s", "foo")) .isInstanceOf(BadRequestException.class) .hasMessageContaining("Missing param: foo"); } }
3,490
33.91
108
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/testFixtures/java/org/sonar/server/ws/DumbResponse.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.google.common.base.Throwables; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.annotation.CheckForNull; import org.apache.commons.io.IOUtils; import org.sonar.api.server.ws.Response; import org.sonar.api.utils.text.JsonWriter; import org.sonar.api.utils.text.XmlWriter; public class DumbResponse implements Response, TestableResponse { private InMemoryStream stream; private final ByteArrayOutputStream output = new ByteArrayOutputStream(); private Map<String, String> headers = new HashMap<>(); public class InMemoryStream implements Response.Stream { private String mediaType; private int status = 200; @Override public Response.Stream setMediaType(String s) { this.mediaType = s; return this; } @Override public Response.Stream setStatus(int i) { this.status = i; return this; } @Override public OutputStream output() { return output; } public String outputAsString() { return new String(output.toByteArray(), StandardCharsets.UTF_8); } } @Override public JsonWriter newJsonWriter() { return JsonWriter.of(new OutputStreamWriter(output, StandardCharsets.UTF_8)); } @Override public XmlWriter newXmlWriter() { return XmlWriter.of(new OutputStreamWriter(output, StandardCharsets.UTF_8)); } @Override public InMemoryStream stream() { if (stream == null) { stream = new InMemoryStream(); } return stream; } @Override public Response noContent() { stream().setStatus(HttpURLConnection.HTTP_NO_CONTENT); IOUtils.closeQuietly(output); return this; } public String outputAsString() { return new String(output.toByteArray(), StandardCharsets.UTF_8); } @CheckForNull public String mediaType() { return stream().mediaType; } public int status() { return stream().status; } @Override public Response setHeader(String name, String value) { headers.put(name, value); return this; } public Collection<String> getHeaderNames() { return headers.keySet(); } @CheckForNull public String getHeader(String name) { return headers.get(name); } public byte[] getFlushedOutput() { try { output.flush(); return output.toByteArray(); } catch (IOException e) { throw Throwables.propagate(e); } } }
3,478
24.962687
81
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/testFixtures/java/org/sonar/server/ws/TestRequest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.google.common.base.Throwables; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ListMultimap; import com.google.protobuf.GeneratedMessageV3; import java.io.BufferedReader; import java.io.InputStream; import java.io.StringReader; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import org.apache.commons.io.IOUtils; import org.sonar.api.impl.ws.PartImpl; import org.sonar.api.impl.ws.ValidatingRequest; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; import static org.sonarqube.ws.MediaTypes.PROTOBUF; public class TestRequest extends ValidatingRequest { private final ListMultimap<String, String> multiParams = ArrayListMultimap.create(); private final Map<String, String> params = new HashMap<>(); private final Map<String, String> headers = new HashMap<>(); private final Map<String, Part> parts = new HashMap<>(); private String payload = ""; private boolean payloadConsumed = false; private String method = "GET"; private String mimeType = "application/octet-stream"; private String path; @Override public BufferedReader getReader() { checkState(!payloadConsumed, "Payload already consumed"); if (payload == null) { return super.getReader(); } BufferedReader res = new BufferedReader(new StringReader(payload)); payloadConsumed = true; return res; } public TestRequest setPayload(String payload) { checkState(!payloadConsumed, "Payload already consumed"); this.payload = payload; return this; } @Override public String readParam(String key) { return params.get(key); } @Override public List<String> readMultiParam(String key) { return multiParams.get(key); } @Override public InputStream readInputStreamParam(String key) { String value = readParam(key); if (value == null) { return null; } return IOUtils.toInputStream(value); } @Override public Part readPart(String key) { return parts.get(key); } public TestRequest setPart(String key, InputStream input, String fileName) { parts.put(key, new PartImpl(input, fileName)); return this; } @Override public String method() { return method; } @Override public boolean hasParam(String key) { return params.containsKey(key) || multiParams.containsKey(key); } @Override public String getPath() { return path; } @Override public Map<String, String[]> getParams() { ArrayListMultimap<String, String> result = ArrayListMultimap.create(multiParams); params.forEach(result::put); return result.asMap().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toArray(new String[0]))); } public TestRequest setPath(String path) { this.path = path; return this; } public TestRequest setMethod(String method) { checkNotNull(method); this.method = method; return this; } @Override public String getMediaType() { return mimeType; } public TestRequest setMediaType(String type) { checkNotNull(type); this.mimeType = type; return this; } public TestRequest setParam(String key, String value) { checkNotNull(key); checkNotNull(value); this.params.put(key, value); return this; } public TestRequest setMultiParam(String key, List<String> values) { requireNonNull(key); requireNonNull(values); multiParams.putAll(key, values); return this; } @Override public Map<String, String> getHeaders() { return ImmutableMap.copyOf(headers); } @Override public Optional<String> header(String name) { return Optional.ofNullable(headers.get(name)); } public TestRequest setHeader(String name, String value) { headers.put(requireNonNull(name), requireNonNull(value)); return this; } public TestResponse execute() { try { DumbResponse response = new DumbResponse(); action().handler().handle(this, response); return new TestResponse(response); } catch (Exception e) { throw Throwables.propagate(e); } } public <T extends GeneratedMessageV3> T executeProtobuf(Class<T> protobufClass) { return setMediaType(PROTOBUF).execute().getInputObject(protobufClass); } @Override public String toString() { return path; } }
5,439
26.474747
133
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/testFixtures/java/org/sonar/server/ws/TestResponse.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.google.protobuf.GeneratedMessageV3; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.lang.reflect.Method; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import javax.annotation.CheckForNull; import org.sonar.test.JsonAssert; import static org.assertj.core.api.Assertions.assertThat; public class TestResponse { private final TestableResponse testableResponse; public TestResponse(TestableResponse dumbResponse) { this.testableResponse = dumbResponse; } public InputStream getInputStream() { return new ByteArrayInputStream(testableResponse.getFlushedOutput()); } public <T extends GeneratedMessageV3> T getInputObject(Class<T> protobufClass) { try (InputStream input = getInputStream()) { Method parseFromMethod = protobufClass.getMethod("parseFrom", InputStream.class); @SuppressWarnings("unchecked") T result = (T) parseFromMethod.invoke(null, input); return result; } catch (Exception e) { throw new IllegalStateException(e); } } public String getInput() { return new String(testableResponse.getFlushedOutput(), StandardCharsets.UTF_8); } public String getMediaType() { return testableResponse.mediaType(); } public int getStatus() { return testableResponse.status(); } @CheckForNull public String getHeader(String headerKey) { return testableResponse.getHeader(headerKey); } public void assertJson(String expectedJson) { JsonAssert.assertJson(getInput()).isSimilarTo(expectedJson); } /** * Compares JSON response with JSON file available in classpath. For example if class * is org.foo.BarTest and filename is index.json, then file must be located * at src/test/resources/org/foo/BarTest/index.json. * * @param clazz the test class * @param expectedJsonFilename name of the file containing the expected JSON */ public void assertJson(Class clazz, String expectedJsonFilename) { String path = clazz.getSimpleName() + "/" + expectedJsonFilename; URL url = clazz.getResource(path); if (url == null) { throw new IllegalStateException("Cannot find " + path); } JsonAssert.assertJson(getInput()).isSimilarTo(url); } public void assertNoContent() { assertThat(getStatus()).isEqualTo(HttpURLConnection.HTTP_NO_CONTENT); } }
3,278
32.121212
87
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/testFixtures/java/org/sonar/server/ws/TestableResponse.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import org.sonar.api.server.ws.Response; public interface TestableResponse { byte[] getFlushedOutput(); Response.Stream stream(); String getHeader(String headerKey); int status(); String mediaType(); }
1,091
29.333333
75
java
sonarqube
sonarqube-master/server/sonar-webserver-ws/src/testFixtures/java/org/sonar/server/ws/WsActionTester.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.ws; import com.google.common.collect.Iterables; import org.sonar.api.server.ws.WebService; public class WsActionTester { public static final String CONTROLLER_KEY = "test"; protected final WebService.Action action; public WsActionTester(WsAction wsAction) { WebService.Context context = new WebService.Context(); WebService.NewController newController = context.createController(CONTROLLER_KEY); wsAction.define(newController); newController.done(); action = Iterables.get(context.controller(CONTROLLER_KEY).actions(), 0); } public WebService.Action getDef() { return action; } public TestRequest newRequest() { TestRequest request = new TestRequest(); request.setAction(action); return request; } }
1,626
32.895833
86
java
sonarqube
sonarqube-master/server/sonar-webserver/src/it/java/org/sonar/server/platform/web/SonarLintConnectionFilterIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletRequest; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.web.FilterChain; import org.sonar.db.DbTester; import org.sonar.db.user.UserDto; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.user.ServerUserSession; import org.sonar.server.user.ThreadLocalUserSession; import static org.assertj.core.api.Assertions.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 SonarLintConnectionFilterIT { private static final String LOGIN = "user1"; private final TestSystem2 system2 = new TestSystem2(); @Rule public DbTester dbTester = DbTester.create(system2); @Test public void update() throws IOException { system2.setNow(10_000_000L); addUser(LOGIN, 1_000_000L); runFilter(LOGIN, "SonarLint for IntelliJ"); assertThat(getLastUpdate(LOGIN)).isEqualTo(10_000_000L); } @Test public void update_first_time() throws IOException { system2.setNow(10_000_000L); addUser(LOGIN, null); runFilter(LOGIN, "SonarLint for IntelliJ"); assertThat(getLastUpdate(LOGIN)).isEqualTo(10_000_000L); } @Test public void only_applies_to_api() { SonarLintConnectionFilter underTest = new SonarLintConnectionFilter(dbTester.getDbClient(), mock(ThreadLocalUserSession.class), system2); assertThat(underTest.doGetPattern().matches("/api/test")).isTrue(); assertThat(underTest.doGetPattern().matches("/test")).isFalse(); } @Test public void do_nothing_if_no_sonarlint_agent() throws IOException { system2.setNow(10_000L); addUser(LOGIN, 1_000L); runFilter(LOGIN, "unknown"); runFilter(LOGIN, null); assertThat(getLastUpdate(LOGIN)).isEqualTo(1_000L); } @Test public void do_nothing_if_not_logged_in() throws IOException { system2.setNow(10_000_000L); addUser("invalid", 1_000_000L); runFilter(LOGIN, "SonarLint for IntelliJ"); assertThat(getLastUpdate("invalid")).isEqualTo(1_000_000L); } @Test public void dont_fail_if_no_user_set() throws IOException { SonarLintConnectionFilter underTest = new SonarLintConnectionFilter(dbTester.getDbClient(), new ThreadLocalUserSession(), system2); HttpServletRequest httpRequest = mock(HttpServletRequest.class); when(httpRequest.getHeader("User-Agent")).thenReturn("sonarlint"); FilterChain chain = mock(FilterChain.class); underTest.doFilter(new JavaxHttpRequest(httpRequest), mock(HttpResponse.class), chain); verify(chain).doFilter(any(), any()); } @Test public void only_update_if_not_updated_within_1h() throws IOException { system2.setNow(2_000_000L); addUser(LOGIN, 1_000_000L); runFilter(LOGIN, "SonarLint for IntelliJ"); assertThat(getLastUpdate(LOGIN)).isEqualTo(1_000_000L); } private void addUser(String login, @Nullable Long lastUpdate) { dbTester.users().insertUser(u -> u.setLogin(login).setLastSonarlintConnectionDate(lastUpdate)); } @CheckForNull private Long getLastUpdate(String login) { return dbTester.getDbClient().userDao().selectByLogin(dbTester.getSession(), login).getLastSonarlintConnectionDate(); } private void runFilter(String loggedInUser, @Nullable String agent) throws IOException { UserDto user = dbTester.getDbClient().userDao().selectByLogin(dbTester.getSession(), loggedInUser); ThreadLocalUserSession session = new ThreadLocalUserSession(); session.set(new ServerUserSession(dbTester.getDbClient(), user)); SonarLintConnectionFilter underTest = new SonarLintConnectionFilter(dbTester.getDbClient(), session, system2); HttpServletRequest httpRequest = mock(HttpServletRequest.class); when(httpRequest.getHeader("User-Agent")).thenReturn(agent); FilterChain chain = mock(FilterChain.class); underTest.doFilter(new JavaxHttpRequest(httpRequest), mock(HttpResponse.class), chain); verify(chain).doFilter(any(), any()); } }
5,104
36.814815
141
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/EmbeddedTomcat.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import com.google.common.base.Throwables; import java.io.File; import java.util.concurrent.CountDownLatch; import org.apache.catalina.LifecycleException; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; import org.slf4j.LoggerFactory; import org.sonar.process.Props; import static org.sonar.core.util.FileUtils.deleteQuietly; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; class EmbeddedTomcat { private final Props props; private Tomcat tomcat = null; private volatile StandardContext webappContext; private final CountDownLatch stopLatch = new CountDownLatch(1); EmbeddedTomcat(Props props) { this.props = props; } void start() { // '%2F' (slash /) and '%5C' (backslash \) are permitted as path delimiters in URLs System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true"); System.setProperty("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE", "true"); // prevent Tomcat from shutting down our logging when stopping System.setProperty("logbackDisableServletContainerInitializer", "true"); tomcat = new Tomcat(); // Initialize directories String basedir = tomcatBasedir().getAbsolutePath(); tomcat.setBaseDir(basedir); tomcat.getHost().setAppBase(basedir); tomcat.getHost().setAutoDeploy(false); tomcat.getHost().setCreateDirs(false); tomcat.getHost().setDeployOnStartup(true); new TomcatErrorHandling().configure(tomcat); new TomcatAccessLog().configure(tomcat, props); TomcatConnectors.configure(tomcat, props); webappContext = new TomcatContexts().configure(tomcat, props); try { // let Tomcat temporarily log errors at start up - for example, port in use Logger logger = (Logger) LoggerFactory.getLogger("org.apache.catalina.core.StandardService"); logger.setLevel(Level.ERROR); tomcat.start(); logger.setLevel(Level.OFF); new TomcatStartupLogs(LoggerFactory.getLogger(getClass())).log(tomcat); } catch (LifecycleException e) { LoggerFactory.getLogger(EmbeddedTomcat.class).error("Fail to start web server", e); Throwables.propagate(e); } } Status getStatus() { if (webappContext == null) { return Status.DOWN; } return switch (webappContext.getState()) { case NEW, INITIALIZING, INITIALIZED, STARTING_PREP, STARTING -> Status.DOWN; case STARTED -> Status.UP; default -> // problem, stopped or failed Status.FAILED; }; } public enum Status { DOWN, UP, FAILED } private File tomcatBasedir() { return new File(props.value(PATH_TEMP.getKey()), "tc"); } void terminate() { try { if (tomcat.getServer().getState().isAvailable()) { try { tomcat.stop(); tomcat.destroy(); } catch (Exception e) { LoggerFactory.getLogger(EmbeddedTomcat.class).warn("Failed to stop web server", e); } } deleteQuietly(tomcatBasedir()); } finally { stopLatch.countDown(); } } void awaitTermination() { try { // calling tomcat.getServer().await() might block forever if stop fails for whatever reason stopLatch.await(); } catch (InterruptedException e) { // quit } } }
4,252
32.753968
99
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/NullJarScanner.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.apache.tomcat.JarScanFilter; import org.apache.tomcat.JarScanType; import org.apache.tomcat.JarScanner; import org.apache.tomcat.JarScannerCallback; import javax.servlet.ServletContext; /** * Disable taglib and web-fragment.xml scanning of Tomcat. Should speed up startup. */ class NullJarScanner implements JarScanner { @Override public void scan(JarScanType jarScanType, ServletContext servletContext, JarScannerCallback jarScannerCallback) { // doing nothing is fast! } @Override public JarScanFilter getJarScanFilter() { return null; } @Override public void setJarScanFilter(JarScanFilter jarScanFilter) { // no need to filter } }
1,558
30.18
115
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/ProgrammaticLogbackValve.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 ch.qos.logback.access.tomcat.LogbackValve; import ch.qos.logback.core.util.ExecutorServiceUtil; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.commons.lang.reflect.FieldUtils; /** * Implementation of {@link ch.qos.logback.access.tomcat.LogbackValve} that does not * rely on the required file logback-access.xml. It allows to be configured * programmatically. */ public class ProgrammaticLogbackValve extends LogbackValve { @Override public synchronized void startInternal() throws LifecycleException { try { // direct coupling with LogbackValve implementation FieldUtils.writeField(this, "scheduledExecutorService", ExecutorServiceUtil.newScheduledExecutorService(), true); FieldUtils.writeField(this, "started", true, true); setState(LifecycleState.STARTING); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } } }
1,836
38.085106
119
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/SecureErrorReportValve.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.IOException; import javax.servlet.ServletException; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.valves.ErrorReportValve; import org.sonar.server.platform.web.SecurityServletFilter; /** * Extending the ErrorReportValve to add security HTTP headers in all responses. */ public class SecureErrorReportValve extends ErrorReportValve { @Override public void invoke(Request request, Response response) throws IOException, ServletException { SecurityServletFilter.addSecurityHeaders(request, response); super.invoke(request, response); } }
1,516
36.925
95
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/TomcatAccessLog.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 ch.qos.logback.access.PatternLayoutEncoder; import ch.qos.logback.core.FileAppender; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.catalina.startup.Tomcat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.process.logging.LogbackHelper; import org.sonar.process.Props; class TomcatAccessLog { private static final String PROPERTY_ENABLE = "sonar.web.accessLogs.enable"; private static final String PROPERTY_PATTERN = "sonar.web.accessLogs.pattern"; private static final String DEFAULT_SQ_ACCESS_LOG_PATTERN = "%h %l %u [%t] \"%r\" %s %b \"%i{Referer}\" \"%i{User-Agent}\" \"%reqAttribute{ID}\""; void configure(Tomcat tomcat, Props props) { tomcat.setSilent(true); tomcat.getService().addLifecycleListener(new LifecycleLogger(LoggerFactory.getLogger(TomcatAccessLog.class))); configureLogbackAccess(tomcat, props); } private static void configureLogbackAccess(Tomcat tomcat, Props props) { if (props.valueAsBoolean(PROPERTY_ENABLE, true)) { ProgrammaticLogbackValve valve = new ProgrammaticLogbackValve(); LogbackHelper helper = new LogbackHelper(); LogbackHelper.RollingPolicy policy = helper.createRollingPolicy(valve, props, "access"); FileAppender appender = policy.createAppender("ACCESS_LOG"); PatternLayoutEncoder fileEncoder = new PatternLayoutEncoder(); fileEncoder.setContext(valve); fileEncoder.setPattern(props.value(PROPERTY_PATTERN, DEFAULT_SQ_ACCESS_LOG_PATTERN)); fileEncoder.start(); appender.setEncoder(fileEncoder); appender.start(); valve.addAppender(appender); valve.setAsyncSupported(true); tomcat.getHost().getPipeline().addValve(valve); } } static class LifecycleLogger implements LifecycleListener { private Logger logger; LifecycleLogger(Logger logger) { this.logger = logger; } @Override public void lifecycleEvent(LifecycleEvent event) { if ("after_start".equals(event.getType())) { logger.debug("Tomcat is started"); } else if ("after_destroy".equals(event.getType())) { logger.debug("Tomcat is stopped"); } } } }
3,098
37.259259
148
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/TomcatConnectors.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 javax.annotation.Nullable; import org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import org.sonar.process.Props; import static java.lang.String.format; import static org.sonar.process.ProcessProperties.Property.WEB_HOST; import static org.sonar.process.ProcessProperties.Property.WEB_HTTP_ACCEPT_COUNT; import static org.sonar.process.ProcessProperties.Property.WEB_HTTP_MAX_THREADS; import static org.sonar.process.ProcessProperties.Property.WEB_HTTP_MIN_THREADS; import static org.sonar.process.ProcessProperties.Property.WEB_HTTP_KEEP_ALIVE_TIMEOUT; /** * Configuration of Tomcat connectors */ class TomcatConnectors { static final String HTTP_PROTOCOL = "HTTP/1.1"; static final int MAX_HTTP_HEADER_SIZE_BYTES = 48 * 1024; private static final int MAX_POST_SIZE = -1; private TomcatConnectors() { // only static stuff } static void configure(Tomcat tomcat, Props props) { Connector httpConnector = newHttpConnector(props); tomcat.getService().addConnector(httpConnector); } private static Connector newHttpConnector(Props props) { // Not named "sonar.web.http.port" to keep backward-compatibility int port = props.valueAsInt("sonar.web.port", 9000); if (port < 0) { throw new IllegalStateException(format("HTTP port '%s' is invalid", port)); } Connector connector = new Connector(HTTP_PROTOCOL); connector.setURIEncoding("UTF-8"); connector.setProperty("address", props.value(WEB_HOST.getKey(), "0.0.0.0")); connector.setProperty("socket.soReuseAddress", "true"); // see https://tomcat.apache.org/tomcat-8.5-doc/config/http.html connector.setProperty("relaxedQueryChars", "\"<>[\\]^`{|}"); configurePool(props, connector); configureCompression(connector); configureMaxHttpHeaderSize(connector); connector.setPort(port); connector.setMaxPostSize(MAX_POST_SIZE); return connector; } /** * HTTP header must be at least 48kb to accommodate the authentication token used for * negotiate protocol of windows authentication. */ private static void configureMaxHttpHeaderSize(Connector connector) { setConnectorAttribute(connector, "maxHttpHeaderSize", MAX_HTTP_HEADER_SIZE_BYTES); } private static void configurePool(Props props, Connector connector) { connector.setProperty("acceptorThreadCount", String.valueOf(2)); connector.setProperty("minSpareThreads", String.valueOf(props.valueAsInt(WEB_HTTP_MIN_THREADS.getKey(), 5))); connector.setProperty("maxThreads", String.valueOf(props.valueAsInt(WEB_HTTP_MAX_THREADS.getKey(), 50))); connector.setProperty("acceptCount", String.valueOf(props.valueAsInt(WEB_HTTP_ACCEPT_COUNT.getKey(), 25))); connector.setProperty("keepAliveTimeout", String.valueOf(props.valueAsInt(WEB_HTTP_KEEP_ALIVE_TIMEOUT.getKey(), 60000))); } private static void configureCompression(Connector connector) { connector.setProperty("compression", "on"); connector.setProperty("compressionMinSize", "1024"); connector.setProperty("compressibleMimeType", "text/html,text/xml,text/plain,text/css,application/json,application/javascript,text/javascript"); } private static void setConnectorAttribute(Connector c, String key, @Nullable Object value) { if (value != null) { c.setAttribute(key, value); } } }
4,228
40.871287
148
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/TomcatContexts.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 com.google.common.annotations.VisibleForTesting; import java.io.File; import java.io.IOException; import java.util.Map; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; import org.apache.commons.io.FileUtils; import org.sonar.api.utils.MessageException; import org.sonar.process.Props; import static java.lang.String.format; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.WEB_CONTEXT; /** * Configures Tomcat contexts: * <ul> * <li>/deploy delivers the plugins required by analyzers. It maps directory ${sonar.path.data}/web/deploy.</li> * <li>/ is the regular webapp</li> * </ul> */ public class TomcatContexts { private static final String WEB_DEPLOY_PATH_RELATIVE_TO_DATA_DIR = "web/deploy"; private final Fs fs; public TomcatContexts() { this.fs = new Fs(); } @VisibleForTesting TomcatContexts(Fs fs) { this.fs = fs; } public StandardContext configure(Tomcat tomcat, Props props) { addStaticDir(tomcat, getContextPath(props) + "/deploy", new File(props.nonNullValueAsFile(PATH_DATA.getKey()), WEB_DEPLOY_PATH_RELATIVE_TO_DATA_DIR)); StandardContext webapp = addContext(tomcat, getContextPath(props), webappDir(props)); for (Map.Entry<Object, Object> entry : props.rawProperties().entrySet()) { String key = entry.getKey().toString(); webapp.addParameter(key, entry.getValue().toString()); } return webapp; } static String getContextPath(Props props) { String context = props.value(WEB_CONTEXT.getKey(), ""); if ("/".equals(context)) { context = ""; } else if (!"".equals(context) && context != null && !context.startsWith("/")) { throw MessageException.of(format("Value of '%s' must start with a forward slash: '%s'", WEB_CONTEXT.getKey(), context)); } return context; } @VisibleForTesting StandardContext addStaticDir(Tomcat tomcat, String contextPath, File dir) { try { fs.createOrCleanupDir(dir); } catch (IOException e) { throw new IllegalStateException(format("Fail to create or clean-up directory %s", dir.getAbsolutePath()), e); } return addContext(tomcat, contextPath, dir); } private static StandardContext addContext(Tomcat tomcat, String contextPath, File dir) { try { StandardContext context = (StandardContext) tomcat.addWebapp(contextPath, dir.getAbsolutePath()); context.setClearReferencesHttpClientKeepAliveThread(false); context.setClearReferencesStopThreads(false); context.setClearReferencesStopTimerThreads(false); context.setClearReferencesStopTimerThreads(false); context.setAntiResourceLocking(false); context.setReloadable(false); context.setUseHttpOnly(true); context.setTldValidation(false); context.setXmlValidation(false); context.setXmlNamespaceAware(false); context.setUseNaming(false); context.setDelegate(true); context.setJarScanner(new NullJarScanner()); context.setAllowCasualMultipartParsing(true); context.setCookies(false); // disable JSP and WebSocket support context.setContainerSciFilter("org.apache.tomcat.websocket.server.WsSci|org.apache.jasper.servlet.JasperInitializer"); return context; } catch (Exception e) { throw new IllegalStateException("Fail to configure webapp from " + dir, e); } } private static File webappDir(Props props) { return new File(props.value(PATH_HOME.getKey()), "web"); } static class Fs { void createOrCleanupDir(File dir) throws IOException { FileUtils.forceMkdir(dir); org.sonar.core.util.FileUtils.cleanDirectory(dir); } } }
4,698
36
154
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/TomcatErrorHandling.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.apache.catalina.startup.Tomcat; import org.apache.catalina.valves.ErrorReportValve; public class TomcatErrorHandling { void configure(Tomcat tomcat) { // This needs to be an instance of ErrrorReportValue, otherwise // Tomcat 9's StandardHost will add another ErrorReportValve with the default values ErrorReportValve valve = new ErrorReportValve(); valve.setShowServerInfo(false); valve.setShowReport(false); tomcat.getHost().getPipeline().addValve(valve); } }
1,375
38.314286
88
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/TomcatStartupLogs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; class TomcatStartupLogs { private final Logger log; TomcatStartupLogs(Logger log) { this.log = log; } void log(Tomcat tomcat) { Connector[] connectors = tomcat.getService().findConnectors(); for (Connector connector : connectors) { if (StringUtils.equalsIgnoreCase(connector.getScheme(), "http")) { logHttp(connector); } else { throw new IllegalArgumentException("Unsupported connector: " + connector); } } } private void logHttp(Connector connector) { log.info(String.format("HTTP connector enabled on port %d", connector.getPort())); } }
1,648
31.333333
86
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/WebSecurityManager.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.sonar.process.PluginFileWriteRule; import org.sonar.process.PluginSecurityManager; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; public class WebSecurityManager { private final PluginSecurityManager pluginSecurityManager; private final Props props; private boolean applied; public WebSecurityManager(PluginSecurityManager pluginSecurityManager, Props props) { this.pluginSecurityManager = pluginSecurityManager; this.props = props; } public void apply() { if (applied) { throw new IllegalStateException("can't apply twice"); } applied = true; PluginFileWriteRule writeRule = new PluginFileWriteRule( props.nonNullValueAsFile(ProcessProperties.Property.PATH_HOME.getKey()).toPath(), props.nonNullValueAsFile(ProcessProperties.Property.PATH_TEMP.getKey()).toPath()); pluginSecurityManager.restrictPlugins(writeRule); } }
1,799
35
88
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/WebServer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 com.google.common.collect.ImmutableMap; import java.io.File; import org.slf4j.LoggerFactory; import org.sonar.process.MinimumViableSystem; import org.sonar.process.Monitored; import org.sonar.process.PluginSecurityManager; import org.sonar.process.ProcessEntryPoint; import org.sonar.process.ProcessId; import org.sonar.process.Props; import org.sonar.process.sharedmemoryfile.DefaultProcessCommands; import static org.sonar.process.ProcessId.WEB_SERVER; public class WebServer implements Monitored { public static final String PROPERTY_SHARED_PATH = "process.sharedDir"; private final File sharedDir; private final EmbeddedTomcat tomcat; WebServer(Props props) { new MinimumViableSystem() .checkWritableTempDir() .checkRequiredJavaOptions(ImmutableMap.of("file.encoding", "UTF-8")); this.sharedDir = getSharedDir(props); this.tomcat = new EmbeddedTomcat(props); } private static File getSharedDir(Props props) { return props.nonNullValueAsFile(PROPERTY_SHARED_PATH); } @Override public void start() { tomcat.start(); } @Override public Status getStatus() { switch (tomcat.getStatus()) { case DOWN: return Status.DOWN; case UP: return isOperational() ? Status.OPERATIONAL : Status.UP; case FAILED: default: return Status.FAILED; } } private boolean isOperational() { try (DefaultProcessCommands processCommands = DefaultProcessCommands.secondary(sharedDir, ProcessId.WEB_SERVER.getIpcIndex())) { return processCommands.isOperational(); } } @Override public void stop() { // hard stop is as graceful as stop for the WebServer hardStop(); LoggerFactory.getLogger(WebServer.class).info("{} stopped", WEB_SERVER.getHumanReadableName()); } @Override public void hardStop() { tomcat.terminate(); } @Override public void awaitStop() { tomcat.awaitTermination(); } /** * Can't be started as is. Needs to be bootstrapped by sonar-application */ public static void main(String[] args) { ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args); Props props = entryPoint.getProps(); new WebServerProcessLogging().configure(props); new WebSecurityManager(new PluginSecurityManager(), props).apply(); WebServer server = new WebServer(props); entryPoint.launch(server); } }
3,277
29.635514
132
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/app/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.app; import javax.annotation.ParametersAreNonnullByDefault;
960
39.041667
75
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/PlatformImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; import javax.annotation.Nullable; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; 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.platform.ExtensionContainer; import org.sonar.core.platform.SpringComponentContainer; import org.sonar.server.app.ProcessCommandWrapper; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import org.sonar.server.platform.platformlevel.PlatformLevel; import org.sonar.server.platform.platformlevel.PlatformLevel1; import org.sonar.server.platform.platformlevel.PlatformLevel2; import org.sonar.server.platform.platformlevel.PlatformLevel3; import org.sonar.server.platform.platformlevel.PlatformLevel4; import org.sonar.server.platform.platformlevel.PlatformLevelSafeMode; import org.sonar.server.platform.platformlevel.PlatformLevelStartup; import org.sonar.server.platform.web.ApiV2Servlet; import static org.sonar.process.ProcessId.WEB_SERVER; /** * @since 2.2 */ public class PlatformImpl implements Platform { private static final Logger LOGGER = Loggers.get(Platform.class); private static final PlatformImpl INSTANCE = new PlatformImpl(); private AutoStarter autoStarter = null; private Properties properties = null; private ServletContext servletContext = null; private PlatformLevel level1 = null; private PlatformLevel level2 = null; private PlatformLevel levelSafeMode = null; private PlatformLevel level3 = null; private PlatformLevel level4 = null; private PlatformLevel currentLevel = null; private boolean dbConnected = false; private boolean started = false; private final List<Object> level4AddedComponents = new ArrayList<>(); private final Profiler profiler = Profiler.createIfTrace(Loggers.get(PlatformImpl.class)); private ApiV2Servlet servlet = null; public static PlatformImpl getInstance() { return INSTANCE; } public void init(Properties properties, ServletContext servletContext) { this.properties = properties; this.servletContext = servletContext; if (!dbConnected) { startLevel1Container(); startLevel2Container(); currentLevel = level2; dbConnected = true; } } @Override public void doStart() { if (started && !isInSafeMode()) { return; } boolean dbRequiredMigration = dbRequiresMigration(); startSafeModeContainer(); currentLevel = levelSafeMode; if (!started) { registerSpringMvcServlet(); this.servlet.initDispatcherSafeMode(levelSafeMode); } started = true; // if AutoDbMigration kicked in or no DB migration was required, startup can be resumed in another thread if (dbRequiresMigration()) { LOGGER.info("Database needs to be migrated. Please refer to https://docs.sonarqube.org/latest/setup/upgrading"); } else { this.autoStarter = createAutoStarter(); this.autoStarter.execute(new AutoStarterRunnable(autoStarter) { @Override public void doRun() { if (dbRequiredMigration) { LOGGER.info("Database has been automatically updated"); } runIfNotAborted(PlatformImpl.this::startLevel34Containers); runIfNotAborted(()->servlet.initDispatcherLevel4(level4)); runIfNotAborted(PlatformImpl.this::executeStartupTasks); // switch current container last to avoid giving access to a partially initialized container runIfNotAborted(() -> { currentLevel = level4; LOGGER.info("{} is operational", WEB_SERVER.getHumanReadableName()); }); // stop safemode container if it existed runIfNotAborted(PlatformImpl.this::stopSafeModeContainer); } }); } } private void registerSpringMvcServlet() { servlet = new ApiV2Servlet(); ServletRegistration.Dynamic app = this.servletContext.addServlet("app", servlet); app.addMapping("/api/v2/*"); app.setLoadOnStartup(1); } private AutoStarter createAutoStarter() { ProcessCommandWrapper processCommandWrapper = getContainer().getComponentByType(ProcessCommandWrapper.class); return new AsynchronousAutoStarter(processCommandWrapper); } private boolean dbRequiresMigration() { return getDatabaseStatus() != DatabaseVersion.Status.UP_TO_DATE; } public boolean isStarted() { return status() == Status.UP; } public boolean isInSafeMode() { return status() == Status.SAFEMODE; } @Override public Status status() { if (!started) { return Status.BOOTING; } PlatformLevel current = this.currentLevel; PlatformLevel levelSafe = this.levelSafeMode; if (levelSafe != null && current == levelSafe) { return isRunning(this.autoStarter) ? Status.STARTING : Status.SAFEMODE; } if (current == level4) { return Status.UP; } return Status.BOOTING; } private static boolean isRunning(@Nullable AutoStarter autoStarter) { return autoStarter != null && autoStarter.isRunning(); } /** * Starts level 1 */ private void startLevel1Container() { level1 = start(new PlatformLevel1(this, properties, servletContext)); } /** * Starts level 2 */ private void startLevel2Container() { level2 = start(new PlatformLevel2(level1)); } /** * Starts level 3 and 4 */ private void startLevel34Containers() { level3 = start(new PlatformLevel3(level2)); level4 = start(new PlatformLevel4(level3, level4AddedComponents)); } private void executeStartupTasks() { new PlatformLevelStartup(level4) .configure() .start() .stop(); } private void startSafeModeContainer() { levelSafeMode = start(new PlatformLevelSafeMode(level2)); } private PlatformLevel start(PlatformLevel platformLevel) { profiler.start(); platformLevel.configure(); profiler.stopTrace(String.format("%s configured", platformLevel.getName())); profiler.start(); platformLevel.start(); profiler.stopTrace(String.format("%s started", platformLevel.getName())); return platformLevel; } /** * Stops level 1 */ private void stopLevel1Container() { if (level1 != null) { level1.stop(); level1 = null; } } /** * Stops level 2, 3 and 4 containers cleanly if they exists. * Call this method before {@link #startLevel1Container()} to avoid duplicate attempt to stop safemode container * components (since calling stop on a container calls stop on its children too, see * {@link SpringComponentContainer#stopComponents()}). */ private void stopLevel234Containers() { if (level2 != null) { level2.stop(); level2 = null; level3 = null; level4 = null; } } /** * Stops safemode container cleanly if it exists. * Call this method before {@link #stopLevel234Containers()} and {@link #stopLevel1Container()} to avoid duplicate * attempt to stop safemode container components (since calling stop on a container calls stops on its children too, * see {@link SpringComponentContainer#stopComponents()}). */ private void stopSafeModeContainer() { if (levelSafeMode != null) { levelSafeMode.stop(); levelSafeMode = null; } } private DatabaseVersion.Status getDatabaseStatus() { DatabaseVersion version = getContainer().getComponentByType(DatabaseVersion.class); return version.getStatus(); } public void doStop() { try { stopAutoStarter(); stopSafeModeContainer(); stopLevel234Containers(); stopLevel1Container(); currentLevel = null; dbConnected = false; started = false; } catch (Exception e) { LOGGER.error("Fail to stop server - ignored", e); } } private void stopAutoStarter() { if (autoStarter != null) { autoStarter.abort(); autoStarter = null; } } public void addComponents(Collection<?> components) { level4AddedComponents.addAll(components); } @Override public ExtensionContainer getContainer() { return currentLevel.getContainer(); } public interface AutoStarter { /** * Let the autostarted execute the provided code. */ void execute(Runnable startCode); /** * This method is called by executed start code (see {@link #execute(Runnable)} has finished with a failure. */ void failure(Throwable t); /** * This method is called by executed start code (see {@link #execute(Runnable)} has finished successfully. */ void success(); /** * Indicates whether the AutoStarter is running. */ boolean isRunning(); /** * Requests the startcode (ie. the argument of {@link #execute(Runnable)}) aborts its processing (if it supports it). */ void abort(); /** * Indicates whether {@link #abort()} was invoked. * <p> * This method can be used by the start code to check whether it should proceed running or stop. * </p> */ boolean isAborting(); /** * Called when abortion is complete. * <p> * Start code support abortion should call this method once is done processing and if it stopped on abortion. * </p> */ void aborted(); } private abstract static class AutoStarterRunnable implements Runnable { private final AutoStarter autoStarter; AutoStarterRunnable(AutoStarter autoStarter) { this.autoStarter = autoStarter; } @Override public void run() { try { doRun(); } catch (Throwable t) { autoStarter.failure(t); } finally { if (autoStarter.isAborting()) { autoStarter.aborted(); } else { autoStarter.success(); } } } abstract void doRun(); void runIfNotAborted(Runnable r) { if (!autoStarter.isAborting()) { r.run(); } } } private static final class AsynchronousAutoStarter implements AutoStarter { private final ProcessCommandWrapper processCommandWrapper; private boolean running = true; private boolean abort = false; private AsynchronousAutoStarter(ProcessCommandWrapper processCommandWrapper) { this.processCommandWrapper = processCommandWrapper; } @Override public void execute(Runnable startCode) { new Thread(startCode, "SQ starter").start(); } @Override public void failure(Throwable t) { LOGGER.error("Background initialization failed. Stopping SonarQube", t); processCommandWrapper.requestHardStop(); this.running = false; } @Override public void success() { LOGGER.debug("Background initialization of SonarQube done"); this.running = false; } @Override public void aborted() { LOGGER.debug("Background initialization of SonarQube aborted"); this.running = false; } @Override public boolean isRunning() { return running; } @Override public void abort() { this.abort = true; } @Override public boolean isAborting() { return this.abort; } } }
12,142
28.189904
121
java
sonarqube
sonarqube-master/server/sonar-webserver/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/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import java.util.Collection; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.core.platform.SpringComponentContainer; import org.sonar.server.platform.NodeInformation; import static com.google.common.base.Preconditions.checkNotNull; public abstract class PlatformLevel { private final String name; @Nullable protected final PlatformLevel parent; private final SpringComponentContainer container; private AddIfStartupLeader addIfStartupLeader; private AddIfCluster addIfCluster; private AddIfStandalone addIfStandalone; protected PlatformLevel(String name) { this.name = name; this.parent = null; this.container = createContainer(null); } protected PlatformLevel(String name, PlatformLevel parent) { this.name = checkNotNull(name); this.parent = checkNotNull(parent); this.container = createContainer(parent.getContainer()); } public SpringComponentContainer getContainer() { return container; } public String getName() { return name; } /** * Intended to be override by subclasses if needed */ protected SpringComponentContainer createContainer(@Nullable SpringComponentContainer parent) { if (parent == null) { return new SpringComponentContainer(); } return parent.createChild(); } public PlatformLevel configure() { configureLevel(); return this; } protected abstract void configureLevel(); /** * Intended to be override by subclasses if needed */ public PlatformLevel start() { container.startComponents(); return this; } /** * Intended to be override by subclasses if needed */ public PlatformLevel stop() { container.stopComponents(); return this; } protected <T> T get(Class<T> tClass) { return container.getComponentByType(tClass); } protected <T> Optional<T> getOptional(Class<T> tClass) { return container.getOptionalComponentByType(tClass); } protected void add(Object... objects) { for (Object object : objects) { if (object != null) { container.add(object); } } } /** * Add a component to container only if the web server is startup leader. * * @throws IllegalStateException if called from PlatformLevel1, when cluster settings are not loaded */ AddIfStartupLeader addIfStartupLeader(Object... objects) { if (addIfStartupLeader == null) { this.addIfStartupLeader = new AddIfStartupLeader(getWebServer().isStartupLeader()); } addIfStartupLeader.ifAdd(objects); return addIfStartupLeader; } /** * Add a component to container only if clustering is enabled. * * @throws IllegalStateException if called from PlatformLevel1, when cluster settings are not loaded */ AddIfCluster addIfCluster(Object... objects) { if (addIfCluster == null) { addIfCluster = new AddIfCluster(!getWebServer().isStandalone()); } addIfCluster.ifAdd(objects); return addIfCluster; } /** * Add a component to container only if this is a standalone instance, without clustering. * * @throws IllegalStateException if called from PlatformLevel1, when cluster settings are not loaded */ AddIfStandalone addIfStandalone(Object... objects) { if (addIfStandalone == null) { addIfStandalone = new AddIfStandalone(getWebServer().isStandalone()); } addIfStandalone.ifAdd(objects); return addIfStandalone; } protected NodeInformation getWebServer() { return Optional.ofNullable(parent) .flatMap(p -> p.getOptional(NodeInformation.class)) .or(() -> getOptional(NodeInformation.class)) .orElseThrow(() -> new IllegalStateException("WebServer not available in the container")); } protected abstract class AddIf { private final boolean condition; protected AddIf(boolean condition) { this.condition = condition; } public void ifAdd(Object... objects) { if (condition) { PlatformLevel.this.add(objects); } } public void otherwiseAdd(Object... objects) { if (!condition) { PlatformLevel.this.add(objects); } } } public final class AddIfStartupLeader extends AddIf { private AddIfStartupLeader(boolean condition) { super(condition); } } public final class AddIfCluster extends AddIf { private AddIfCluster(boolean condition) { super(condition); } } public final class AddIfStandalone extends AddIf { private AddIfStandalone(boolean condition) { super(condition); } } protected void addAll(Collection<?> objects) { add(objects.toArray(new Object[objects.size()])); } }
5,561
27.233503
102
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel1.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import java.time.Clock; import java.util.Properties; import org.sonar.api.SonarEdition; import org.sonar.api.SonarQubeSide; import org.sonar.api.internal.MetadataLoader; import org.sonar.api.internal.SonarRuntimeImpl; import org.sonar.api.utils.System2; import org.sonar.api.utils.Version; import org.sonar.core.config.CorePropertyDefinitions; import org.sonar.core.extension.CoreExtensionRepositoryImpl; import org.sonar.core.extension.CoreExtensionsLoader; import org.sonar.core.platform.SonarQubeVersion; import org.sonar.core.util.UuidFactoryImpl; import org.sonar.db.DBSessionsImpl; import org.sonar.db.DaoModule; import org.sonar.db.DbClient; import org.sonar.db.DefaultDatabase; import org.sonar.db.MyBatis; import org.sonar.db.StartMyBatis; import org.sonar.db.audit.AuditPersister; import org.sonar.db.audit.NoOpAuditPersister; import org.sonar.db.purge.PurgeProfiler; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.logging.LogbackHelper; import org.sonar.server.app.ProcessCommandWrapperImpl; import org.sonar.server.app.RestartFlagHolderImpl; import org.sonar.server.app.WebServerProcessLogging; import org.sonar.server.config.ConfigurationProvider; import org.sonar.server.es.EsModule; import org.sonar.server.issue.index.IssueIndex; import org.sonar.server.issue.index.IssueIndexSyncProgressChecker; import org.sonar.server.permission.index.WebAuthorizationTypeSupport; import org.sonar.server.platform.DefaultNodeInformation; import org.sonar.server.platform.ContainerSupportImpl; import org.sonar.server.platform.LogServerVersion; import org.sonar.server.platform.Platform; import org.sonar.server.platform.ServerFileSystemImpl; import org.sonar.server.platform.TempFolderProvider; import org.sonar.server.platform.UrlSettings; import org.sonar.server.platform.WebCoreExtensionsInstaller; import org.sonar.server.platform.db.EmbeddedDatabaseFactory; import org.sonar.server.rule.index.RuleIndex; import org.sonar.server.setting.ThreadLocalSettings; import org.sonar.server.user.SystemPasscodeImpl; import org.sonar.server.user.ThreadLocalUserSession; import org.sonar.server.util.GlobalLockManagerImpl; import org.sonar.server.util.OkHttpClientProvider; import org.sonar.server.util.Paths2Impl; import org.sonar.server.util.TempFolderCleaner; import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter; import static org.sonar.core.extension.PlatformLevelPredicates.hasPlatformLevel; public class PlatformLevel1 extends PlatformLevel { private final Platform platform; private final Properties properties; private final Object[] extraRootComponents; public PlatformLevel1(Platform platform, Properties properties, Object... extraRootComponents) { super("level1"); this.platform = platform; this.properties = properties; this.extraRootComponents = extraRootComponents; } @Override public void configureLevel() { add(platform, properties); addExtraRootComponents(); Version apiVersion = MetadataLoader.loadApiVersion(System2.INSTANCE); Version sqVersion = MetadataLoader.loadSQVersion(System2.INSTANCE); SonarEdition edition = MetadataLoader.loadEdition(System2.INSTANCE); add( new SonarQubeVersion(sqVersion), SonarRuntimeImpl.forSonarQube(apiVersion, SonarQubeSide.SERVER, edition), ThreadLocalSettings.class, ConfigurationProvider.class, LogServerVersion.class, ProcessCommandWrapperImpl.class, RestartFlagHolderImpl.class, UuidFactoryImpl.INSTANCE, NetworkUtilsImpl.INSTANCE, UrlSettings.class, EmbeddedDatabaseFactory.class, LogbackHelper.class, WebServerProcessLogging.class, DefaultDatabase.class, MyBatis.class, StartMyBatis.class, PurgeProfiler.class, ServerFileSystemImpl.class, TempFolderCleaner.class, new TempFolderProvider(), System2.INSTANCE, Paths2Impl.getInstance(), ContainerSupportImpl.class, Clock.systemDefaultZone(), // user session ThreadLocalUserSession.class, SystemPasscodeImpl.class, // DB DBSessionsImpl.class, DbClient.class, new DaoModule(), // Elasticsearch WebAuthorizationTypeSupport.class, new EsModule(), // rules/qprofiles RuleIndex.class, // issues IssueIndex.class, IssueIndexSyncProgressChecker.class, GlobalLockManagerImpl.class, new OkHttpClientProvider(), CoreExtensionRepositoryImpl.class, CoreExtensionsLoader.class, WebCoreExtensionsInstaller.class); addAll(CorePropertyDefinitions.all()); // cluster add(DefaultNodeInformation.class); } private void addExtraRootComponents() { if (this.extraRootComponents != null) { for (Object extraRootComponent : this.extraRootComponents) { add(extraRootComponent); } } } @Override public PlatformLevel start() { PlatformLevel start = super.start(); get(CoreExtensionsLoader.class) .load(); get(WebCoreExtensionsInstaller.class) .install(getContainer(), hasPlatformLevel(1), noAdditionalSideFilter()); if (getOptional(AuditPersister.class).isEmpty()) { add(NoOpAuditPersister.class); } return start; } }
6,170
34.0625
98
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel2.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import org.sonar.api.utils.Durations; import org.sonar.core.extension.CoreExtensionsInstaller; import org.sonar.core.platform.PluginClassLoader; import org.sonar.core.platform.PluginClassloaderFactory; import org.sonar.core.platform.SpringComponentContainer; import org.sonar.server.l18n.ServerI18n; import org.sonar.server.platform.DatabaseServerCompatibility; import org.sonar.server.platform.DefaultServerUpgradeStatus; import org.sonar.server.platform.OfficialDistribution; import org.sonar.server.platform.StartupMetadataProvider; import org.sonar.server.platform.WebCoreExtensionsInstaller; import org.sonar.server.platform.db.CheckDatabaseCharsetAtStartup; import org.sonar.server.platform.db.migration.DatabaseMigrationExecutorServiceImpl; import org.sonar.server.platform.db.migration.DatabaseMigrationStateImpl; import org.sonar.server.platform.db.migration.MigrationConfigurationModule; import org.sonar.server.platform.db.migration.charset.DatabaseCharsetChecker; import org.sonar.server.platform.db.migration.version.DatabaseVersion; import org.sonar.server.platform.web.WebPagesCache; import org.sonar.server.plugins.InstalledPluginReferentialFactory; import org.sonar.server.plugins.PluginJarLoader; import org.sonar.server.plugins.ServerPluginJarExploder; import org.sonar.server.plugins.ServerPluginManager; import org.sonar.server.plugins.ServerPluginRepository; import org.sonar.server.plugins.WebServerExtensionInstaller; import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter; import static org.sonar.core.extension.PlatformLevelPredicates.hasPlatformLevel; public class PlatformLevel2 extends PlatformLevel { public PlatformLevel2(PlatformLevel parent) { super("level2", parent); } @Override protected void configureLevel() { add( new MigrationConfigurationModule(), DatabaseVersion.class, DatabaseServerCompatibility.class, new StartupMetadataProvider(), DefaultServerUpgradeStatus.class, Durations.class, // index.html cache WebPagesCache.class, // plugins PluginJarLoader.class, ServerPluginRepository.class, ServerPluginManager.class, ServerPluginJarExploder.class, PluginClassLoader.class, PluginClassloaderFactory.class, InstalledPluginReferentialFactory.class, WebServerExtensionInstaller.class, // depends on plugins ServerI18n.class, OfficialDistribution.class); // Migration state must be kept at level2 to survive moving in and then out of safe mode // ExecutorService must be kept at level2 because stopping it when stopping safe mode level causes error making SQ fail add( DatabaseMigrationStateImpl.class, DatabaseMigrationExecutorServiceImpl.class); addIfStartupLeader( DatabaseCharsetChecker.class, CheckDatabaseCharsetAtStartup.class); } @Override public PlatformLevel start() { SpringComponentContainer container = getContainer(); CoreExtensionsInstaller coreExtensionsInstaller = parent.get(WebCoreExtensionsInstaller.class); coreExtensionsInstaller.install(container, hasPlatformLevel(2), noAdditionalSideFilter()); return super.start(); } }
4,120
38.625
123
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel3.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import org.sonar.api.utils.UriReader; import org.sonar.core.extension.CoreExtensionsInstaller; import org.sonar.core.platform.SpringComponentContainer; import org.sonar.core.util.DefaultHttpDownloader; import org.sonar.server.async.AsyncExecutionModule; import org.sonar.server.platform.ServerImpl; import org.sonar.server.platform.StartupMetadataPersister; import org.sonar.server.platform.WebCoreExtensionsInstaller; import org.sonar.server.platform.db.migration.NoopDatabaseMigrationImpl; import org.sonar.server.platform.serverid.ServerIdModule; import org.sonar.server.plugins.DetectPluginChange; import org.sonar.server.setting.DatabaseSettingLoader; import org.sonar.server.setting.DatabaseSettingsEnabler; import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter; import static org.sonar.core.extension.PlatformLevelPredicates.hasPlatformLevel; public class PlatformLevel3 extends PlatformLevel { public PlatformLevel3(PlatformLevel parent) { super("level3", parent); } @Override protected void configureLevel() { addIfStartupLeader( StartupMetadataPersister.class, DetectPluginChange.class); add( NoopDatabaseMigrationImpl.class, new ServerIdModule(), ServerImpl.class, DatabaseSettingLoader.class, DatabaseSettingsEnabler.class, UriReader.class, DefaultHttpDownloader.class, new AsyncExecutionModule()); } @Override public PlatformLevel start() { SpringComponentContainer container = getContainer(); CoreExtensionsInstaller coreExtensionsInstaller = parent.get(WebCoreExtensionsInstaller.class); coreExtensionsInstaller.install(container, hasPlatformLevel(3), noAdditionalSideFilter()); return super.start(); } }
2,654
37.478261
99
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevel4.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import java.util.List; import org.sonar.alm.client.TimeoutConfigurationImpl; import org.sonar.alm.client.azure.AzureDevOpsHttpClient; import org.sonar.alm.client.azure.AzureDevOpsValidator; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudRestClientConfiguration; import org.sonar.alm.client.bitbucket.bitbucketcloud.BitbucketCloudValidator; import org.sonar.alm.client.bitbucketserver.BitbucketServerRestClient; import org.sonar.alm.client.bitbucketserver.BitbucketServerSettingsValidator; import org.sonar.alm.client.github.GithubApplicationClientImpl; import org.sonar.alm.client.github.GithubApplicationHttpClientImpl; import org.sonar.alm.client.github.GithubGlobalSettingsValidator; import org.sonar.alm.client.github.config.GithubProvisioningConfigValidator; import org.sonar.alm.client.github.security.GithubAppSecurityImpl; import org.sonar.alm.client.gitlab.GitlabGlobalSettingsValidator; import org.sonar.alm.client.gitlab.GitlabHttpClient; import org.sonar.api.profiles.XMLProfileParser; import org.sonar.api.profiles.XMLProfileSerializer; import org.sonar.api.resources.ResourceTypes; import org.sonar.api.rules.AnnotationRuleParser; import org.sonar.api.server.rule.RulesDefinitionXmlLoader; import org.sonar.auth.bitbucket.BitbucketModule; import org.sonar.auth.github.GitHubModule; import org.sonar.auth.github.GitHubSettings; import org.sonar.auth.gitlab.GitLabModule; import org.sonar.auth.ldap.LdapModule; import org.sonar.auth.saml.SamlModule; import org.sonar.ce.task.projectanalysis.notification.ReportAnalysisFailureNotificationModule; import org.sonar.ce.task.projectanalysis.taskprocessor.AuditPurgeTaskProcessor; import org.sonar.ce.task.projectanalysis.taskprocessor.IssueSyncTaskProcessor; import org.sonar.ce.task.projectanalysis.taskprocessor.ReportTaskProcessor; import org.sonar.ce.task.projectexport.taskprocessor.ProjectExportTaskProcessor; import org.sonar.core.component.DefaultResourceTypes; import org.sonar.core.documentation.DefaultDocumentationLinkGenerator; import org.sonar.core.extension.CoreExtensionsInstaller; import org.sonar.core.language.LanguagesProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.core.platform.SpringComponentContainer; import org.sonar.server.almintegration.ws.AlmIntegrationsWSModule; import org.sonar.server.almintegration.ws.CredentialsEncoderHelper; import org.sonar.server.almintegration.ws.ImportHelper; import org.sonar.server.almintegration.ws.ProjectKeyGenerator; import org.sonar.server.almintegration.ws.github.GithubProvisioningWs; import org.sonar.server.almsettings.MultipleAlmFeature; import org.sonar.server.almsettings.ws.AlmSettingsWsModule; import org.sonar.server.authentication.AuthenticationModule; import org.sonar.server.authentication.DefaultAdminCredentialsVerifierImpl; import org.sonar.server.authentication.DefaultAdminCredentialsVerifierNotificationHandler; import org.sonar.server.authentication.DefaultAdminCredentialsVerifierNotificationTemplate; import org.sonar.server.authentication.LogOAuthWarning; import org.sonar.server.authentication.ws.AuthenticationWsModule; import org.sonar.server.badge.ws.ProjectBadgesWsModule; import org.sonar.server.batch.BatchWsModule; import org.sonar.server.branch.BranchFeatureProxyImpl; import org.sonar.server.branch.ws.BranchWsModule; import org.sonar.server.ce.CeModule; import org.sonar.server.ce.projectdump.ProjectExportWsModule; import org.sonar.server.ce.ws.CeWsModule; import org.sonar.server.component.ComponentCleanerService; import org.sonar.server.component.ComponentFinder; import org.sonar.server.component.ComponentService; import org.sonar.server.component.ComponentUpdater; import org.sonar.server.component.index.ComponentIndex; import org.sonar.server.component.index.ComponentIndexDefinition; import org.sonar.server.component.index.EntityDefinitionIndexer; import org.sonar.server.component.ws.ComponentViewerJsonWriter; import org.sonar.server.component.ws.ComponentsWsModule; import org.sonar.server.developers.ws.DevelopersWsModule; import org.sonar.server.duplication.ws.DuplicationsParser; import org.sonar.server.duplication.ws.DuplicationsWs; import org.sonar.server.duplication.ws.ShowResponseBuilder; import org.sonar.server.email.ws.EmailsWsModule; import org.sonar.server.es.IndexCreator; import org.sonar.server.es.IndexDefinitions; import org.sonar.server.es.IndexersImpl; import org.sonar.server.es.RecoveryIndexer; import org.sonar.server.es.metadata.EsDbCompatibilityImpl; import org.sonar.server.es.metadata.MetadataIndexDefinition; import org.sonar.server.es.metadata.MetadataIndexImpl; import org.sonar.server.extension.CoreExtensionBootstraper; import org.sonar.server.extension.CoreExtensionStopper; import org.sonar.server.favorite.FavoriteModule; import org.sonar.server.favorite.ws.FavoriteWsModule; import org.sonar.server.feature.ws.FeatureWsModule; import org.sonar.server.health.NodeHealthModule; import org.sonar.server.hotspot.ws.HotspotsWsModule; import org.sonar.server.issue.AddTagsAction; import org.sonar.server.issue.AssignAction; import org.sonar.server.issue.CommentAction; import org.sonar.server.issue.IssueChangePostProcessorImpl; import org.sonar.server.issue.RemoveTagsAction; import org.sonar.server.issue.SetSeverityAction; import org.sonar.server.issue.SetTypeAction; import org.sonar.server.issue.TransitionAction; import org.sonar.server.issue.index.AsyncIssueIndexingImpl; import org.sonar.server.issue.index.IssueIndexDefinition; import org.sonar.server.issue.index.IssueIndexer; import org.sonar.server.issue.index.IssueIteratorFactory; import org.sonar.server.issue.notification.IssuesChangesNotificationModule; import org.sonar.server.issue.notification.MyNewIssuesEmailTemplate; import org.sonar.server.issue.notification.MyNewIssuesNotificationHandler; import org.sonar.server.issue.notification.NewIssuesEmailTemplate; import org.sonar.server.issue.notification.NewIssuesNotificationHandler; import org.sonar.server.issue.ws.IssueWsModule; import org.sonar.server.language.LanguageValidation; import org.sonar.server.language.ws.LanguageWs; import org.sonar.server.log.ServerLogging; import org.sonar.server.loginmessage.LoginMessageFeature; import org.sonar.server.management.DelegatingManagedInstanceService; import org.sonar.server.measure.index.ProjectsEsModule; import org.sonar.server.measure.live.LiveMeasureModule; import org.sonar.server.measure.ws.MeasuresWsModule; import org.sonar.server.metric.MetricFinder; import org.sonar.server.metric.UnanalyzedLanguageMetrics; import org.sonar.server.metric.ws.MetricsWsModule; import org.sonar.server.monitoring.ComputeEngineMetricStatusTask; import org.sonar.server.monitoring.ElasticSearchMetricTask; import org.sonar.server.monitoring.MainCollector; import org.sonar.server.monitoring.MonitoringWsModule; import org.sonar.server.monitoring.ServerMonitoringMetrics; import org.sonar.server.monitoring.SonarLintConnectedClientsTask; import org.sonar.server.monitoring.WebUptimeTask; import org.sonar.server.monitoring.ce.NumberOfTasksInQueueTask; import org.sonar.server.monitoring.ce.RecentTasksDurationTask; import org.sonar.server.monitoring.devops.AzureMetricsTask; import org.sonar.server.monitoring.devops.BitbucketMetricsTask; import org.sonar.server.monitoring.devops.GithubMetricsTask; import org.sonar.server.monitoring.devops.GitlabMetricsTask; import org.sonar.server.newcodeperiod.NewCodeDefinitionResolver; import org.sonar.server.newcodeperiod.ws.NewCodePeriodsWsModule; import org.sonar.server.notification.NotificationModule; import org.sonar.server.notification.ws.NotificationWsModule; import org.sonar.server.permission.DefaultTemplatesResolverImpl; import org.sonar.server.permission.GroupPermissionChanger; import org.sonar.server.permission.PermissionTemplateService; import org.sonar.server.permission.PermissionUpdater; import org.sonar.server.permission.UserPermissionChanger; import org.sonar.server.permission.index.PermissionIndexer; import org.sonar.server.permission.ws.PermissionsWsModule; import org.sonar.server.platform.ClusterVerification; import org.sonar.server.platform.PersistentSettings; import org.sonar.server.platform.SystemInfoWriterModule; import org.sonar.server.platform.WebCoreExtensionsInstaller; import org.sonar.server.platform.db.CheckAnyonePermissionsAtStartup; import org.sonar.server.platform.db.CheckLanguageSpecificParamsAtStartup; import org.sonar.server.platform.web.SonarLintConnectionFilter; import org.sonar.server.platform.web.WebServiceFilter; import org.sonar.server.platform.web.WebServiceReroutingFilter; import org.sonar.server.platform.web.requestid.HttpRequestIdModule; import org.sonar.server.platform.ws.ChangeLogLevelServiceModule; import org.sonar.server.platform.ws.HealthCheckerModule; import org.sonar.server.platform.ws.L10nWs; import org.sonar.server.platform.ws.ServerWs; import org.sonar.server.platform.ws.SystemWsModule; import org.sonar.server.plugins.PluginDownloader; import org.sonar.server.plugins.PluginUninstaller; import org.sonar.server.plugins.PluginsRiskConsentFilter; import org.sonar.server.plugins.ServerExtensionInstaller; import org.sonar.server.plugins.ws.AvailableAction; import org.sonar.server.plugins.ws.CancelAllAction; import org.sonar.server.plugins.ws.DownloadAction; import org.sonar.server.plugins.ws.InstallAction; import org.sonar.server.plugins.ws.InstalledAction; import org.sonar.server.plugins.ws.PendingAction; import org.sonar.server.plugins.ws.PluginUpdateAggregator; import org.sonar.server.plugins.ws.PluginsWs; import org.sonar.server.plugins.ws.UninstallAction; import org.sonar.server.plugins.ws.UpdatesAction; import org.sonar.server.project.DefaultBranchNameResolver; import org.sonar.server.project.ProjectQGChangeEventListener; import org.sonar.server.project.ws.ProjectsWsModule; import org.sonar.server.projectanalysis.ws.ProjectAnalysisWsModule; import org.sonar.server.projectlink.ws.ProjectLinksModule; import org.sonar.server.projecttag.ws.ProjectTagsWsModule; import org.sonar.server.property.InternalPropertiesImpl; import org.sonar.server.pushapi.ServerPushModule; import org.sonar.server.pushapi.hotspots.HotspotChangeEventServiceImpl; import org.sonar.server.pushapi.issues.IssueChangeEventServiceImpl; import org.sonar.server.pushapi.qualityprofile.QualityProfileChangeEventServiceImpl; import org.sonar.server.qualitygate.ProjectsInWarningModule; import org.sonar.server.qualitygate.QualityGateModule; import org.sonar.server.qualitygate.notification.QGChangeNotificationHandler; import org.sonar.server.qualitygate.ws.QualityGateWsModule; import org.sonar.server.qualityprofile.QProfileBackuperImpl; import org.sonar.server.qualityprofile.QProfileComparison; import org.sonar.server.qualityprofile.QProfileCopier; import org.sonar.server.qualityprofile.QProfileExporters; import org.sonar.server.qualityprofile.QProfileFactoryImpl; import org.sonar.server.qualityprofile.QProfileParser; import org.sonar.server.qualityprofile.QProfileResetImpl; import org.sonar.server.qualityprofile.QProfileRulesImpl; import org.sonar.server.qualityprofile.QProfileTreeImpl; import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationHandler; import org.sonar.server.qualityprofile.builtin.BuiltInQPChangeNotificationTemplate; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileRepositoryImpl; import org.sonar.server.qualityprofile.builtin.RuleActivator; import org.sonar.server.qualityprofile.index.ActiveRuleIndexer; import org.sonar.server.qualityprofile.ws.QProfilesWsModule; import org.sonar.server.rule.RuleCreator; import org.sonar.server.rule.RuleDefinitionsLoader; import org.sonar.server.rule.RuleDescriptionFormatter; import org.sonar.server.rule.RuleUpdater; import org.sonar.server.rule.WebServerRuleFinderImpl; import org.sonar.server.rule.index.RuleIndexDefinition; import org.sonar.server.rule.index.RuleIndexer; import org.sonar.server.rule.ws.ActiveRuleCompleter; import org.sonar.server.rule.ws.RepositoriesAction; import org.sonar.server.rule.ws.RuleMapper; import org.sonar.server.rule.ws.RuleQueryFactory; import org.sonar.server.rule.ws.RuleWsSupport; import org.sonar.server.rule.ws.RulesWs; import org.sonar.server.rule.ws.TagsAction; import org.sonar.server.saml.ws.SamlValidationModule; import org.sonar.server.scannercache.ScannerCache; import org.sonar.server.scannercache.ws.AnalysisCacheWsModule; import org.sonar.server.setting.ProjectConfigurationLoaderImpl; import org.sonar.server.setting.SettingsChangeNotifier; import org.sonar.server.setting.ws.SettingsWsModule; import org.sonar.server.source.ws.SourceWsModule; import org.sonar.server.startup.LogServerId; import org.sonar.server.telemetry.CloudUsageDataProvider; import org.sonar.server.telemetry.TelemetryClient; import org.sonar.server.telemetry.TelemetryDaemon; import org.sonar.server.telemetry.TelemetryDataJsonWriter; import org.sonar.server.telemetry.TelemetryDataLoaderImpl; import org.sonar.server.text.MacroInterpreter; import org.sonar.server.ui.PageRepository; import org.sonar.server.ui.WebAnalyticsLoaderImpl; import org.sonar.server.ui.ws.NavigationWsModule; import org.sonar.server.updatecenter.UpdateCenterModule; import org.sonar.server.user.NewUserNotifier; import org.sonar.server.user.SecurityRealmFactory; import org.sonar.server.user.UserSessionFactoryImpl; import org.sonar.server.user.UserUpdater; import org.sonar.server.user.ws.UsersWsModule; import org.sonar.server.usergroups.DefaultGroupFinder; import org.sonar.server.usergroups.ws.UserGroupsModule; import org.sonar.server.usertoken.UserTokenModule; import org.sonar.server.usertoken.ws.UserTokenWsModule; import org.sonar.server.util.TypeValidationModule; import org.sonar.server.view.index.ViewIndex; import org.sonar.server.view.index.ViewIndexDefinition; import org.sonar.server.view.index.ViewIndexer; import org.sonar.server.webhook.WebhookModule; import org.sonar.server.webhook.WebhookQGChangeEventListener; import org.sonar.server.webhook.ws.WebhooksWsModule; import org.sonar.server.ws.WebServiceEngine; import org.sonar.server.ws.ws.WebServicesWsModule; import static org.sonar.core.extension.CoreExtensionsInstaller.noAdditionalSideFilter; import static org.sonar.core.extension.PlatformLevelPredicates.hasPlatformLevel4OrNone; public class PlatformLevel4 extends PlatformLevel { private final List<Object> level4AddedComponents; public PlatformLevel4(PlatformLevel parent, List<Object> level4AddedComponents) { super("level4", parent); this.level4AddedComponents = level4AddedComponents; } @Override protected void configureLevel() { addIfStartupLeader( IndexCreator.class, MetadataIndexDefinition.class, MetadataIndexImpl.class, EsDbCompatibilityImpl.class); addIfCluster(new NodeHealthModule()); add( RuleDescriptionFormatter.class, ClusterVerification.class, LogServerId.class, LogOAuthWarning.class, PluginUninstaller.class, PluginDownloader.class, PageRepository.class, ResourceTypes.class, DefaultResourceTypes.get(), SettingsChangeNotifier.class, ServerWs.class, IndexDefinitions.class, WebAnalyticsLoaderImpl.class, new MonitoringWsModule(), DefaultBranchNameResolver.class, DefaultDocumentationLinkGenerator.class, DelegatingManagedInstanceService.class, // batch new BatchWsModule(), // update center new UpdateCenterModule(), // quality profile BuiltInQProfileRepositoryImpl.class, ActiveRuleIndexer.class, XMLProfileParser.class, XMLProfileSerializer.class, QProfileComparison.class, QProfileTreeImpl.class, QProfileRulesImpl.class, RuleActivator.class, QualityProfileChangeEventServiceImpl.class, QProfileExporters.class, QProfileFactoryImpl.class, QProfileCopier.class, QProfileBackuperImpl.class, QProfileParser.class, QProfileResetImpl.class, new QProfilesWsModule(), // rule RuleIndexDefinition.class, RuleIndexer.class, AnnotationRuleParser.class, WebServerRuleFinderImpl.class, RuleDefinitionsLoader.class, RulesDefinitionXmlLoader.class, RuleUpdater.class, RuleCreator.class, org.sonar.server.rule.ws.UpdateAction.class, RulesWs.class, RuleWsSupport.class, org.sonar.server.rule.ws.SearchAction.class, org.sonar.server.rule.ws.ShowAction.class, org.sonar.server.rule.ws.CreateAction.class, org.sonar.server.rule.ws.DeleteAction.class, org.sonar.server.rule.ws.ListAction.class, TagsAction.class, RuleMapper.class, ActiveRuleCompleter.class, RepositoriesAction.class, RuleQueryFactory.class, org.sonar.server.rule.ws.AppAction.class, // languages LanguagesProvider.class, LanguageWs.class, LanguageValidation.class, org.sonar.server.language.ws.ListAction.class, // measure new MetricsWsModule(), new MeasuresWsModule(), MetricFinder.class, UnanalyzedLanguageMetrics.class, new QualityGateModule(), new ProjectsInWarningModule(), new QualityGateWsModule(), // web services WebServiceEngine.class, new WebServicesWsModule(), SonarLintConnectionFilter.class, WebServiceFilter.class, WebServiceReroutingFilter.class, // localization L10nWs.class, org.sonar.server.platform.ws.IndexAction.class, // authentication new AuthenticationModule(), new AuthenticationWsModule(), new BitbucketModule(), GitHubSettings.class, new GitHubModule(), new GitLabModule(), new LdapModule(), new SamlModule(), new SamlValidationModule(), DefaultAdminCredentialsVerifierImpl.class, DefaultAdminCredentialsVerifierNotificationTemplate.class, DefaultAdminCredentialsVerifierNotificationHandler.class, // users UserSessionFactoryImpl.class, SecurityRealmFactory.class, NewUserNotifier.class, UserUpdater.class, new UsersWsModule(), new UserTokenModule(), new UserTokenWsModule(), // groups new UserGroupsModule(), DefaultGroupFinder.class, // permissions DefaultTemplatesResolverImpl.class, new PermissionsWsModule(), PermissionTemplateService.class, PermissionUpdater.class, UserPermissionChanger.class, GroupPermissionChanger.class, CheckAnyonePermissionsAtStartup.class, CheckLanguageSpecificParamsAtStartup.class, // components new BranchWsModule(), new ProjectsWsModule(), new ProjectsEsModule(), new ProjectTagsWsModule(), new ComponentsWsModule(), ComponentService.class, ComponentUpdater.class, ComponentFinder.class, QGChangeNotificationHandler.class, QGChangeNotificationHandler.newMetadata(), ComponentCleanerService.class, ComponentIndexDefinition.class, ComponentIndex.class, EntityDefinitionIndexer.class, new LiveMeasureModule(), ComponentViewerJsonWriter.class, new DevelopersWsModule(), new FavoriteModule(), new FavoriteWsModule(), // views ViewIndexDefinition.class, ViewIndexer.class, ViewIndex.class, // issues IssueIndexDefinition.class, AsyncIssueIndexingImpl.class, IssueIndexer.class, IssueIteratorFactory.class, PermissionIndexer.class, new IssueWsModule(), NewIssuesEmailTemplate.class, MyNewIssuesEmailTemplate.class, new IssuesChangesNotificationModule(), NewIssuesNotificationHandler.class, NewIssuesNotificationHandler.newMetadata(), MyNewIssuesNotificationHandler.class, MyNewIssuesNotificationHandler.newMetadata(), IssueChangeEventServiceImpl.class, HotspotChangeEventServiceImpl.class, // issues actions AssignAction.class, SetTypeAction.class, SetSeverityAction.class, CommentAction.class, TransitionAction.class, AddTagsAction.class, RemoveTagsAction.class, IssueChangePostProcessorImpl.class, // hotspots new HotspotsWsModule(), // source new SourceWsModule(), // Duplications DuplicationsParser.class, DuplicationsWs.class, ShowResponseBuilder.class, org.sonar.server.duplication.ws.ShowAction.class, // text MacroInterpreter.class, // Notifications // Those class are required in order to be able to send emails during startup // Without having two NotificationModule (one in StartupLevel and one in Level4) BuiltInQPChangeNotificationTemplate.class, BuiltInQPChangeNotificationHandler.class, new NotificationModule(), new NotificationWsModule(), new EmailsWsModule(), // Settings ProjectConfigurationLoaderImpl.class, PersistentSettings.class, new SettingsWsModule(), new TypeValidationModule(), // New Code Periods new NewCodePeriodsWsModule(), NewCodeDefinitionResolver.class, // Project Links new ProjectLinksModule(), // Project Analyses new ProjectAnalysisWsModule(), // System ServerLogging.class, new ChangeLogLevelServiceModule(getWebServer()), new HealthCheckerModule(getWebServer()), new SystemWsModule(), // Plugins WS PluginUpdateAggregator.class, InstalledAction.class, AvailableAction.class, DownloadAction.class, UpdatesAction.class, PendingAction.class, InstallAction.class, org.sonar.server.plugins.ws.UpdateAction.class, UninstallAction.class, CancelAllAction.class, PluginsWs.class, // Scanner Cache ScannerCache.class, new AnalysisCacheWsModule(), // ALM integrations TimeoutConfigurationImpl.class, CredentialsEncoderHelper.class, ImportHelper.class, ProjectKeyGenerator.class, GithubAppSecurityImpl.class, GithubApplicationClientImpl.class, GithubApplicationHttpClientImpl.class, GithubProvisioningConfigValidator.class, GithubProvisioningWs.class, BitbucketCloudRestClientConfiguration.class, BitbucketServerRestClient.class, GitlabHttpClient.class, AzureDevOpsHttpClient.class, new AlmIntegrationsWSModule(), BitbucketCloudValidator.class, BitbucketServerSettingsValidator.class, GithubGlobalSettingsValidator.class, GitlabGlobalSettingsValidator.class, AzureDevOpsValidator.class, // ALM settings new AlmSettingsWsModule(), // Project export new ProjectExportWsModule(), // Branch BranchFeatureProxyImpl.class, // Project badges new ProjectBadgesWsModule(), // Core Extensions CoreExtensionBootstraper.class, CoreExtensionStopper.class, MultipleAlmFeature.class, LoginMessageFeature.class, // ServerPush endpoints new ServerPushModule(), // Compute engine (must be after Views and Developer Cockpit) new ReportAnalysisFailureNotificationModule(), new CeModule(), new CeWsModule(), ReportTaskProcessor.class, IssueSyncTaskProcessor.class, AuditPurgeTaskProcessor.class, ProjectExportTaskProcessor.class, // SonarSource editions PlatformEditionProvider.class, InternalPropertiesImpl.class, // UI new NavigationWsModule(), // SonarQube features new FeatureWsModule(), // webhooks WebhookQGChangeEventListener.class, new WebhookModule(), new WebhooksWsModule(), ProjectQGChangeEventListener.class, // Http Request ID new HttpRequestIdModule(), RecoveryIndexer.class, IndexersImpl.class, // telemetry TelemetryDataLoaderImpl.class, TelemetryDataJsonWriter.class, TelemetryDaemon.class, TelemetryClient.class, CloudUsageDataProvider.class, // monitoring ServerMonitoringMetrics.class, AzureMetricsTask.class, BitbucketMetricsTask.class, GithubMetricsTask.class, GitlabMetricsTask.class, NumberOfTasksInQueueTask.class, RecentTasksDurationTask.class, ComputeEngineMetricStatusTask.class, ElasticSearchMetricTask.class, WebUptimeTask.class, SonarLintConnectedClientsTask.class, MainCollector.class, PluginsRiskConsentFilter.class); // system info add(new SystemInfoWriterModule(getWebServer())); addAll(level4AddedComponents); } @Override public PlatformLevel start() { SpringComponentContainer container = getContainer(); CoreExtensionsInstaller coreExtensionsInstaller = parent.get(WebCoreExtensionsInstaller.class); coreExtensionsInstaller.install(container, hasPlatformLevel4OrNone(), noAdditionalSideFilter()); ServerExtensionInstaller extensionInstaller = parent.get(ServerExtensionInstaller.class); extensionInstaller.installExtensions(container); super.start(); return this; } }
26,139
38.131737
100
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevelSafeMode.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import org.sonar.server.authentication.SafeModeUserSession; import org.sonar.server.monitoring.ServerMonitoringMetrics; import org.sonar.server.platform.ServerImpl; import org.sonar.server.platform.db.migration.AutoDbMigration; import org.sonar.server.platform.db.migration.DatabaseMigrationImpl; import org.sonar.server.platform.db.migration.MigrationEngineModule; import org.sonar.server.platform.db.migration.NoopDatabaseMigrationImpl; import org.sonar.server.platform.web.WebServiceFilter; import org.sonar.server.platform.ws.IndexAction; import org.sonar.server.platform.ws.L10nWs; import org.sonar.server.platform.ws.SafeModeHealthCheckerModule; import org.sonar.server.platform.ws.SafemodeSystemWsModule; import org.sonar.server.ws.WebServiceEngine; import org.sonar.server.ws.ws.WebServicesWsModule; public class PlatformLevelSafeMode extends PlatformLevel { public PlatformLevelSafeMode(PlatformLevel parent) { super("Safemode", parent); } @Override protected void configureLevel() { add( ServerImpl.class, // l10n WS L10nWs.class, IndexAction.class, // Server WS new SafeModeHealthCheckerModule(), new SafemodeSystemWsModule(), // Listing WS new WebServicesWsModule(), // WS engine SafeModeUserSession.class, WebServiceEngine.class, WebServiceFilter.class, // Monitoring ServerMonitoringMetrics.class); addIfStartupLeader( DatabaseMigrationImpl.class, new MigrationEngineModule(), AutoDbMigration.class) .otherwiseAdd(NoopDatabaseMigrationImpl.class); } }
2,504
33.791667
75
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/PlatformLevelStartup.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import org.slf4j.LoggerFactory; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.server.app.ProcessCommandWrapper; import org.sonar.server.authentication.DefaultAdminCredentialsVerifierImpl; import org.sonar.server.ce.queue.CeQueueCleaner; import org.sonar.server.es.IndexerStartupTask; import org.sonar.server.platform.ServerLifecycleNotifier; import org.sonar.server.platform.web.RegisterServletFilters; import org.sonar.server.plugins.DetectPluginChange; import org.sonar.server.plugins.PluginConsentVerifier; import org.sonar.server.qualitygate.ProjectsInWarningDaemon; import org.sonar.server.qualitygate.RegisterQualityGates; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileInsertImpl; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileLoader; import org.sonar.server.qualityprofile.builtin.BuiltInQProfileUpdateImpl; import org.sonar.server.qualityprofile.builtin.BuiltInQualityProfilesUpdateListener; import org.sonar.server.qualityprofile.RegisterQualityProfiles; import org.sonar.server.rule.AdvancedRuleDescriptionSectionsGenerator; import org.sonar.server.rule.LegacyHotspotRuleDescriptionSectionsGenerator; import org.sonar.server.rule.LegacyIssueRuleDescriptionSectionsGenerator; import org.sonar.server.rule.RegisterRules; import org.sonar.server.rule.RuleDescriptionSectionsGeneratorResolver; import org.sonar.server.rule.WebServerRuleFinder; import org.sonar.server.startup.GeneratePluginIndex; import org.sonar.server.startup.RegisterMetrics; import org.sonar.server.startup.RegisterPermissionTemplates; import org.sonar.server.startup.RegisterPlugins; import org.sonar.server.startup.RenameDeprecatedPropertyKeys; import org.sonar.server.startup.UpgradeSuggestionsCleaner; import org.sonar.server.user.DoPrivileged; import org.sonar.server.user.ThreadLocalUserSession; public class PlatformLevelStartup extends PlatformLevel { private AddIfStartupLeaderAndPluginsChanged addIfPluginsChanged; public PlatformLevelStartup(PlatformLevel parent) { super("startup tasks", parent); } @Override protected void configureLevel() { add(GeneratePluginIndex.class, ServerLifecycleNotifier.class); addIfStartupLeader( IndexerStartupTask.class); addIfStartupLeaderAndPluginsChanged( RegisterMetrics.class, RegisterQualityGates.class, RuleDescriptionSectionsGeneratorResolver.class, AdvancedRuleDescriptionSectionsGenerator.class, LegacyHotspotRuleDescriptionSectionsGenerator.class, LegacyIssueRuleDescriptionSectionsGenerator.class, RegisterRules.class, BuiltInQProfileLoader.class); addIfStartupLeader( BuiltInQualityProfilesUpdateListener.class, BuiltInQProfileUpdateImpl.class); addIfStartupLeaderAndPluginsChanged( BuiltInQProfileInsertImpl.class, RegisterQualityProfiles.class); addIfStartupLeader( RegisterPermissionTemplates.class, RenameDeprecatedPropertyKeys.class, CeQueueCleaner.class, UpgradeSuggestionsCleaner.class, PluginConsentVerifier.class); add(RegisterPlugins.class, // RegisterServletFilters makes the WebService engine of Level4 served by the MasterServletFilter, therefore it // must be started after all the other startup tasks RegisterServletFilters.class ); } /** * Add a component to container only if plugins have changed since last start. * * @throws IllegalStateException if called from PlatformLevel3 or below, plugin info is loaded yet */ AddIfStartupLeaderAndPluginsChanged addIfStartupLeaderAndPluginsChanged(Object... objects) { if (addIfPluginsChanged == null) { this.addIfPluginsChanged = new AddIfStartupLeaderAndPluginsChanged(getWebServer().isStartupLeader() && anyPluginChanged()); } addIfPluginsChanged.ifAdd(objects); return addIfPluginsChanged; } private boolean anyPluginChanged() { return parent.getOptional(DetectPluginChange.class) .map(DetectPluginChange::anyPluginChanged) .orElseThrow(() -> new IllegalStateException("DetectPluginChange not available in the container yet")); } public final class AddIfStartupLeaderAndPluginsChanged extends AddIf { private AddIfStartupLeaderAndPluginsChanged(boolean condition) { super(condition); } } @Override public PlatformLevel start() { DoPrivileged.execute(new DoPrivileged.Task(parent.get(ThreadLocalUserSession.class)) { @Override protected void doPrivileged() { PlatformLevelStartup.super.start(); getOptional(IndexerStartupTask.class).ifPresent(IndexerStartupTask::execute); // Need to be executed after indexing as it executes an ES query get(ProjectsInWarningDaemon.class).notifyStart(); get(ServerLifecycleNotifier.class).notifyStart(); get(ProcessCommandWrapper.class).notifyOperational(); get(WebServerRuleFinder.class).stopCaching(); LoggerFactory.getLogger(PlatformLevelStartup.class) .info("Running {} Edition", get(PlatformEditionProvider.class).get().map(EditionProvider.Edition::getLabel).orElse("")); get(DefaultAdminCredentialsVerifierImpl.class).runAtStart(); } }); return this; } }
6,177
42.202797
130
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/platformlevel/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.platformlevel; import javax.annotation.ParametersAreNonnullByDefault;
979
39.833333
75
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/ApiV2Servlet.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.util.function.Function; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.sonar.server.platform.platformlevel.PlatformLevel; import org.sonar.server.v2.config.PlatformLevel4WebConfig; import org.sonar.server.v2.config.SafeModeWebConfig; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.AnnotationConfigWebApplicationContext; import org.springframework.web.servlet.DispatcherServlet; public class ApiV2Servlet implements Servlet { public static final String SERVLET_NAME = "WebAPI V2 Servlet"; private Function<WebApplicationContext, DispatcherServlet> servletProvider; private ServletConfig config = null; private DispatcherServlet dispatcherLevel4 = null; private DispatcherServlet dispatcherSafeMode = null; public ApiV2Servlet() { this.servletProvider = DispatcherServlet::new; } @VisibleForTesting void setServletProvider(Function<WebApplicationContext, DispatcherServlet> servletProvider) { this.servletProvider = servletProvider; } @Override public String getServletInfo() { return SERVLET_NAME; } @Override public ServletConfig getServletConfig() { return config; } @Override public void init(ServletConfig config) throws ServletException { this.config = config; if (dispatcherLevel4 != null) { dispatcherLevel4.init(config); } if (dispatcherSafeMode != null) { dispatcherSafeMode.init(config); } } public void initDispatcherSafeMode(PlatformLevel platformLevel) { this.dispatcherSafeMode = initDispatcherServlet(platformLevel, SafeModeWebConfig.class); } public void initDispatcherLevel4(PlatformLevel platformLevel) { dispatcherLevel4 = initDispatcherServlet(platformLevel, PlatformLevel4WebConfig.class); destroyDispatcherSafeMode(); } private DispatcherServlet initDispatcherServlet(PlatformLevel platformLevel, Class<?> configClass) { AnnotationConfigWebApplicationContext springMvcContext = new AnnotationConfigWebApplicationContext(); springMvcContext.setParent(platformLevel.getContainer().context()); springMvcContext.register(configClass); DispatcherServlet dispatcher = servletProvider.apply(springMvcContext); try { if (config != null) { dispatcher.init(config); } } catch (ServletException e) { throw new RuntimeException(e); } return dispatcher; } @Override public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { if (dispatcherSafeMode != null) { dispatcherSafeMode.service(req, res); } else if (dispatcherLevel4 != null) { dispatcherLevel4.service(req, res); } else { HttpServletResponse httpResponse = (HttpServletResponse) res; httpResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } } @Override public void destroy() { destroyDispatcherSafeMode(); destroyLevel4(); } private void destroyDispatcherSafeMode() { if (dispatcherSafeMode != null) { DispatcherServlet dispatcherToDestroy = dispatcherSafeMode; dispatcherSafeMode = null; dispatcherToDestroy.destroy(); } } private void destroyLevel4() { if (dispatcherLevel4 != null) { dispatcherLevel4.destroy(); } } }
4,453
33
105
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/CacheControlFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.util.Map; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static java.lang.String.format; /** * This servlet filter sets response headers that enable cache control on some static resources */ public class CacheControlFilter implements Filter { private static final String CACHE_CONTROL_HEADER = "Cache-Control"; /** * Recommended max value for max-age is 1 year * @see <a href="https://stackoverflow.com/questions/7071763/max-value-for-cache-control-header-in-http">stackoverflow thread</a> */ private static final int ONE_YEAR_IN_SECONDS = 365 * 24 * 60 * 60; private static final int FIVE_MINUTES_IN_SECONDS = 5 * 60; private static final String MAX_AGE_TEMPLATE = "max-age=%d"; private static final Map<String, Integer> MAX_AGE_BY_PATH = ImmutableMap.of( // These folders contains files that are suffixed with their content hash : the cache should never be invalidated "/js/", ONE_YEAR_IN_SECONDS, "/css/", ONE_YEAR_IN_SECONDS, // This folder contains static resources from plugins : the cache should be set to a small value "/static/", FIVE_MINUTES_IN_SECONDS, "/images/", FIVE_MINUTES_IN_SECONDS); @Override public void init(FilterConfig filterConfig) { // nothing } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { String path = ((HttpServletRequest) req).getRequestURI().replaceFirst(((HttpServletRequest) req).getContextPath(), ""); MAX_AGE_BY_PATH.entrySet().stream() .filter(m -> path.startsWith(m.getKey())) .map(Map.Entry::getValue) .findFirst() .ifPresent(maxAge -> ((HttpServletResponse) resp).addHeader(CACHE_CONTROL_HEADER, format(MAX_AGE_TEMPLATE, maxAge))); chain.doFilter(req, resp); } @Override public void destroy() { // nothing } }
3,091
35.809524
131
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/CspFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; public class CspFilter implements Filter { private final List<String> cspHeaders = new ArrayList<>(); private String policies = null; @Override public void init(FilterConfig filterConfig) throws ServletException { cspHeaders.add("Content-Security-Policy"); cspHeaders.add("X-Content-Security-Policy"); cspHeaders.add("X-WebKit-CSP"); List<String> cspPolicies = new ArrayList<>(); cspPolicies.add("default-src 'self'"); cspPolicies.add("base-uri 'none'"); cspPolicies.add("connect-src 'self' http: https:"); cspPolicies.add("img-src * data: blob:"); cspPolicies.add("object-src 'none'"); cspPolicies.add("script-src 'self'"); cspPolicies.add("style-src 'self' 'unsafe-inline'"); cspPolicies.add("worker-src 'none'"); this.policies = String.join("; ", cspPolicies).trim(); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // Add policies to all HTTP headers for (String header : this.cspHeaders) { ((HttpServletResponse) response).setHeader(header, this.policies); } chain.doFilter(request, response); } @Override public void destroy() { // Not used } }
2,479
33.444444
130
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/MasterServletFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.slf4j.LoggerFactory; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.ServletFilter; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import org.sonar.server.platform.PlatformImpl; /** * Inspired by http://stackoverflow.com/a/7592883/229031 */ public class MasterServletFilter implements Filter { private static final String SCIM_FILTER_PATH = "/api/scim/v2/"; private static final Logger LOG = LoggerFactory.getLogger(MasterServletFilter.class); private static volatile MasterServletFilter instance; @Deprecated(forRemoval = true) private ServletFilter[] filters; private HttpFilter[] httpFilters; private FilterConfig config; public MasterServletFilter() { if (instance != null) { throw new IllegalStateException("Servlet filter " + getClass().getName() + " is already instantiated"); } instance = this; } @Override public void init(FilterConfig config) { // Filters are already available in the container unless a database migration is required. See // org.sonar.server.startup.RegisterServletFilters. List<ServletFilter> servletFilterList = PlatformImpl.getInstance().getContainer().getComponentsByType(ServletFilter.class); List<HttpFilter> httpFilterList = PlatformImpl.getInstance().getContainer().getComponentsByType(HttpFilter.class); init(config, servletFilterList, httpFilterList); } @CheckForNull public static MasterServletFilter getInstance() { return instance; } @VisibleForTesting static void setInstance(@Nullable MasterServletFilter instance) { MasterServletFilter.instance = instance; } void init(FilterConfig config, List<ServletFilter> filters, List<HttpFilter> httpFilters) { this.config = config; initHttpFilters(httpFilters); initServletFilters(filters); } public void initHttpFilters(List<HttpFilter> filterExtensions) { LinkedList<HttpFilter> filterList = new LinkedList<>(); for (HttpFilter extension : filterExtensions) { try { LOG.info(String.format("Initializing servlet filter %s [pattern=%s]", extension, extension.doGetPattern().label())); extension.init(); // As for scim we need to intercept traffic to URLs with path parameters // and that use is not properly handled when dealing with inclusions/exclusions of the WebServiceFilter, // we need to make sure the Scim filters are invoked before the WebserviceFilter if (isScimFilter(extension)) { filterList.addFirst(extension); } else { filterList.addLast(extension); } } catch (Exception e) { throw new IllegalStateException("Fail to initialize servlet filter: " + extension + ". Message: " + e.getMessage(), e); } } httpFilters = filterList.toArray(new HttpFilter[0]); } private static boolean isScimFilter(HttpFilter extension) { return extension.doGetPattern().getInclusions().stream() .anyMatch(s -> s.startsWith(SCIM_FILTER_PATH)); } @Deprecated(forRemoval = true) public void initServletFilters(List<ServletFilter> filterExtensions) { LinkedList<ServletFilter> filterList = new LinkedList<>(); for (ServletFilter extension : filterExtensions) { try { LOG.info(String.format("Initializing servlet filter %s [pattern=%s]", extension, extension.doGetPattern().label())); extension.init(config); // adding deprecated extensions as last filterList.addLast(extension); } catch (Exception e) { throw new IllegalStateException("Fail to initialize servlet filter: " + extension + ". Message: " + e.getMessage(), e); } } filters = filterList.toArray(new ServletFilter[0]); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest hsr = (HttpServletRequest) request; if (filters.length == 0 && httpFilters.length == 0) { chain.doFilter(hsr, response); } else { String path = hsr.getRequestURI().replaceFirst(hsr.getContextPath(), ""); GodFilterChain godChain = new GodFilterChain(chain); buildGodchain(path, godChain); godChain.doFilter(hsr, response); } } private void buildGodchain(String path, GodFilterChain godChain) { Arrays.stream(httpFilters) .filter(filter -> filter.doGetPattern().matches(path)) .forEachOrdered(godChain::addFilter); Arrays.stream(filters) .filter(filter -> filter.doGetPattern().matches(path)) .forEachOrdered(godChain::addFilter); } @Override public void destroy() { for (ServletFilter filter : filters) { filter.destroy(); } for (HttpFilter filter : httpFilters) { filter.destroy(); } } @VisibleForTesting ServletFilter[] getFilters() { return filters; } @VisibleForTesting HttpFilter[] getHttpFilters() { return httpFilters; } private static final class GodFilterChain implements FilterChain { private final FilterChain chain; private final List<Filter> filters = new LinkedList<>(); private Iterator<Filter> iterator; public GodFilterChain(FilterChain chain) { this.chain = chain; } @Override public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException { if (iterator == null) { iterator = filters.iterator(); } if (iterator.hasNext()) { Filter next = iterator.next(); next.doFilter(request, response, this); } else { chain.doFilter(request, response); } } @Deprecated(forRemoval = true) public void addFilter(Filter filter) { Preconditions.checkState(iterator == null); filters.add(filter); } public void addFilter(HttpFilter filter) { Preconditions.checkState(iterator == null); filters.add(new JavaxFilterAdapter(filter)); } } private static class JavaxFilterAdapter implements Filter { private final HttpFilter httpFilter; JavaxFilterAdapter(HttpFilter httpFilter) { this.httpFilter = httpFilter; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpRequest javaxHttpRequest = new JavaxHttpRequest((HttpServletRequest) servletRequest); HttpResponse javaxHttpResponse = new JavaxHttpResponse((HttpServletResponse) servletResponse); httpFilter.doFilter(javaxHttpRequest, javaxHttpResponse, new HttpFilterChainAdapter(chain)); } } private static class HttpFilterChainAdapter implements org.sonar.api.web.FilterChain { private final FilterChain filterChain; HttpFilterChainAdapter(FilterChain filterChain) { this.filterChain = filterChain; } @Override public void doFilter(HttpRequest httpRequest, HttpResponse httpResponse) throws IOException { try { filterChain.doFilter(((JavaxHttpRequest) httpRequest).getDelegate(), ((JavaxHttpResponse) httpResponse).getDelegate()); } catch (ServletException e) { throw new RuntimeException(e); } } } }
8,857
34.717742
146
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/PlatformServletContextListener.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.util.Enumeration; import java.util.Properties; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.server.platform.PlatformImpl; public final class PlatformServletContextListener implements ServletContextListener { static final String STARTED_ATTRIBUTE = "sonarqube.started"; private static final Logger LOG = LoggerFactory.getLogger(PlatformServletContextListener.class); @Override public void contextInitialized(ServletContextEvent event) { try { Properties props = new Properties(); ServletContext servletContext = event.getServletContext(); Enumeration<String> paramKeys = servletContext.getInitParameterNames(); while (paramKeys.hasMoreElements()) { String key = paramKeys.nextElement(); props.put(key, servletContext.getInitParameter(key)); } PlatformImpl.getInstance().init(props, servletContext); PlatformImpl.getInstance().doStart(); event.getServletContext().setAttribute(STARTED_ATTRIBUTE, Boolean.TRUE); } catch (org.sonar.api.utils.MessageException | org.sonar.process.MessageException e) { LOG.error("Web server startup failed: {}", e.getMessage()); stopQuietly(); } catch (Throwable t) { LOG.error("Web server startup failed", t); stopQuietly(); throw new AbortTomcatStartException(); } } private static void stopQuietly() { try { PlatformImpl.getInstance().doStop(); } catch (Exception e) { // ignored, but an error during startup generally prevents pico to be correctly stopped } } @Override public void contextDestroyed(ServletContextEvent event) { PlatformImpl.getInstance().doStop(); } }
2,712
36.680556
98
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/RedirectFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static java.lang.String.format; public class RedirectFilter implements Filter { private static final String EMPTY = ""; private static final List<Redirect> REDIRECTS = List.of( newSimpleRedirect("/api", "/api/webservices/list") ); @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; String path = extractPath(request); Predicate<Redirect> match = redirect -> redirect.test(path); List<Redirect> redirects = REDIRECTS.stream() .filter(match) .toList(); switch (redirects.size()) { case 0: chain.doFilter(request, response); break; case 1: response.sendRedirect(redirects.get(0).apply(request)); break; default: throw new IllegalStateException(format("Multiple redirects have been found for '%s'", path)); } } public static Redirect newSimpleRedirect(String from, String to) { return new Redirect() { @Override public boolean test(String path) { return from.equals(path); } @Override public String apply(HttpServletRequest request) { return format("%s%s", request.getContextPath(), to); } }; } @Override public void init(FilterConfig filterConfig) { // Nothing } @Override public void destroy() { // Nothing } private interface Redirect extends Predicate<String>, Function<HttpServletRequest, String> { @Override boolean test(String path); @Override String apply(HttpServletRequest request); } private static String extractPath(HttpServletRequest request) { return sanitizePath(request.getRequestURI().replaceFirst(request.getContextPath(), EMPTY)); } private static String sanitizePath(String path) { if (path.length() > 1 && path.endsWith("/")) { return path.substring(0, path.length() - 1); } return path; } }
3,428
30.458716
144
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/RegisterServletFilters.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.util.Arrays; import org.sonar.api.Startable; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.ServletFilter; import org.springframework.beans.factory.annotation.Autowired; /** * @since 3.5 */ public class RegisterServletFilters implements Startable { private final ServletFilter[] servletFilters; private final HttpFilter[] httpFilters; @Autowired(required = false) @Deprecated(since = "10.1", forRemoval = true) public RegisterServletFilters(ServletFilter[] servletFilters, HttpFilter[] httpFilters) { this.servletFilters = servletFilters; this.httpFilters = httpFilters; } @Autowired(required = false) public RegisterServletFilters(HttpFilter[] httpFilters) { this(new ServletFilter[0], httpFilters); } @Autowired(required = false) public RegisterServletFilters() { this(new ServletFilter[0], new HttpFilter[0]); } @Override public void start() { MasterServletFilter masterServletFilter = MasterServletFilter.getInstance(); if (masterServletFilter != null) { // Probably a database upgrade. MasterSlaveFilter was instantiated by the servlet container // while spring was not completely up. // See https://jira.sonarsource.com/browse/SONAR-3612 masterServletFilter.initHttpFilters(Arrays.asList(httpFilters)); masterServletFilter.initServletFilters(Arrays.asList(servletFilters)); } } @Override public void stop() { // nothing to do } }
2,352
33.101449
97
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/RequestIdFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.sonar.server.platform.Platform; import org.sonar.server.platform.PlatformImpl; import org.sonar.server.platform.web.requestid.RequestIdGenerator; import org.sonar.server.platform.web.requestid.RequestIdMDCStorage; /** * A {@link Filter} that puts and removes the HTTP request ID from the {@link org.slf4j.MDC}. */ public class RequestIdFilter implements Filter { private final Platform platform; public RequestIdFilter() { this(PlatformImpl.getInstance()); } @VisibleForTesting RequestIdFilter(Platform platform) { this.platform = platform; } @Override public void init(FilterConfig filterConfig) { // nothing to do } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { var requestIdGenerator = platform.getContainer().getOptionalComponentByType(RequestIdGenerator.class); if (requestIdGenerator.isEmpty()) { chain.doFilter(request, response); } else { String requestId = requestIdGenerator.get().generate(); try (RequestIdMDCStorage mdcStorage = new RequestIdMDCStorage(requestId)) { request.setAttribute("ID", requestId); chain.doFilter(request, response); } } } @Override public void destroy() { // nothing to do } }
2,510
31.61039
130
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/SecurityServletFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import java.util.Set; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * This servlet filter sets response headers that enable browser protection against several classes if Web attacks. */ public class SecurityServletFilter implements Filter { private static final Set<String> ALLOWED_HTTP_METHODS = Set.of("DELETE", "GET", "HEAD", "POST", "PUT", "PATCH"); @Override public void init(FilterConfig filterConfig) { // nothing } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { doHttpFilter((HttpServletRequest) req, (HttpServletResponse) resp, chain); } private static void doHttpFilter(HttpServletRequest httpRequest, HttpServletResponse httpResponse, FilterChain chain) throws IOException, ServletException { // SONAR-6881 Disable OPTIONS and TRACE methods if (!ALLOWED_HTTP_METHODS.contains(httpRequest.getMethod())) { httpResponse.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); return; } // WARNING, headers must be added before the doFilter, otherwise they won't be added when response is already committed (for instance when a WS is called) addSecurityHeaders(httpRequest, httpResponse); chain.doFilter(httpRequest, httpResponse); } /** * Adds security HTTP headers in the response. The headers are added using {@code setHeader()}, which overwrites existing headers. */ public static void addSecurityHeaders(HttpServletRequest httpRequest, HttpServletResponse httpResponse) { if (httpRequest.getRequestURI() == null) { httpResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } // Clickjacking protection // See https://www.owasp.org/index.php/Clickjacking_Protection_for_Java_EE // The protection is disabled on purpose for integration in external systems like Github (/integration/github). String path = httpRequest.getRequestURI().replaceFirst(httpRequest.getContextPath(), ""); if (!path.startsWith("/integration/")) { httpResponse.setHeader("X-Frame-Options", "SAMEORIGIN"); } // If the request is secure, the Strict-Transport-Security header is added. if ("https".equals(httpRequest.getHeader("x-forwarded-proto"))) { httpResponse.setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains;"); } // Cross-site scripting // See https://www.owasp.org/index.php/List_of_useful_HTTP_headers httpResponse.setHeader("X-XSS-Protection", "1; mode=block"); // MIME-sniffing // See https://www.owasp.org/index.php/List_of_useful_HTTP_headers httpResponse.setHeader("X-Content-Type-Options", "nosniff"); } @Override public void destroy() { // nothing } }
3,933
38.737374
158
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/SonarLintConnectionFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import java.util.Locale; import java.util.Optional; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.utils.System2; import org.sonar.api.web.FilterChain; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.UrlPattern; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.server.user.ThreadLocalUserSession; import org.sonar.server.ws.ServletRequest; import static java.util.concurrent.TimeUnit.HOURS; public class SonarLintConnectionFilter extends HttpFilter { private static final UrlPattern URL_PATTERN = UrlPattern.builder() .includes("/api/*") .excludes("/api/v2/*") .build(); private final DbClient dbClient; private final ThreadLocalUserSession userSession; private final System2 system2; public SonarLintConnectionFilter(DbClient dbClient, ThreadLocalUserSession userSession, System2 system2) { this.dbClient = dbClient; this.userSession = userSession; this.system2 = system2; } @Override public UrlPattern doGetPattern() { return URL_PATTERN; } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain chain) throws IOException { ServletRequest wsRequest = new ServletRequest(request); Optional<String> agent = wsRequest.header("User-Agent"); if (agent.isPresent() && agent.get().toLowerCase(Locale.ENGLISH).contains("sonarlint")) { update(); } chain.doFilter(request, response); } public void update() { if (shouldUpdate()) { try (DbSession session = dbClient.openSession(false)) { dbClient.userDao().updateSonarlintLastConnectionDate(session, userSession.getLogin()); session.commit(); } } } private boolean shouldUpdate() { if (!userSession.hasSession() || !userSession.isLoggedIn()) { return false; } long now = system2.now(); Long lastUpdate = userSession.getLastSonarlintConnectionDate(); return (lastUpdate == null || lastUpdate < now - HOURS.toMillis(1L)); } }
2,974
33.195402
108
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/StaticResourcesServlet.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.annotation.CheckForNull; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.connector.ClientAbortException; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.platform.PluginRepository; import org.sonar.core.extension.CoreExtensionRepository; import org.sonar.server.platform.PlatformImpl; import org.sonarqube.ws.MediaTypes; import static java.lang.String.format; import static javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; public class StaticResourcesServlet extends HttpServlet { private static final Logger LOG = LoggerFactory.getLogger(StaticResourcesServlet.class); private static final long serialVersionUID = -2577454614650178426L; private final System system; @VisibleForTesting StaticResourcesServlet(System system) { this.system = system; } public StaticResourcesServlet() { this.system = new System(); } @Override public void doGet(HttpServletRequest request, HttpServletResponse response) { String pluginKey = getPluginKey(request); String resource = getResourcePath(request); InputStream in = null; OutputStream out = null; try { CoreExtensionRepository coreExtensionRepository = system.getCoreExtensionRepository(); PluginRepository pluginRepository = system.getPluginRepository(); boolean coreExtension = coreExtensionRepository.isInstalled(pluginKey); if (!coreExtension && !pluginRepository.hasPlugin(pluginKey)) { silentlySendError(response, SC_NOT_FOUND); return; } in = coreExtension ? system.openCoreExtensionResourceStream(resource) : system.openPluginResourceStream(pluginKey, resource, pluginRepository); if (in == null) { silentlySendError(response, SC_NOT_FOUND); return; } // mime type must be set before writing response body completeContentType(response, resource); out = response.getOutputStream(); IOUtils.copy(in, out); } catch (ClientAbortException e) { LOG.trace("Client canceled loading resource [{}] from plugin [{}]: {}", resource, pluginKey, e); } catch (Exception e) { LOG.error(format("Unable to load resource [%s] from plugin [%s]", resource, pluginKey), e); silentlySendError(response, SC_INTERNAL_SERVER_ERROR); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } private void silentlySendError(HttpServletResponse response, int error) { if (system.isCommitted(response)) { LOG.trace("Response is committed. Cannot send error response code {}", error); return; } try { system.sendError(response, error); } catch (IOException e) { LOG.trace("Failed to send error code {}: {}", error, e); } } /** * @return part of request URL after servlet path */ private static String getPluginKeyAndResourcePath(HttpServletRequest request) { return StringUtils.substringAfter(request.getRequestURI(), request.getContextPath() + request.getServletPath() + "/"); } private static String getPluginKey(HttpServletRequest request) { return StringUtils.substringBefore(getPluginKeyAndResourcePath(request), "/"); } /** * Note that returned value should not have a leading "/" - see {@link Class#resolveName(String)}. */ private static String getResourcePath(HttpServletRequest request) { return "static/" + StringUtils.substringAfter(getPluginKeyAndResourcePath(request), "/"); } private static void completeContentType(HttpServletResponse response, String filename) { response.setContentType(MediaTypes.getByFilename(filename)); } static class System { PluginRepository getPluginRepository() { return PlatformImpl.getInstance().getContainer().getComponentByType(PluginRepository.class); } CoreExtensionRepository getCoreExtensionRepository() { return PlatformImpl.getInstance().getContainer().getComponentByType(CoreExtensionRepository.class); } @CheckForNull InputStream openPluginResourceStream(String pluginKey, String resource, PluginRepository pluginRepository) throws Exception { ClassLoader pluginClassLoader = pluginRepository.getPluginInstance(pluginKey).getClass().getClassLoader(); return pluginClassLoader.getResourceAsStream(resource); } @CheckForNull InputStream openCoreExtensionResourceStream(String resource) throws Exception { return getClass().getClassLoader().getResourceAsStream(resource); } boolean isCommitted(HttpServletResponse response) { return response.isCommitted(); } void sendError(HttpServletResponse response, int error) throws IOException { response.sendError(error); } } }
6,009
36.5625
149
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/UserSessionFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import javax.annotation.Nullable; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DBSessions; import org.sonar.server.authentication.UserSessionInitializer; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import org.sonar.server.platform.Platform; import org.sonar.server.platform.PlatformImpl; import org.sonar.server.setting.ThreadLocalSettings; public class UserSessionFilter implements Filter { private static final Logger LOG = LoggerFactory.getLogger(UserSessionFilter.class); private final Platform platform; public UserSessionFilter() { this.platform = PlatformImpl.getInstance(); } @VisibleForTesting UserSessionFilter(Platform platform) { this.platform = platform; } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; DBSessions dbSessions = platform.getContainer().getComponentByType(DBSessions.class); ThreadLocalSettings settings = platform.getContainer().getComponentByType(ThreadLocalSettings.class); UserSessionInitializer userSessionInitializer = platform.getContainer().getOptionalComponentByType(UserSessionInitializer.class).orElse(null); LOG.trace("{} serves {}", Thread.currentThread(), request.getRequestURI()); dbSessions.enableCaching(); try { settings.load(); try { doFilter(request, response, chain, userSessionInitializer); } finally { settings.unload(); } } finally { dbSessions.disableCaching(); } } private static void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain, @Nullable UserSessionInitializer userSessionInitializer) throws IOException, ServletException { try { if (userSessionInitializer == null || userSessionInitializer.initUserSession(new JavaxHttpRequest(request), new JavaxHttpResponse(response))) { chain.doFilter(request, response); } } finally { if (userSessionInitializer != null) { userSessionInitializer.removeUserSession(); } } } @Override public void init(FilterConfig filterConfig) { // nothing to do } @Override public void destroy() { // nothing to do } }
3,738
35.656863
149
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/WebPagesCache.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import javax.servlet.ServletContext; import org.apache.commons.io.IOUtils; import org.sonar.server.platform.OfficialDistribution; import org.sonar.server.platform.Platform; import org.sonar.server.platform.Platform.Status; import static com.google.common.base.Preconditions.checkState; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; import static org.sonar.server.platform.Platform.Status.UP; public class WebPagesCache { private static final String WEB_CONTEXT_PLACEHOLDER = "%WEB_CONTEXT%"; private static final String SERVER_STATUS_PLACEHOLDER = "%SERVER_STATUS%"; private static final String INSTANCE_PLACEHOLDER = "%INSTANCE%"; private static final String OFFICIAL_PLACEHOLDER = "%OFFICIAL%"; private static final String SONARQUBE_INSTANCE_VALUE = "SonarQube"; private static final String INDEX_HTML_PATH = "/index.html"; private static final Set<String> HTML_PATHS = Set.of(INDEX_HTML_PATH); private final Platform platform; private final OfficialDistribution officialDistribution; private ServletContext servletContext; private Map<String, String> indexHtmlByPath; private Status status; public WebPagesCache(Platform platform, OfficialDistribution officialDistribution) { this.platform = platform; this.indexHtmlByPath = new HashMap<>(); this.officialDistribution = officialDistribution; } public void init(ServletContext servletContext) { this.servletContext = servletContext; generate(platform.status()); } public String getContent(String path) { String htmlPath = HTML_PATHS.contains(path) ? path : INDEX_HTML_PATH; checkState(servletContext != null, "init has not been called"); // Optimization to not have to call platform.currentStatus on each call if (Objects.equals(status, UP)) { return indexHtmlByPath.get(htmlPath); } Status currentStatus = platform.status(); if (!Objects.equals(status, currentStatus)) { generate(currentStatus); } return indexHtmlByPath.get(htmlPath); } private void generate(Status status) { this.status = status; HTML_PATHS.forEach(path -> indexHtmlByPath.put(path, provide(path))); } private String provide(String path) { getClass().getResourceAsStream(INDEX_HTML_PATH); return loadHtmlFile(path, status.name()); } private String loadHtmlFile(String path, String serverStatus) { try (InputStream input = servletContext.getResourceAsStream(path)) { String template = IOUtils.toString(requireNonNull(input), UTF_8); return template .replace(WEB_CONTEXT_PLACEHOLDER, servletContext.getContextPath()) .replace(SERVER_STATUS_PLACEHOLDER, serverStatus) .replace(INSTANCE_PLACEHOLDER, WebPagesCache.SONARQUBE_INSTANCE_VALUE) .replace(OFFICIAL_PLACEHOLDER, String.valueOf(officialDistribution.check())); } catch (Exception e) { throw new IllegalStateException("Fail to load file " + path, e); } } }
4,003
36.773585
86
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/WebPagesFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.sonar.api.web.ServletFilter; import org.sonar.server.platform.PlatformImpl; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Locale.ENGLISH; import static java.util.Objects.requireNonNull; import static org.apache.commons.io.IOUtils.write; import static org.sonar.api.impl.ws.StaticResources.patterns; import static org.sonarqube.ws.MediaTypes.HTML; /** * This filter provide the HTML file that will be used to display every web pages. * The same file should be provided for any URLs except WS and static resources. */ public class WebPagesFilter implements Filter { private static final String CACHE_CONTROL_HEADER = "Cache-Control"; private static final String CACHE_CONTROL_VALUE = "no-cache, no-store, must-revalidate"; private static final ServletFilter.UrlPattern URL_PATTERN = ServletFilter.UrlPattern .builder() .excludes(patterns()) .excludes("/api/v2/*") .build(); private WebPagesCache webPagesCache; public WebPagesFilter() { this(PlatformImpl.getInstance().getContainer().getComponentByType(WebPagesCache.class)); } @VisibleForTesting WebPagesFilter(WebPagesCache webPagesCache) { this.webPagesCache = webPagesCache; } @Override public void init(FilterConfig filterConfig) { webPagesCache.init(filterConfig.getServletContext()); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String path = httpServletRequest.getRequestURI().replaceFirst(httpServletRequest.getContextPath(), ""); if (!URL_PATTERN.matches(path)) { chain.doFilter(request, response); return; } httpServletResponse.setContentType(HTML); httpServletResponse.setCharacterEncoding(UTF_8.name().toLowerCase(ENGLISH)); httpServletResponse.setHeader(CACHE_CONTROL_HEADER, CACHE_CONTROL_VALUE); String htmlContent = requireNonNull(webPagesCache.getContent(path)); write(htmlContent, httpServletResponse.getOutputStream(), UTF_8); } @Override public void destroy() { // Nothing to do } }
3,540
36.670213
130
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/WebServiceFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.util.HashSet; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.FilterChain; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.UrlPattern; import org.sonar.server.ws.ServletFilterHandler; import org.sonar.server.ws.ServletRequest; import org.sonar.server.ws.ServletResponse; import org.sonar.server.ws.WebServiceEngine; import static java.util.stream.Collectors.toCollection; import static java.util.stream.Stream.concat; import static org.sonar.server.platform.web.WebServiceReroutingFilter.MOVED_WEB_SERVICES; /** * This filter is used to execute Web Services. * * Every urls beginning with '/api' and every web service urls are taken into account, except : * <ul> * <li>web services that directly implemented with servlet filter, see {@link ServletFilterHandler})</li> * </ul> */ public class WebServiceFilter extends HttpFilter { private final WebServiceEngine webServiceEngine; private final Set<String> includeUrls; private final Set<String> excludeUrls; public WebServiceFilter(WebServiceEngine webServiceEngine) { this.webServiceEngine = webServiceEngine; this.includeUrls = concat( Stream.of("/api/*"), webServiceEngine.controllers().stream() .flatMap(controller -> controller.actions().stream()) .map(toPath())) .collect(Collectors.toSet()); this.excludeUrls = concat(MOVED_WEB_SERVICES.stream(), webServiceEngine.controllers().stream() .flatMap(controller -> controller.actions().stream()) .filter(action -> action.handler() instanceof ServletFilterHandler) .map(toPath())).collect(toCollection(HashSet::new)); excludeUrls.add("/api/v2/*"); } @Override public UrlPattern doGetPattern() { return UrlPattern.builder() .includes(includeUrls) .excludes(excludeUrls) .build(); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain filterChain) { ServletRequest wsRequest = new ServletRequest(request); ServletResponse wsResponse = new ServletResponse(response); webServiceEngine.execute(wsRequest, wsResponse); } private static Function<WebService.Action, String> toPath() { return action -> "/" + action.path() + ".*"; } }
3,374
35.684783
107
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/WebServiceReroutingFilter.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.util.Map; import java.util.Set; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.web.FilterChain; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.UrlPattern; import org.sonar.server.ws.ServletRequest; import org.sonar.server.ws.ServletResponse; import org.sonar.server.ws.WebServiceEngine; /** * This filter is used to execute renamed/moved web services */ public class WebServiceReroutingFilter extends HttpFilter { private static final Map<String, String> REDIRECTS = Map.of( "/api/components/bulk_update_key", "/api/projects/bulk_update_key", "/api/components/update_key", "/api/projects/update_key"); static final Set<String> MOVED_WEB_SERVICES = REDIRECTS.keySet(); private final WebServiceEngine webServiceEngine; public WebServiceReroutingFilter(WebServiceEngine webServiceEngine) { this.webServiceEngine = webServiceEngine; } @Override public UrlPattern doGetPattern() { return UrlPattern.builder() .includes(MOVED_WEB_SERVICES) .build(); } @Override public void doFilter(HttpRequest request, HttpResponse response, FilterChain filterChain) { RedirectionRequest wsRequest = new RedirectionRequest(request); ServletResponse wsResponse = new ServletResponse(response); webServiceEngine.execute(wsRequest, wsResponse); } @Override public void init() { // Nothing to do } @Override public void destroy() { // Nothing to do } private static class RedirectionRequest extends ServletRequest { private final String redirectedPath; public RedirectionRequest(HttpRequest source) { super(source); this.redirectedPath = REDIRECTS.getOrDefault(source.getServletPath(), source.getServletPath()); } @Override public String getPath() { return redirectedPath; } } }
2,773
30.522727
101
java
sonarqube
sonarqube-master/server/sonar-webserver/src/main/java/org/sonar/server/platform/web/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.web; import javax.annotation.ParametersAreNonnullByDefault;
969
39.416667
75
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/EmbeddedTomcatTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.net.ConnectException; import java.net.InetAddress; import java.net.URL; import java.util.Properties; import org.apache.commons.io.FileUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.process.NetworkUtilsImpl; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class EmbeddedTomcatTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void start() throws Exception { Props props = new Props(new Properties()); // prepare file system File home = temp.newFolder(); File data = temp.newFolder(); File webDir = new File(home, "web"); FileUtils.write(new File(home, "web/WEB-INF/web.xml"), "<web-app/>"); props.set("sonar.path.home", home.getAbsolutePath()); props.set("sonar.path.data", data.getAbsolutePath()); props.set("sonar.path.web", webDir.getAbsolutePath()); props.set("sonar.path.logs", temp.newFolder().getAbsolutePath()); // start server on a random port InetAddress address = InetAddress.getLoopbackAddress(); int httpPort = NetworkUtilsImpl.INSTANCE.getNextLoopbackAvailablePort(); props.set("sonar.web.host", address.getHostAddress()); props.set("sonar.web.port", String.valueOf(httpPort)); EmbeddedTomcat tomcat = new EmbeddedTomcat(props); assertThat(tomcat.getStatus()).isEqualTo(EmbeddedTomcat.Status.DOWN); tomcat.start(); assertThat(tomcat.getStatus()).isEqualTo(EmbeddedTomcat.Status.UP); // check that http connector accepts requests URL url = new URL("http://" + address.getHostAddress() + ":" + httpPort); url.openConnection().connect(); // stop server tomcat.terminate(); // tomcat.isUp() must not be called. It is used to wait for server startup, not shutdown. try { url.openConnection().connect(); fail(); } catch (ConnectException e) { // expected } } }
2,901
34.82716
93
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/NullJarScannerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.apache.tomcat.JarScanFilter; import org.apache.tomcat.JarScanType; import org.apache.tomcat.JarScannerCallback; import org.junit.Test; import javax.servlet.ServletContext; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; public class NullJarScannerTest { @Test public void does_nothing() { ServletContext context = mock(ServletContext.class); JarScannerCallback callback = mock(JarScannerCallback.class); NullJarScanner scanner = new NullJarScanner(); scanner.scan(JarScanType.PLUGGABILITY, context, callback); verifyNoInteractions(context, callback); scanner.setJarScanFilter(mock(JarScanFilter.class)); assertThat(scanner.getJarScanFilter()).isNull(); } }
1,687
34.914894
75
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/ProgrammaticLogbackValveTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.apache.catalina.Container; import org.junit.AfterClass; import org.junit.Test; import org.sonar.process.logging.LogbackHelper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class ProgrammaticLogbackValveTest { @AfterClass public static void resetLogback() throws Exception { new LogbackHelper().resetFromXml("/logback-test.xml"); } @Test public void startInternal() throws Exception { ProgrammaticLogbackValve valve = new ProgrammaticLogbackValve(); valve.setContainer(mock(Container.class)); valve.start(); assertThat(valve.isStarted()).isTrue(); valve.stop(); assertThat(valve.isStarted()).isFalse(); } }
1,598
30.98
75
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/SecurityErrorReportValveTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.IOException; import javax.servlet.ServletException; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.valves.ValveBase; import org.junit.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class SecurityErrorReportValveTest { SecureErrorReportValve underTest = spy(SecureErrorReportValve.class); @Test public void add_security_headers() throws ServletException, IOException { var request = mock(Request.class); var response = mock(Response.class); underTest.setNext(new ValveBase() { @Override public void invoke(Request request, Response response) { } }); when(request.getMethod()).thenReturn("GET"); when(request.getRequestURI()).thenReturn("/"); when(request.getContextPath()).thenReturn(""); when(request.getHeader("x-forwarded-proto")).thenReturn("https"); underTest.invoke(request, response); verify(response).setHeader("X-Frame-Options", "SAMEORIGIN"); verify(response).setHeader("X-XSS-Protection", "1; mode=block"); verify(response).setHeader("X-Content-Type-Options", "nosniff"); verify(response).setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains;"); } }
2,258
35.435484
100
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/StartupLogsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.apache.catalina.connector.Connector; import org.apache.catalina.startup.Tomcat; import org.junit.Test; import org.mockito.Mockito; import org.slf4j.Logger; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class StartupLogsTest { private Tomcat tomcat = mock(Tomcat.class, Mockito.RETURNS_DEEP_STUBS); private Logger logger = mock(Logger.class); private TomcatStartupLogs underTest = new TomcatStartupLogs(logger); @Test public void fail_with_IAE_on_unsupported_protocol() { Connector connector = newConnector("AJP/1.3", "ajp"); when(tomcat.getService().findConnectors()).thenReturn(new Connector[] {connector}); assertThatThrownBy(() -> underTest.log(tomcat)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("Unsupported connector: Connector[AJP/1.3-1234]"); } @Test public void logHttp() { Connector connector = newConnector("HTTP/1.1", "http"); when(tomcat.getService().findConnectors()).thenReturn(new Connector[] {connector}); underTest.log(tomcat); verify(logger).info("HTTP connector enabled on port 1234"); verifyNoMoreInteractions(logger); } @Test public void unsupported_connector() { Connector connector = mock(Connector.class, Mockito.RETURNS_DEEP_STUBS); when(connector.getProtocol()).thenReturn("SPDY/1.1"); when(connector.getScheme()).thenReturn("spdy"); when(tomcat.getService().findConnectors()).thenReturn(new Connector[] {connector}); try { underTest.log(tomcat); fail(); } catch (IllegalArgumentException e) { // expected } } private Connector newConnector(String protocol, String schema) { Connector httpConnector = new Connector(protocol); httpConnector.setScheme(schema); httpConnector.setPort(1234); return httpConnector; } }
2,941
34.445783
87
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/TomcatAccessLogTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.Properties; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.startup.Tomcat; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.mockito.Mockito; import org.slf4j.Logger; import org.sonar.process.Props; import static org.mockito.Mockito.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; public class TomcatAccessLogTest { TomcatAccessLog underTest = new TomcatAccessLog(); @Rule public TemporaryFolder temp = new TemporaryFolder(); @Before public void setHome() throws IOException { File homeDir = temp.newFolder("home"); System.setProperty("SONAR_HOME", homeDir.getAbsolutePath()); } @Test public void enable_access_logs_by_Default() throws Exception { Tomcat tomcat = mock(Tomcat.class, Mockito.RETURNS_DEEP_STUBS); Props props = new Props(new Properties()); props.set(PATH_LOGS.getKey(), temp.newFolder().getAbsolutePath()); underTest.configure(tomcat, props); verify(tomcat.getHost().getPipeline()).addValve(any(ProgrammaticLogbackValve.class)); } @Test public void log_when_started_and_stopped() { Logger logger = mock(Logger.class); TomcatAccessLog.LifecycleLogger listener = new TomcatAccessLog.LifecycleLogger(logger); LifecycleEvent event = new LifecycleEvent(mock(Lifecycle.class), "before_init", null); listener.lifecycleEvent(event); verifyNoInteractions(logger); event = new LifecycleEvent(mock(Lifecycle.class), "after_start", null); listener.lifecycleEvent(event); verify(logger).debug("Tomcat is started"); event = new LifecycleEvent(mock(Lifecycle.class), "after_destroy", null); listener.lifecycleEvent(event); verify(logger).debug("Tomcat is stopped"); } }
2,915
34.13253
91
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/TomcatConnectorsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 com.google.common.collect.ImmutableMap; import java.net.InetAddress; import java.util.Map; import java.util.Properties; import org.apache.catalina.startup.Tomcat; import org.junit.Test; import org.mockito.Mockito; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class TomcatConnectorsTest { private static final int DEFAULT_PORT = 9000; private Tomcat tomcat = mock(Tomcat.class, Mockito.RETURNS_DEEP_STUBS); @Test public void configure_thread_pool() { Properties p = new Properties(); p.setProperty("sonar.web.http.minThreads", "2"); p.setProperty("sonar.web.http.maxThreads", "30"); p.setProperty("sonar.web.http.acceptCount", "20"); Props props = new Props(p); TomcatConnectors.configure(tomcat, props); verifyHttpConnector(DEFAULT_PORT, ImmutableMap.of("minSpareThreads", 2, "maxThreads", 30, "acceptCount", 20)); } @Test public void configure_defaults() { Props props = new Props(new Properties()); TomcatConnectors.configure(tomcat, props); verifyHttpConnector(DEFAULT_PORT, ImmutableMap.of("minSpareThreads", 5, "maxThreads", 50, "acceptCount", 25)); } @Test public void different_thread_pools_for_connectors() { Properties p = new Properties(); p.setProperty("sonar.web.http.minThreads", "2"); Props props = new Props(p); TomcatConnectors.configure(tomcat, props); verifyHttpConnector(DEFAULT_PORT, ImmutableMap.of("minSpareThreads", 2)); } @Test public void fail_with_ISE_if_http_port_is_invalid() { Properties p = new Properties(); p.setProperty("sonar.web.port", "-1"); try { TomcatConnectors.configure(tomcat, new Props(p)); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("HTTP port '-1' is invalid"); } } @Test public void bind_to_all_addresses_by_default() { Properties p = new Properties(); p.setProperty("sonar.web.port", "9000"); TomcatConnectors.configure(tomcat, new Props(p)); verify(tomcat.getService()).addConnector(argThat(c -> c.getScheme().equals("http") && c.getPort() == 9000 && ((InetAddress) c.getProperty("address")).getHostAddress().equals("0.0.0.0"))); } @Test public void bind_to_specific_address() { Properties p = new Properties(); p.setProperty("sonar.web.port", "9000"); p.setProperty("sonar.web.host", "1.2.3.4"); TomcatConnectors.configure(tomcat, new Props(p)); verify(tomcat.getService()) .addConnector(argThat(c -> c.getScheme().equals("http") && c.getPort() == 9000 && ((InetAddress) c.getProperty("address")).getHostAddress().equals("1.2.3.4"))); } @Test public void test_max_http_header_size_for_http_connection() { TomcatConnectors.configure(tomcat, new Props(new Properties())); verifyHttpConnector(DEFAULT_PORT, ImmutableMap.of("maxHttpHeaderSize", TomcatConnectors.MAX_HTTP_HEADER_SIZE_BYTES)); } @Test public void test_max_post_size_for_http_connection() { Properties properties = new Properties(); Props props = new Props(properties); TomcatConnectors.configure(tomcat, props); verify(tomcat.getService()).addConnector(argThat(c -> c.getMaxPostSize() == -1)); } private void verifyHttpConnector(int expectedPort, Map<String, Object> expectedProps) { verify(tomcat.getService()).addConnector(argThat(c -> { if (!c.getScheme().equals("http")) { return false; } if (!c.getProtocol().equals(TomcatConnectors.HTTP_PROTOCOL)) { return false; } if (c.getPort() != expectedPort) { return false; } for (Map.Entry<String, Object> expectedProp : expectedProps.entrySet()) { if (!expectedProp.getValue().equals(c.getProperty(expectedProp.getKey()))) { return false; } } return true; })); } }
4,911
32.643836
191
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/TomcatContextsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.Properties; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; 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.utils.MessageException; import org.sonar.process.Props; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property; public class TomcatContextsTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); Tomcat tomcat = mock(Tomcat.class); Properties props = new Properties(); TomcatContexts underTest = new TomcatContexts(); @Before public void setUp() throws Exception { props.setProperty(Property.PATH_DATA.getKey(), temp.newFolder("data").getAbsolutePath()); when(tomcat.addWebapp(anyString(), anyString())).thenReturn(mock(StandardContext.class)); } @Test public void configure_root_webapp() { props.setProperty("foo", "bar"); StandardContext context = mock(StandardContext.class); when(tomcat.addWebapp(anyString(), anyString())).thenReturn(context); underTest.configure(tomcat, new Props(props)); // configure webapp with properties verify(context).addParameter("foo", "bar"); } @Test public void create_dir_and_configure_static_directory() throws Exception { File dir = temp.newFolder(); dir.delete(); underTest.addStaticDir(tomcat, "/deploy", dir); assertThat(dir).isDirectory().exists(); verify(tomcat).addWebapp("/deploy", dir.getAbsolutePath()); } @Test public void cleanup_static_directory_if_already_exists() throws Exception { File dir = temp.newFolder(); FileUtils.touch(new File(dir, "foo.txt")); underTest.addStaticDir(tomcat, "/deploy", dir); assertThat(dir).isDirectory() .exists() .isEmptyDirectory(); } @Test public void fail_if_static_directory_can_not_be_initialized() throws Exception { File dir = temp.newFolder(); TomcatContexts.Fs fs = mock(TomcatContexts.Fs.class); doThrow(new IOException()).when(fs).createOrCleanupDir(any(File.class)); assertThatThrownBy(() -> new TomcatContexts(fs).addStaticDir(tomcat, "/deploy", dir)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Fail to create or clean-up directory " + dir.getAbsolutePath()); } @Test public void context_path() { props.setProperty("sonar.web.context", "/foo"); assertThat(TomcatContexts.getContextPath(new Props(props))).isEqualTo("/foo"); } @Test public void context_path_must_start_with_slash() { props.setProperty("sonar.web.context", "foo"); assertThatThrownBy(() -> underTest.configure(tomcat, new Props(props))) .isInstanceOf(MessageException.class) .hasMessageContaining("Value of 'sonar.web.context' must start with a forward slash: 'foo'"); } @Test public void root_context_path_must_be_blank() { props.setProperty("sonar.web.context", "/"); assertThat(TomcatContexts.getContextPath(new Props(props))).isEmpty(); } @Test public void default_context_path_is_root() { String context = TomcatContexts.getContextPath(new Props(new Properties())); assertThat(context).isEmpty(); } }
4,549
32.211679
99
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/TomcatErrorHandlingTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.apache.catalina.startup.Tomcat; import org.apache.catalina.valves.ErrorReportValve; import org.junit.Test; import org.mockito.Mockito; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class TomcatErrorHandlingTest { private final TomcatErrorHandling underTest = new TomcatErrorHandling(); @Test public void configure_shouldAddErrorValve() { Tomcat tomcat = mock(Tomcat.class, Mockito.RETURNS_DEEP_STUBS); underTest.configure(tomcat); verify(tomcat.getHost().getPipeline()).addValve(any(ErrorReportValve.class)); } }
1,512
35.902439
81
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/WebSecurityManagerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.util.Properties; import org.junit.Test; import org.sonar.process.PluginFileWriteRule; import org.sonar.process.PluginSecurityManager; import org.sonar.process.Props; import static org.junit.Assert.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; public class WebSecurityManagerTest { private final PluginSecurityManager pluginSecurityManager = mock(PluginSecurityManager.class); @Test public void apply_calls_PluginSecurityManager() { Properties properties = new Properties(); properties.setProperty(PATH_HOME.getKey(), "home"); properties.setProperty(PATH_TEMP.getKey(), "temp"); Props props = new Props(properties); WebSecurityManager securityManager = new WebSecurityManager(pluginSecurityManager, props); securityManager.apply(); verify(pluginSecurityManager).restrictPlugins(any(PluginFileWriteRule.class)); } @Test public void fail_if_runs_twice() { Properties properties = new Properties(); properties.setProperty(PATH_HOME.getKey(), "home"); properties.setProperty(PATH_TEMP.getKey(), "temp"); Props props = new Props(properties); WebSecurityManager securityManager = new WebSecurityManager(pluginSecurityManager, props); securityManager.apply(); assertThrows(IllegalStateException.class, securityManager::apply); } }
2,422
38.721311
96
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/app/WebServerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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 org.junit.Assert; import org.junit.Test; import org.junit.function.ThrowingRunnable; public class WebServerTest { @Test public void main_givenNoArguments() { String[] arguments = {}; ThrowingRunnable runnable = () -> WebServer.main(arguments); Assert.assertThrows("Only a single command-line argument is accepted (absolute path to configuration file)", IllegalArgumentException.class, runnable); } }
1,309
33.473684
112
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/platformlevel/PlatformLevel1Test.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import java.util.Properties; import org.junit.Test; import org.sonar.server.platform.Platform; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class PlatformLevel1Test { private final PlatformLevel1 underTest = new PlatformLevel1(mock(Platform.class), new Properties()); @Test public void no_missing_dependencies_between_components() { underTest.configureLevel(); assertThat(underTest.getContainer().context().getBeanDefinitionNames()).isNotEmpty(); } }
1,426
33.804878
102
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/platformlevel/PlatformLevel2Test.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import java.util.Optional; import java.util.Properties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.core.platform.SpringComponentContainer; import org.sonar.server.platform.NodeInformation; import org.sonar.server.platform.db.migration.charset.DatabaseCharsetChecker; import org.sonar.server.plugins.ServerPluginRepository; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; public class PlatformLevel2Test { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); private Properties props = new Properties(); @Before public void setUp() throws Exception { // these are mandatory settings declared by bootstrap process props.setProperty(PATH_HOME.getKey(), tempFolder.newFolder().getAbsolutePath()); props.setProperty(PATH_DATA.getKey(), tempFolder.newFolder().getAbsolutePath()); props.setProperty(PATH_TEMP.getKey(), tempFolder.newFolder().getAbsolutePath()); } @Test public void add_all_components_by_default() { var parentContainer = mock(SpringComponentContainer.class); var container = mock(SpringComponentContainer.class); var platform = mock(PlatformLevel.class); var webserver = mock(NodeInformation.class); when(parentContainer.createChild()).thenReturn(container); when(platform.getContainer()).thenReturn(parentContainer); when(parentContainer.getOptionalComponentByType(any())).thenReturn(Optional.empty()); when(container.getOptionalComponentByType(NodeInformation.class)).thenReturn(Optional.of(webserver)); when(webserver.isStartupLeader()).thenReturn(true); PlatformLevel2 underTest = new PlatformLevel2(platform); underTest.configure(); verify(container).add(ServerPluginRepository.class); verify(container).add(DatabaseCharsetChecker.class); verify(container, times(21)).add(any()); } @Test public void do_not_add_all_components_when_startup_follower() { var parentContainer = mock(SpringComponentContainer.class); var container = mock(SpringComponentContainer.class); var platform = mock(PlatformLevel.class); var webserver = mock(NodeInformation.class); when(parentContainer.createChild()).thenReturn(container); when(platform.getContainer()).thenReturn(parentContainer); when(parentContainer.getOptionalComponentByType(any())).thenReturn(Optional.empty()); when(container.getOptionalComponentByType(NodeInformation.class)).thenReturn(Optional.of(webserver)); when(webserver.isStartupLeader()).thenReturn(false); PlatformLevel2 underTest = new PlatformLevel2(platform); underTest.configure(); verify(container).add(ServerPluginRepository.class); verify(container, never()).add(DatabaseCharsetChecker.class); verify(container, times(19)).add(any()); } }
4,138
39.578431
105
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/platformlevel/PlatformLevelTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.platformlevel; import java.util.Random; import java.util.stream.IntStream; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sonar.server.platform.NodeInformation; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class PlatformLevelTest { private final PlatformLevel underTest = new PlatformLevel("name") { @Override protected void configureLevel() { } }; @Before public void setUp() { underTest.start(); } @After public void tearDown() { // clean up for next test underTest.stop(); } @Test public void addIfStartupLeader_throws_ISE_if_container_does_not_have_WebServer_object() { assertThatThrownBy(underTest::addIfStartupLeader) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("WebServer not available in the container"); } @Test public void addIfStartupLeader_always_returns_the_same_instance() { underTest.add(mock(NodeInformation.class)); PlatformLevel.AddIfStartupLeader addIfStartupLeader = underTest.addIfStartupLeader(); IntStream.range(0, 1 + new Random().nextInt(4)).forEach(i -> assertThat(underTest.addIfStartupLeader()).isSameAs(addIfStartupLeader)); } @Test public void addIfCluster_throws_ISE_if_container_does_not_have_WebServer_object() { assertThatThrownBy(underTest::addIfCluster) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("WebServer not available in the container"); } @Test public void addIfCluster_always_returns_the_same_instance() { underTest.add(mock(NodeInformation.class)); PlatformLevel.AddIfCluster addIfCluster = underTest.addIfCluster(); IntStream.range(0, 1 + new Random().nextInt(4)).forEach(i -> assertThat(underTest.addIfCluster()).isSameAs(addIfCluster)); } @Test public void addIfStandalone_throws_ISE_if_container_does_not_have_WebServer_object() { assertThatThrownBy(underTest::addIfCluster) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("WebServer not available in the container"); } @Test public void addIfStandalone_always_returns_the_same_instance() { underTest.add(mock(NodeInformation.class)); PlatformLevel.AddIfCluster addIfCluster = underTest.addIfCluster(); IntStream.range(0, 1 + new Random().nextInt(4)).forEach(i -> assertThat(underTest.addIfCluster()).isSameAs(addIfCluster)); } }
3,403
33.383838
138
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/ApiV2ServletTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import org.sonar.core.platform.SpringComponentContainer; import org.sonar.server.platform.platformlevel.PlatformLevel; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.web.servlet.DispatcherServlet; import static javax.servlet.http.HttpServletResponse.SC_NOT_FOUND; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doThrow; 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 ApiV2ServletTest { @Test public void getServletConfig_shouldReturnServletConfig() throws ServletException { ApiV2Servlet underTest = new ApiV2Servlet(); ServletConfig mockServletConfig = mock(ServletConfig.class); underTest.init(mockServletConfig); assertThat(underTest.getServletConfig()).isEqualTo(mockServletConfig); } @Test public void getServletInfo_shouldReturnOwnDefinedServletName() { ApiV2Servlet underTest = new ApiV2Servlet(); assertThat(underTest.getServletInfo()) .isEqualTo(ApiV2Servlet.SERVLET_NAME); } @Test public void init_shouldInitDispatcherSafeModeConfig_whenDispatcherHadBeenInitWithoutConfig() throws ServletException { ApiV2Servlet underTest = new ApiV2Servlet(); DispatcherServlet mockDispatcherServletSafeMode = mock(DispatcherServlet.class); underTest.setServletProvider(context -> mockDispatcherServletSafeMode); PlatformLevel mockPlatformLevel = getMockPlatformLevel(); underTest.initDispatcherSafeMode(mockPlatformLevel); ServletConfig mockServletConfig = mock(ServletConfig.class); underTest.init(mockServletConfig); verify(mockDispatcherServletSafeMode, times(1)).init(mockServletConfig); } @Test public void init_shouldInitDispatcherLevel4Config_whenDispatcherHadBeenInitWithoutConfig() throws ServletException { PlatformLevel mockPlatformLevel = getMockPlatformLevel(); ApiV2Servlet underTest = new ApiV2Servlet(); DispatcherServlet mockDispatcherServletLevel4 = mock(DispatcherServlet.class); underTest.setServletProvider(context -> mockDispatcherServletLevel4); underTest.initDispatcherLevel4(mockPlatformLevel); ServletConfig mockServletConfig = mock(ServletConfig.class); underTest.init(mockServletConfig); verify(mockDispatcherServletLevel4, times(1)).init(mockServletConfig); } @Test public void service_shouldDispatchOnRightDispatcher() throws ServletException, IOException { PlatformLevel mockPlatformLevel = getMockPlatformLevel(); ApiV2Servlet underTest = new ApiV2Servlet(); DispatcherServlet mockDispatcherServletSafeMode = mock(DispatcherServlet.class); DispatcherServlet mockDispatcherServletLevel4 = mock(DispatcherServlet.class); underTest.setServletProvider(context -> mockDispatcherServletSafeMode); underTest.init(mock(ServletConfig.class)); underTest.initDispatcherSafeMode(mockPlatformLevel); ServletRequest mockRequest1 = mock(ServletRequest.class); ServletResponse mockResponse1 = mock(ServletResponse.class); underTest.service(mockRequest1, mockResponse1); verify(mockDispatcherServletSafeMode, times(1)).service(mockRequest1, mockResponse1); underTest.setServletProvider(context -> mockDispatcherServletLevel4); underTest.initDispatcherLevel4(mockPlatformLevel); ServletRequest mockRequest2 = mock(ServletRequest.class); ServletResponse mockResponse2 = mock(ServletResponse.class); underTest.service(mockRequest2, mockResponse2); verify(mockDispatcherServletLevel4, times(1)).service(mockRequest2, mockResponse2); } @Test public void service_shouldReturnNotFound_whenDispatchersAreNotAvailable() throws ServletException, IOException { ApiV2Servlet underTest = new ApiV2Servlet(); HttpServletResponse mockResponse = mock(HttpServletResponse.class); underTest.service(mock(ServletRequest.class), mockResponse); verify(mockResponse, times(1)).sendError(SC_NOT_FOUND); } @Test public void initDispatcherServlet_shouldThrowRuntimeException_whenDispatcherInitFails() throws ServletException { PlatformLevel mockPlatformLevel = getMockPlatformLevel(); ApiV2Servlet underTest = new ApiV2Servlet(); ServletConfig mockServletConfig = mock(ServletConfig.class); String exceptionMessage = "Exception message"; DispatcherServlet mockDispatcherServletSafeMode = mock(DispatcherServlet.class); doThrow(new ServletException(exceptionMessage)).when(mockDispatcherServletSafeMode).init(mockServletConfig); underTest.setServletProvider(context -> mockDispatcherServletSafeMode); underTest.init(mockServletConfig); assertThatThrownBy(() -> underTest.initDispatcherSafeMode(mockPlatformLevel)) .isInstanceOf(RuntimeException.class) .hasMessageContaining(exceptionMessage); } @Test public void initDispatcherServlet_initLevel4ShouldDestroySafeMode() { PlatformLevel mockPlatformLevel = getMockPlatformLevel(); ApiV2Servlet underTest = new ApiV2Servlet(); DispatcherServlet mockDispatcherServletSafeMode = mock(DispatcherServlet.class); underTest.setServletProvider(context -> mockDispatcherServletSafeMode); underTest.initDispatcherSafeMode(mockPlatformLevel); underTest.setServletProvider(context -> mock(DispatcherServlet.class)); underTest.initDispatcherLevel4(mockPlatformLevel); verify(mockDispatcherServletSafeMode, times(1)).destroy(); } @Test public void destroy_shouldDestroyDispatcherLevel4() { PlatformLevel mockPlatformLevel = getMockPlatformLevel(); ApiV2Servlet underTest = new ApiV2Servlet(); DispatcherServlet mockDispatcherServletLevel4 = mock(DispatcherServlet.class); underTest.setServletProvider(context -> mockDispatcherServletLevel4); underTest.initDispatcherLevel4(mockPlatformLevel); underTest.destroy(); verify(mockDispatcherServletLevel4, times(1)).destroy(); } @Test public void destroy_shouldDestroyDispatcherSafeMode() { PlatformLevel mockPlatformLevel = getMockPlatformLevel(); ApiV2Servlet underTest = new ApiV2Servlet(); DispatcherServlet mockDispatcherServletSafeMode = mock(DispatcherServlet.class); underTest.setServletProvider(context -> mockDispatcherServletSafeMode); underTest.initDispatcherSafeMode(mockPlatformLevel); underTest.destroy(); verify(mockDispatcherServletSafeMode, times(1)).destroy(); } private static PlatformLevel getMockPlatformLevel() { SpringComponentContainer mockSpringComponentContainer = mock(SpringComponentContainer.class); when(mockSpringComponentContainer.context()).thenReturn(new AnnotationConfigApplicationContext()); PlatformLevel mockPlatformLevel = mock(PlatformLevel.class); when(mockPlatformLevel.getContainer()).thenReturn(mockSpringComponentContainer); return mockPlatformLevel; } }
8,133
40.712821
120
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/CacheControlFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import static java.lang.String.format; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class CacheControlFilterTest { private HttpServletResponse response = mock(HttpServletResponse.class); private FilterChain chain = mock(FilterChain.class); private CacheControlFilter underTest = new CacheControlFilter(); @Test public void max_age_is_set_to_one_year_on_js() throws Exception { HttpServletRequest request = newRequest("/js/sonar.js"); underTest.doFilter(request, response, chain); verify(response).addHeader("Cache-Control", format("max-age=%s", 31_536_000)); } @Test public void max_age_is_set_to_one_year_on_css() throws Exception { HttpServletRequest request = newRequest("/css/sonar.css"); underTest.doFilter(request, response, chain); verify(response).addHeader("Cache-Control", format("max-age=%s", 31_536_000)); } @Test public void max_age_is_set_to_five_minutes_on_images() throws Exception { HttpServletRequest request = newRequest("/images/logo.png"); underTest.doFilter(request, response, chain); verify(response).addHeader("Cache-Control", format("max-age=%s", 300)); } @Test public void max_age_is_set_to_five_minutes_on_static() throws Exception { HttpServletRequest request = newRequest("/static/something"); underTest.doFilter(request, response, chain); verify(response).addHeader("Cache-Control", format("max-age=%s", 300)); } @Test public void max_age_is_set_to_five_minutes_on_css_of_static() throws Exception { HttpServletRequest request = newRequest("/static/css/custom.css"); underTest.doFilter(request, response, chain); verify(response).addHeader("Cache-Control", format("max-age=%s", 300)); } @Test public void does_nothing_on_home() throws Exception { HttpServletRequest request = newRequest("/"); underTest.doFilter(request, response, chain); verifyNoInteractions(response); } @Test public void does_nothing_on_web_service() throws Exception { HttpServletRequest request = newRequest("/api/ping"); underTest.doFilter(request, response, chain); verifyNoInteractions(response); } private static HttpServletRequest newRequest(String path) { HttpServletRequest req = mock(HttpServletRequest.class); when(req.getMethod()).thenReturn("GET"); when(req.getRequestURI()).thenReturn(path); when(req.getContextPath()).thenReturn(""); return req; } }
3,621
31.339286
82
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/CspFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import static org.mockito.Mockito.RETURNS_MOCKS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class CspFilterTest { private static final String TEST_CONTEXT = "/sonarqube"; private static final String EXPECTED = "default-src 'self'; " + "base-uri 'none'; " + "connect-src 'self' http: https:; " + "img-src * data: blob:; " + "object-src 'none'; " + "script-src 'self'; " + "style-src 'self' 'unsafe-inline'; " + "worker-src 'none'"; private final ServletContext servletContext = mock(ServletContext.class, RETURNS_MOCKS); private final HttpServletResponse response = mock(HttpServletResponse.class); private final FilterChain chain = mock(FilterChain.class); private final CspFilter underTest = new CspFilter(); FilterConfig config = mock(FilterConfig.class); @Before public void setUp() throws ServletException { when(servletContext.getContextPath()).thenReturn(TEST_CONTEXT); } @Test public void set_content_security_headers() throws Exception { doInit(); HttpServletRequest request = newRequest("/"); underTest.doFilter(request, response, chain); verify(response).setHeader("Content-Security-Policy", EXPECTED); verify(response).setHeader("X-Content-Security-Policy", EXPECTED); verify(response).setHeader("X-WebKit-CSP", EXPECTED); verify(chain).doFilter(request, response); } private void doInit() throws ServletException { underTest.init(config); } private HttpServletRequest newRequest(String path) { HttpServletRequest req = mock(HttpServletRequest.class); when(req.getMethod()).thenReturn("GET"); when(req.getRequestURI()).thenReturn(path); when(req.getContextPath()).thenReturn(""); when(req.getServletContext()).thenReturn(this.servletContext); return req; } }
3,054
36.256098
90
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/MasterServletFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import java.util.Collections; import java.util.List; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mockito; import org.slf4j.event.Level; import org.sonar.api.server.http.HttpRequest; import org.sonar.api.server.http.HttpResponse; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.ServletFilter; import org.sonar.api.web.ServletFilter.UrlPattern; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class MasterServletFilterTest { @Rule public LogTester logTester = new LogTester(); @Before public void resetSingleton() { MasterServletFilter.setInstance(null); } @Test public void should_init_and_destroy_filters() throws ServletException { ServletFilter servletFilter = createMockServletFilter(); HttpFilter httpFilter = createMockHttpFilter(); FilterConfig config = mock(FilterConfig.class); MasterServletFilter master = new MasterServletFilter(); master.init(config, singletonList(servletFilter), singletonList(httpFilter)); assertThat(master.getFilters()).containsOnly(servletFilter); assertThat(master.getHttpFilters()).containsOnly(httpFilter); verify(servletFilter).init(config); verify(httpFilter).init(); master.destroy(); verify(servletFilter).destroy(); verify(httpFilter).destroy(); } @Test public void servlet_container_should_instantiate_only_a_single_master_instance() { new MasterServletFilter(); assertThatThrownBy(MasterServletFilter::new) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Servlet filter org.sonar.server.platform.web.MasterServletFilter is already instantiated"); } @Test public void should_propagate_initialization_failure() throws Exception { ServletFilter filter = createMockServletFilter(); doThrow(new IllegalStateException("foo")).when(filter).init(any(FilterConfig.class)); FilterConfig config = mock(FilterConfig.class); MasterServletFilter filters = new MasterServletFilter(); List<ServletFilter> servletFilters = singletonList(filter); List<HttpFilter> httpFilters = emptyList(); assertThatThrownBy(() -> filters.init(config, servletFilters, httpFilters)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("foo"); } @Test public void filters_should_be_optional() throws Exception { FilterConfig config = mock(FilterConfig.class); MasterServletFilter filters = new MasterServletFilter(); filters.init(config, Collections.emptyList(), Collections.emptyList()); ServletRequest request = mock(HttpServletRequest.class); ServletResponse response = mock(HttpServletResponse.class); FilterChain chain = mock(FilterChain.class); filters.doFilter(request, response, chain); verify(chain).doFilter(request, response); } @Test public void should_add_scim_filter_first_for_scim_request() throws Exception { String scimPath = "/api/scim/v2/Groups"; HttpServletRequest request = mock(HttpServletRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getRequestURI()).thenReturn(scimPath); when(request.getContextPath()).thenReturn(""); HttpRequest httpRequest = mock(JavaxHttpRequest.class); HttpResponse httpResponse = mock(JavaxHttpResponse.class); when(httpRequest.getRequestURI()).thenReturn(scimPath); when(httpRequest.getContextPath()).thenReturn(""); FilterChain chain = mock(FilterChain.class); ServletFilter filter1 = mockFilter(ServletFilter.class, request, response); ServletFilter filter2 = mockFilter(ServletFilter.class, request, response); HttpFilter filter3 = mockHttpFilter(WebServiceFilter.class, httpRequest, httpResponse); HttpFilter filter4 = mockHttpFilter(HttpFilter.class, httpRequest, httpResponse); when(filter3.doGetPattern()).thenReturn(org.sonar.api.web.UrlPattern.builder().includes(scimPath).build()); MasterServletFilter filters = new MasterServletFilter(); filters.init(mock(FilterConfig.class), asList(filter1, filter2), asList(filter4, filter3)); filters.doFilter(request, response, chain); InOrder inOrder = Mockito.inOrder(filter1, filter2, filter3, filter4); inOrder.verify(filter3).doFilter(any(), any(), any()); inOrder.verify(filter4).doFilter(any(), any(), any()); inOrder.verify(filter1).doFilter(any(), any(), any()); inOrder.verify(filter2).doFilter(any(), any(), any()); } private ServletFilter mockFilter(Class<? extends ServletFilter> filterClazz, HttpServletRequest request, ServletResponse response) throws IOException, ServletException { ServletFilter filter = mock(filterClazz); when(filter.doGetPattern()).thenReturn(UrlPattern.builder().build()); doAnswer(invocation -> { FilterChain argument = invocation.getArgument(2, FilterChain.class); argument.doFilter(request, response); return null; }).when(filter).doFilter(any(), any(), any()); return filter; } private HttpFilter mockHttpFilter(Class<? extends HttpFilter> filterClazz, HttpRequest request, HttpResponse response) throws IOException { HttpFilter filter = mock(filterClazz); when(filter.doGetPattern()).thenReturn(org.sonar.api.web.UrlPattern.builder().build()); doAnswer(invocation -> { org.sonar.api.web.FilterChain argument = invocation.getArgument(2, org.sonar.api.web.FilterChain.class); argument.doFilter(request, response); return null; }).when(filter).doFilter(any(), any(), any()); return filter; } @Test public void display_servlet_filter_patterns_in_INFO_log() { HttpFilter filter = new PatternFilter(org.sonar.api.web.UrlPattern.builder().includes("/api/issues").excludes("/batch/projects").build()); FilterConfig config = mock(FilterConfig.class); MasterServletFilter master = new MasterServletFilter(); master.init(config, emptyList(), singletonList(filter)); assertThat(logTester.logs(Level.INFO)).containsOnly("Initializing servlet filter PatternFilter [pattern=UrlPattern{inclusions=[/api/issues], exclusions=[/batch/projects]}]"); } private static ServletFilter createMockServletFilter() { ServletFilter filter = mock(ServletFilter.class); when(filter.doGetPattern()).thenReturn(UrlPattern.builder().build()); return filter; } private static HttpFilter createMockHttpFilter() { HttpFilter filter = mock(HttpFilter.class); when(filter.doGetPattern()).thenReturn(org.sonar.api.web.UrlPattern.builder().build()); return filter; } private static class PatternFilter extends HttpFilter { private final org.sonar.api.web.UrlPattern urlPattern; PatternFilter(org.sonar.api.web.UrlPattern urlPattern) { this.urlPattern = urlPattern; } @Override public org.sonar.api.web.UrlPattern doGetPattern() { return urlPattern; } @Override public void doFilter(HttpRequest request, HttpResponse response, org.sonar.api.web.FilterChain chain) throws IOException { } @Override public String toString() { return "PatternFilter"; } } }
8,960
38.302632
178
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/RedirectFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import javax.annotation.Nullable; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class RedirectFilterTest { private HttpServletRequest request = mock(HttpServletRequest.class); private HttpServletResponse response = mock(HttpServletResponse.class); private FilterChain chain = mock(FilterChain.class); private RedirectFilter underTest = new RedirectFilter(); @Before public void setUp() { when(request.getContextPath()).thenReturn("/sonarqube"); } @Test public void send_redirect_when_url_contains_only_api() throws Exception { verifyRedirection("/api", null, "/sonarqube/api/webservices/list"); verifyRedirection("/api/", null, "/sonarqube/api/webservices/list"); } @Test public void does_not_redirect_and_execute_remaining_filter_on_unknown_path() throws Exception { verifyNoRedirection("/api/issues/search", null); } private void verifyRedirection(String requestUrl, @Nullable String queryString, String expectedRedirection) throws Exception { when(request.getRequestURI()).thenReturn(requestUrl); when(request.getQueryString()).thenReturn(queryString); underTest.doFilter(request, response, chain); verify(response).sendRedirect(expectedRedirection); verifyNoInteractions(chain); reset(response, chain); } private void verifyNoRedirection(String requestUrl, @Nullable String queryString) throws IOException, ServletException { when(request.getRequestURI()).thenReturn(requestUrl); when(request.getQueryString()).thenReturn(queryString); when(request.getParameter(anyString())).thenReturn(null); underTest.doFilter(request, response, chain); verify(chain).doFilter(request, response); verifyNoInteractions(response); reset(response, chain); } }
3,121
35.729412
128
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/RegisterServletFiltersTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import org.junit.Test; import org.sonar.api.web.HttpFilter; import org.sonar.api.web.ServletFilter; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class RegisterServletFiltersTest { @Test public void should_not_fail_if_master_filter_is_not_up() { MasterServletFilter.setInstance(null); new RegisterServletFilters(new ServletFilter[2], new HttpFilter[2]).start(); } @Test public void should_register_filters_if_master_filter_is_up() { MasterServletFilter.setInstance(mock(MasterServletFilter.class)); new RegisterServletFilters(new ServletFilter[2], new HttpFilter[2]).start(); verify(MasterServletFilter.getInstance()).initServletFilters(anyList()); } @Test public void filters_should_be_optional() { MasterServletFilter.setInstance(mock(MasterServletFilter.class)); new RegisterServletFilters().start(); // do not fail verify(MasterServletFilter.getInstance()).initHttpFilters(anyList()); verify(MasterServletFilter.getInstance()).initServletFilters(anyList()); } }
2,007
36.185185
80
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/RequestIdFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import java.util.Optional; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import org.junit.Before; import org.junit.Test; import org.slf4j.MDC; import org.sonar.core.platform.ExtensionContainer; import org.sonar.server.platform.Platform; import org.sonar.server.platform.web.requestid.RequestIdGenerator; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; 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 RequestIdFilterTest { private final Platform platform = mock(Platform.class); private final RequestIdGenerator requestIdGenerator = mock(RequestIdGenerator.class); private final ServletRequest servletRequest = mock(ServletRequest.class); private final ServletResponse servletResponse = mock(ServletResponse.class); private final FilterChain filterChain = mock(FilterChain.class); private final RequestIdFilter underTest = new RequestIdFilter(platform); @Before public void setUp() { ExtensionContainer container = mock(ExtensionContainer.class); when(container.getOptionalComponentByType(RequestIdGenerator.class)).thenReturn(Optional.of(requestIdGenerator)); when(platform.getContainer()).thenReturn(container); } @Test public void filter_put_id_in_MDC_and_remove_it_after_chain_has_executed() throws IOException, ServletException { String requestId = "request id"; when(requestIdGenerator.generate()).thenReturn(requestId); doAnswer(invocation -> assertThat(MDC.get("HTTP_REQUEST_ID")).isEqualTo(requestId)) .when(filterChain) .doFilter(servletRequest, servletResponse); underTest.doFilter(servletRequest, servletResponse, filterChain); assertThat(MDC.get("HTTP_REQUEST_ID")).isNull(); } @Test public void filter_put_id_in_MDC_and_remove_it_after_chain_throws_exception() throws IOException, ServletException { RuntimeException exception = new RuntimeException("Simulating chain failing"); String requestId = "request id"; when(requestIdGenerator.generate()).thenReturn(requestId); doAnswer(invocation -> { assertThat(MDC.get("HTTP_REQUEST_ID")).isEqualTo(requestId); throw exception; }) .when(filterChain) .doFilter(servletRequest, servletResponse); try { underTest.doFilter(servletRequest, servletResponse, filterChain); fail("A runtime exception should have been raised"); } catch (RuntimeException e) { assertThat(e).isEqualTo(exception); } finally { assertThat(MDC.get("HTTP_REQUEST_ID")).isNull(); } } @Test public void filter_adds_requestId_to_request_passed_on_to_chain() throws IOException, ServletException { String requestId = "request id"; when(requestIdGenerator.generate()).thenReturn(requestId); underTest.doFilter(servletRequest, servletResponse, filterChain); verify(servletRequest).setAttribute("ID", requestId); } @Test public void filter_does_not_fail_when_there_is_no_RequestIdGenerator_in_container() throws IOException, ServletException { ExtensionContainer container = mock(ExtensionContainer.class); when(container.getOptionalComponentByType(RequestIdGenerator.class)).thenReturn(Optional.empty()); when(platform.getContainer()).thenReturn(container); RequestIdFilter underTest = new RequestIdFilter(platform); underTest.doFilter(servletRequest, servletResponse, filterChain); } @Test public void filter_does_not_add_requestId_to_request_passed_on_to_chain_when_there_is_no_RequestIdGenerator_in_container() throws IOException, ServletException { ExtensionContainer container = mock(ExtensionContainer.class); when(container.getOptionalComponentByType(RequestIdGenerator.class)).thenReturn(Optional.empty()); when(platform.getContainer()).thenReturn(container); RequestIdFilter underTest = new RequestIdFilter(platform); underTest.doFilter(servletRequest, servletResponse, filterChain); verify(servletRequest, times(0)).setAttribute(anyString(), anyString()); } }
5,244
40.626984
163
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/SecurityServletFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Test; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class SecurityServletFilterTest { private SecurityServletFilter underTest = new SecurityServletFilter(); private HttpServletResponse response = mock(HttpServletResponse.class); private FilterChain chain = mock(FilterChain.class); @Test public void ifRequestUriIsNull_returnBadRequest() throws ServletException, IOException { HttpServletRequest request = newRequest("GET", "/"); when(request.getRequestURI()).thenReturn(null); underTest.doFilter(request, response, chain); verify(response).setStatus(HttpServletResponse.SC_BAD_REQUEST); } @Test public void allow_GET_method() throws IOException, ServletException { assertThatMethodIsAllowed("GET"); } @Test public void allow_HEAD_method() throws IOException, ServletException { assertThatMethodIsAllowed("HEAD"); } @Test public void allow_PUT_method() throws IOException, ServletException { assertThatMethodIsAllowed("PUT"); } @Test public void allow_POST_method() throws IOException, ServletException { assertThatMethodIsAllowed("POST"); } private void assertThatMethodIsAllowed(String httpMethod) throws IOException, ServletException { HttpServletRequest request = newRequest(httpMethod, "/"); underTest.doFilter(request, response, chain); verify(response, never()).setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); verify(chain).doFilter(request, response); } @Test public void deny_OPTIONS_method() throws IOException, ServletException { assertThatMethodIsDenied("OPTIONS"); } @Test public void deny_TRACE_method() throws IOException, ServletException { assertThatMethodIsDenied("TRACE"); } private void assertThatMethodIsDenied(String httpMethod) throws IOException, ServletException { underTest.doFilter(newRequest(httpMethod, "/"), response, chain); verify(response).setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED); } @Test public void set_security_headers_non_secure_request() throws Exception { HttpServletRequest request = newRequest("GET", "/"); when(request.getHeader("x-forwarded-proto")).thenReturn("https"); underTest.doFilter(request, response, chain); verify(response).setHeader("X-Frame-Options", "SAMEORIGIN"); verify(response).setHeader("X-XSS-Protection", "1; mode=block"); verify(response).setHeader("X-Content-Type-Options", "nosniff"); assertNull(response.getHeader("Strict-Transport-Security")); } @Test public void set_security_headers_secure_request() throws ServletException, IOException { HttpServletRequest request = newRequest("GET", "/"); when(request.getHeader("x-forwarded-proto")).thenReturn("https"); underTest.doFilter(request, response, chain); verify(response).setHeader("X-Frame-Options", "SAMEORIGIN"); verify(response).setHeader("X-XSS-Protection", "1; mode=block"); verify(response).setHeader("X-Content-Type-Options", "nosniff"); verify(response).setHeader("Strict-Transport-Security", "max-age=31536000; includeSubDomains;"); } @Test public void do_not_set_frame_protection_on_integration_resources() throws Exception { HttpServletRequest request = newRequest("GET", "/integration/github"); underTest.doFilter(request, response, chain); verify(response, never()).setHeader(eq("X-Frame-Options"), anyString()); verify(response).setHeader("X-XSS-Protection", "1; mode=block"); verify(response).setHeader("X-Content-Type-Options", "nosniff"); } @Test public void do_not_set_frame_protection_on_integration_resources_with_context() throws Exception { HttpServletRequest request = mock(HttpServletRequest.class); when(request.getMethod()).thenReturn("GET"); when(request.getRequestURI()).thenReturn("/sonarqube/integration/github"); when(request.getContextPath()).thenReturn("/sonarqube"); underTest.doFilter(request, response, chain); verify(response, never()).setHeader(eq("X-Frame-Options"), anyString()); verify(response).setHeader("X-XSS-Protection", "1; mode=block"); verify(response).setHeader("X-Content-Type-Options", "nosniff"); } private static HttpServletRequest newRequest(String httpMethod, String path) { HttpServletRequest req = mock(HttpServletRequest.class); when(req.getMethod()).thenReturn(httpMethod); when(req.getRequestURI()).thenReturn(path); when(req.getContextPath()).thenReturn(""); return req; } }
5,840
37.176471
100
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/StaticResourcesServletTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import java.io.InputStream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.servlet.http.HttpServletResponse; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import org.apache.catalina.connector.ClientAbortException; import org.apache.commons.io.IOUtils; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogAndArguments; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.extension.CoreExtensionRepository; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StaticResourcesServletTest { @Rule public LogTester logTester = new LogTester(); private Server jetty; private PluginRepository pluginRepository = mock(PluginRepository.class); private CoreExtensionRepository coreExtensionRepository = mock(CoreExtensionRepository.class); private TestSystem system = new TestSystem(pluginRepository, coreExtensionRepository); @Before public void setUp() throws Exception { logTester.setLevel(Level.TRACE); jetty = new Server(0); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS); context.setContextPath("/"); ServletHolder servletHolder = new ServletHolder(new StaticResourcesServlet(system)); context.addServlet(servletHolder, "/static/*"); jetty.setHandler(context); jetty.start(); } @After public void tearDown() throws Exception { if (jetty != null) { jetty.stop(); } } private Response callAndStop(String path) throws Exception { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(jetty.getURI().resolve(path).toString()) .build(); Response response = client.newCall(request).execute(); jetty.stop(); return response; } @Test public void return_content_if_exists_in_installed_plugin() throws Exception { system.pluginStream = IOUtils.toInputStream("bar"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); Response response = callAndStop("/static/myplugin/foo.txt"); assertThat(response.isSuccessful()).isTrue(); assertThat(response.body().string()).isEqualTo("bar"); assertThat(system.pluginResource).isEqualTo("static/foo.txt"); } @Test public void return_content_of_folder_of_installed_plugin() throws Exception { system.pluginStream = IOUtils.toInputStream("bar"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); Response response = callAndStop("/static/myplugin/foo/bar.txt"); assertThat(response.isSuccessful()).isTrue(); assertThat(response.body().string()).isEqualTo("bar"); assertThat(system.pluginResource).isEqualTo("static/foo/bar.txt"); } @Test public void return_content_of_folder_of_installed_core_extension() throws Exception { system.coreExtensionStream = IOUtils.toInputStream("bar"); when(coreExtensionRepository.isInstalled("coreext")).thenReturn(true); Response response = callAndStop("/static/coreext/foo/bar.txt"); assertThat(response.isSuccessful()).isTrue(); assertThat(response.body().string()).isEqualTo("bar"); assertThat(system.coreExtensionResource).isEqualTo("static/foo/bar.txt"); } @Test public void return_content_of_folder_of_installed_core_extension_over_installed_plugin_in_case_of_key_conflict() throws Exception { system.coreExtensionStream = IOUtils.toInputStream("bar of plugin"); when(coreExtensionRepository.isInstalled("samekey")).thenReturn(true); system.coreExtensionStream = IOUtils.toInputStream("bar of core extension"); when(coreExtensionRepository.isInstalled("samekey")).thenReturn(true); Response response = callAndStop("/static/samekey/foo/bar.txt"); assertThat(response.isSuccessful()).isTrue(); assertThat(response.body().string()).isEqualTo("bar of core extension"); assertThat(system.pluginResource).isNull(); assertThat(system.coreExtensionResource).isEqualTo("static/foo/bar.txt"); } @Test public void mime_type_is_set_on_response() throws Exception { system.pluginStream = IOUtils.toInputStream("bar"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.header("Content-Type")).isEqualTo("text/css"); assertThat(response.body().string()).isEqualTo("bar"); } @Test public void return_404_if_resource_not_found_in_installed_plugin() throws Exception { system.pluginStream = null; when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.code()).isEqualTo(404); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.WARN)).isEmpty(); } @Test public void return_404_if_plugin_does_not_exist() throws Exception { system.pluginStream = null; when(pluginRepository.hasPlugin("myplugin")).thenReturn(false); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.code()).isEqualTo(404); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.WARN)).isEmpty(); } @Test public void return_resource_if_exists_in_requested_plugin() throws Exception { system.pluginStream = IOUtils.toInputStream("bar"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); when(pluginRepository.getPluginInfo("myplugin")).thenReturn(new PluginInfo("myplugin")); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.isSuccessful()).isTrue(); assertThat(response.body().string()).isEqualTo("bar"); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.WARN)).isEmpty(); } @Test public void do_not_fail_nor_log_ERROR_when_response_is_already_committed_and_plugin_does_not_exist() throws Exception { system.pluginStream = null; system.isCommitted = true; when(pluginRepository.hasPlugin("myplugin")).thenReturn(false); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.code()).isEqualTo(200); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.TRACE)).contains("Response is committed. Cannot send error response code 404"); } @Test public void do_not_fail_nor_log_ERROR_when_sendError_throws_IOException_and_plugin_does_not_exist() throws Exception { system.sendErrorException = new IOException("Simulating sendError throwing IOException"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(false); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.code()).isEqualTo(200); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.TRACE)).contains("Failed to send error code 404: {}"); } @Test public void do_not_fail_nor_log_ERROR_when_response_is_already_committed_and_resource_does_not_exist_in_installed_plugin() throws Exception { system.isCommitted = true; system.pluginStream = null; when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.code()).isEqualTo(200); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.TRACE)).contains("Response is committed. Cannot send error response code 404"); } @Test public void do_not_fail_nor_log_not_attempt_to_send_error_if_ClientAbortException_is_raised() throws Exception { system.pluginStreamException = new ClientAbortException("Simulating ClientAbortException"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.code()).isEqualTo(200); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.getLogs(Level.TRACE)).extracting(LogAndArguments::getFormattedMsg).contains( "Client canceled loading resource [static/foo.css] from plugin [myplugin]: {}"); } @Test public void do_not_fail_when_response_is_committed_after_other_error() throws Exception { system.isCommitted = true; system.pluginStreamException = new RuntimeException("Simulating a error"); when(pluginRepository.hasPlugin("myplugin")).thenReturn(true); Response response = callAndStop("/static/myplugin/foo.css"); assertThat(response.code()).isEqualTo(200); assertThat(logTester.logs(Level.ERROR)).contains("Unable to load resource [static/foo.css] from plugin [myplugin]"); } private static class TestSystem extends StaticResourcesServlet.System { private final PluginRepository pluginRepository; private final CoreExtensionRepository coreExtensionRepository; @Nullable private InputStream pluginStream; private Exception pluginStreamException = null; @Nullable private String pluginResource; @Nullable private InputStream coreExtensionStream; private Exception coreExtensionStreamException = null; private String coreExtensionResource; private boolean isCommitted = false; private IOException sendErrorException = null; TestSystem(PluginRepository pluginRepository, CoreExtensionRepository coreExtensionRepository) { this.pluginRepository = pluginRepository; this.coreExtensionRepository = coreExtensionRepository; } @Override PluginRepository getPluginRepository() { return pluginRepository; } @Override CoreExtensionRepository getCoreExtensionRepository() { return this.coreExtensionRepository; } @CheckForNull @Override InputStream openPluginResourceStream(String pluginKey, String resource, PluginRepository pluginRepository) throws Exception { pluginResource = resource; if (pluginStreamException != null) { throw pluginStreamException; } return pluginStream; } @CheckForNull @Override InputStream openCoreExtensionResourceStream(String resource) throws Exception { coreExtensionResource = resource; if (coreExtensionStreamException != null) { throw coreExtensionStreamException; } return coreExtensionStream; } @Override boolean isCommitted(HttpServletResponse response) { return isCommitted; } @Override void sendError(HttpServletResponse response, int error) throws IOException { if (sendErrorException != null) { throw sendErrorException; } else { super.sendError(response, error); } } } }
12,027
36.943218
143
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/UserSessionFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.IOException; import java.util.Optional; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.assertj.core.api.Assertions; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.sonar.core.platform.ExtensionContainer; import org.sonar.db.DBSessions; import org.sonar.server.authentication.UserSessionInitializer; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import org.sonar.server.platform.Platform; import org.sonar.server.setting.ThreadLocalSettings; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class UserSessionFilterTest { private final UserSessionInitializer userSessionInitializer = mock(UserSessionInitializer.class); private final ExtensionContainer container = mock(ExtensionContainer.class); private final Platform platform = mock(Platform.class); private final HttpServletRequest request = mock(HttpServletRequest.class); private final HttpServletResponse response = mock(HttpServletResponse.class); private final FilterChain chain = mock(FilterChain.class); private final DBSessions dbSessions = mock(DBSessions.class); private final ThreadLocalSettings settings = mock(ThreadLocalSettings.class); private final UserSessionFilter underTest = new UserSessionFilter(platform); @Before public void setUp() { when(container.getComponentByType(DBSessions.class)).thenReturn(dbSessions); when(container.getComponentByType(ThreadLocalSettings.class)).thenReturn(settings); when(container.getOptionalComponentByType(UserSessionInitializer.class)).thenReturn(Optional.empty()); when(platform.getContainer()).thenReturn(container); } @Test public void cleanup_user_session_after_request_handling() throws IOException, ServletException { mockUserSessionInitializer(true); underTest.doFilter(request, response, chain); verify(chain).doFilter(request, response); verify(userSessionInitializer).initUserSession(any(JavaxHttpRequest.class), any(JavaxHttpResponse.class)); } @Test public void stop_when_user_session_return_false() throws Exception { mockUserSessionInitializer(false); underTest.doFilter(request, response, chain); verify(chain, never()).doFilter(request, response); verify(userSessionInitializer).initUserSession(any(JavaxHttpRequest.class), any(JavaxHttpResponse.class)); } @Test public void does_nothing_when_not_initialized() throws Exception { underTest.doFilter(request, response, chain); verify(chain).doFilter(request, response); verifyNoInteractions(userSessionInitializer); } @Test public void doFilter_loads_and_unloads_settings() throws Exception { underTest.doFilter(request, response, chain); InOrder inOrder = inOrder(settings); inOrder.verify(settings).load(); inOrder.verify(settings).unload(); inOrder.verifyNoMoreInteractions(); } @Test public void doFilter_unloads_Settings_even_if_chain_throws_exception() throws Exception { RuntimeException thrown = mockChainDoFilterError(); try { underTest.doFilter(request, response, chain); fail("A RuntimeException should have been thrown"); } catch (RuntimeException e) { assertThat(e).isSameAs(thrown); verify(settings).unload(); } } @Test public void doFilter_enables_and_disables_caching_in_DbSessions() throws Exception { underTest.doFilter(request, response, chain); InOrder inOrder = inOrder(dbSessions); inOrder.verify(dbSessions).enableCaching(); inOrder.verify(dbSessions).disableCaching(); inOrder.verifyNoMoreInteractions(); } @Test public void doFilter_disables_caching_in_DbSessions_even_if_chain_throws_exception() throws Exception { RuntimeException thrown = mockChainDoFilterError(); try { underTest.doFilter(request, response, chain); fail("A RuntimeException should have been thrown"); } catch (RuntimeException e) { assertThat(e).isSameAs(thrown); verify(dbSessions).disableCaching(); } } @Test public void doFilter_unloads_Settings_even_if_UserSessionInitializer_removeUserSession_fails() throws Exception { RuntimeException thrown = mockUserSessionInitializerRemoveUserSessionFailing(); try { underTest.doFilter(request, response, chain); fail("A RuntimeException should have been thrown"); } catch (RuntimeException e) { assertThat(e).isSameAs(thrown); verify(settings).unload(); } } @Test public void just_for_fun_and_coverage() { UserSessionFilter filter = new UserSessionFilter(); FilterConfig filterConfig = mock(FilterConfig.class); Assertions.assertThatNoException().isThrownBy(() -> filter.init(filterConfig)); Assertions.assertThatNoException().isThrownBy(filter::destroy); } private void mockUserSessionInitializer(boolean value) { when(container.getOptionalComponentByType(UserSessionInitializer.class)).thenReturn(Optional.of(userSessionInitializer)); when(userSessionInitializer.initUserSession(any(JavaxHttpRequest.class), any(JavaxHttpResponse.class))).thenReturn(value); } private RuntimeException mockUserSessionInitializerRemoveUserSessionFailing() { when(container.getOptionalComponentByType(UserSessionInitializer.class)).thenReturn(Optional.of(userSessionInitializer)); RuntimeException thrown = new RuntimeException("Faking UserSessionInitializer.removeUserSession failing"); doThrow(thrown) .when(userSessionInitializer) .removeUserSession(); return thrown; } private RuntimeException mockChainDoFilterError() throws IOException, ServletException { RuntimeException thrown = new RuntimeException("Faking chain.doFilter failing"); doThrow(thrown) .when(chain) .doFilter(request, response); return thrown; } }
7,303
37.442105
126
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesCacheTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.io.InputStream; import javax.servlet.ServletContext; import org.junit.Before; import org.junit.Test; import org.mockito.stubbing.Answer; import org.sonar.server.platform.OfficialDistribution; import org.sonar.server.platform.Platform; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.commons.io.IOUtils.toInputStream; 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.server.platform.Platform.Status.BOOTING; import static org.sonar.server.platform.Platform.Status.STARTING; import static org.sonar.server.platform.Platform.Status.UP; public class WebPagesCacheTest { private static final String TEST_CONTEXT = "/sonarqube"; private ServletContext servletContext = mock(ServletContext.class); private final OfficialDistribution officialDistribution = mock(OfficialDistribution.class); private final Platform platform = mock(Platform.class); private final WebPagesCache underTest = new WebPagesCache(platform, officialDistribution); @Before public void setUp() { when(servletContext.getContextPath()).thenReturn(TEST_CONTEXT); when(servletContext.getResourceAsStream("/index.html")).thenAnswer( (Answer<InputStream>) invocationOnMock -> toInputStream("Content of default index.html with context [%WEB_CONTEXT%], status [%SERVER_STATUS%], instance [%INSTANCE%]", UTF_8)); } @Test public void check_paths() { doInit(); when(platform.status()).thenReturn(UP); assertThat(underTest.getContent("/foo")).contains(TEST_CONTEXT).contains("default"); assertThat(underTest.getContent("/foo.html")).contains(TEST_CONTEXT).contains("default"); assertThat(underTest.getContent("/index")).contains(TEST_CONTEXT).contains("default"); assertThat(underTest.getContent("/index.html")).contains(TEST_CONTEXT).contains("default"); } @Test public void contains_web_context() { doInit(); assertThat(underTest.getContent("/foo")) .contains(TEST_CONTEXT); } @Test public void status_is_starting() { doInit(); when(platform.status()).thenReturn(STARTING); assertThat(underTest.getContent("/foo")) .contains(STARTING.name()); } @Test public void status_is_up() { doInit(); when(platform.status()).thenReturn(UP); assertThat(underTest.getContent("/foo")) .contains(UP.name()); } @Test public void no_sonarcloud_setting() { doInit(); assertThat(underTest.getContent("/foo")) .contains("SonarQube"); } @Test public void content_is_updated_when_status_has_changed() { doInit(); when(platform.status()).thenReturn(STARTING); assertThat(underTest.getContent("/foo")) .contains(STARTING.name()); when(platform.status()).thenReturn(UP); assertThat(underTest.getContent("/foo")) .contains(UP.name()); } @Test public void content_is_not_updated_when_status_is_up() { doInit(); when(platform.status()).thenReturn(UP); assertThat(underTest.getContent("/foo")) .contains(UP.name()); when(platform.status()).thenReturn(STARTING); assertThat(underTest.getContent("/foo")) .contains(UP.name()); } @Test public void fail_to_get_content_when_init_has_not_been_called() { assertThatThrownBy(() -> underTest.getContent("/foo")) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("init has not been called"); } private void doInit() { when(platform.status()).thenReturn(BOOTING); underTest.init(servletContext); } }
4,577
31.239437
172
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebPagesFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import javax.servlet.FilterChain; import javax.servlet.ServletContext; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.RETURNS_MOCKS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class WebPagesFilterTest { private static final String TEST_CONTEXT = "/sonarqube"; private ServletContext servletContext = mock(ServletContext.class, RETURNS_MOCKS); private WebPagesCache webPagesCache = mock(WebPagesCache.class); private HttpServletRequest request = mock(HttpServletRequest.class); private HttpServletResponse response = mock(HttpServletResponse.class); private FilterChain chain = mock(FilterChain.class); private WebPagesFilter underTest = new WebPagesFilter(webPagesCache); @Before public void setUp() { when(servletContext.getContextPath()).thenReturn(TEST_CONTEXT); } @Test public void return_web_page_content() throws Exception { String path = "/index.html"; when(webPagesCache.getContent(path)).thenReturn("test"); when(request.getRequestURI()).thenReturn(path); when(request.getContextPath()).thenReturn(TEST_CONTEXT); StringOutputStream outputStream = new StringOutputStream(); when(response.getOutputStream()).thenReturn(outputStream); underTest.doFilter(request, response, chain); verify(response).setContentType("text/html"); verify(response).setCharacterEncoding("utf-8"); verify(response).setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); assertThat(outputStream).hasToString("test"); } @Test public void does_nothing_when_static_resource() throws Exception{ when(request.getRequestURI()).thenReturn("/static"); when(request.getContextPath()).thenReturn(TEST_CONTEXT); underTest.doFilter(request, response, chain); verify(chain).doFilter(request, response); verifyNoInteractions(webPagesCache); } static class StringOutputStream extends ServletOutputStream { private final StringBuilder buf = new StringBuilder(); StringOutputStream() { } @Override public boolean isReady() { return false; } @Override public void setWriteListener(WriteListener listener) { } public void write(byte[] b) { this.buf.append(new String(b)); } public void write(byte[] b, int off, int len) { this.buf.append(new String(b, off, len)); } public void write(int b) { byte[] bytes = new byte[] {(byte) b}; this.buf.append(new String(bytes)); } public String toString() { return this.buf.toString(); } } }
3,824
31.415254
87
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.sonar.api.server.ws.Request; import org.sonar.api.server.ws.RequestHandler; import org.sonar.api.server.ws.Response; import org.sonar.api.server.ws.WebService; import org.sonar.api.web.FilterChain; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import org.sonar.server.ws.ServletFilterHandler; import org.sonar.server.ws.WebServiceEngine; import static org.assertj.core.api.Assertions.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; import static org.sonar.server.platform.web.WebServiceFilterTest.WsUrl.newWsUrl; public class WebServiceFilterTest { private final WebServiceEngine webServiceEngine = mock(WebServiceEngine.class); private final HttpServletRequest request = mock(HttpServletRequest.class); private final HttpServletResponse response = mock(HttpServletResponse.class); private final FilterChain chain = mock(FilterChain.class); private final ServletOutputStream responseOutput = mock(ServletOutputStream.class); private WebServiceFilter underTest; @Before public void setUp() throws Exception { when(request.getContextPath()).thenReturn(""); HttpServletResponse mockResponse = mock(HttpServletResponse.class); when(mockResponse.getOutputStream()).thenReturn(responseOutput); } @Test public void match_declared_web_services_with_optional_suffix() { initWebServiceEngine( newWsUrl("api/issues", "search"), newWsUrl("batch", "index")); assertThat(underTest.doGetPattern().matches("/api/issues/search")).isTrue(); assertThat(underTest.doGetPattern().matches("/api/issues/search.protobuf")).isTrue(); assertThat(underTest.doGetPattern().matches("/batch/index")).isTrue(); assertThat(underTest.doGetPattern().matches("/batch/index.protobuf")).isTrue(); assertThat(underTest.doGetPattern().matches("/foo")).isFalse(); } @Test public void match_undeclared_web_services_starting_with_api() { initWebServiceEngine(newWsUrl("api/issues", "search")); assertThat(underTest.doGetPattern().matches("/api/resources/index")).isTrue(); assertThat(underTest.doGetPattern().matches("/api/user_properties")).isTrue(); } @Test public void does_not_match_web_services_using_servlet_filter() { initWebServiceEngine(newWsUrl("api/authentication", "login").setHandler(ServletFilterHandler.INSTANCE)); assertThat(underTest.doGetPattern().matches("/api/authentication/login")).isFalse(); } @Test public void does_not_match_servlet_filter_that_prefix_a_ws() { initWebServiceEngine( newWsUrl("api/foo", "action").setHandler(ServletFilterHandler.INSTANCE), newWsUrl("api/foo", "action_2")); assertThat(underTest.doGetPattern().matches("/api/foo/action")).isFalse(); assertThat(underTest.doGetPattern().matches("/api/foo/action_2")).isTrue(); } @Test public void execute_ws() { underTest = new WebServiceFilter(webServiceEngine); underTest.doFilter(new JavaxHttpRequest(request), new JavaxHttpResponse(response), chain); verify(webServiceEngine).execute(any(), any()); } private void initWebServiceEngine(WsUrl... wsUrls) { List<WebService.Controller> controllers = new ArrayList<>(); for (WsUrl wsUrl : wsUrls) { String controller = wsUrl.getController(); WebService.Controller wsController = mock(WebService.Controller.class); when(wsController.path()).thenReturn(controller); List<WebService.Action> actions = new ArrayList<>(); for (String action : wsUrl.getActions()) { WebService.Action wsAction = mock(WebService.Action.class); when(wsAction.path()).thenReturn(controller + "/" + action); when(wsAction.key()).thenReturn(action); when(wsAction.handler()).thenReturn(wsUrl.getRequestHandler()); actions.add(wsAction); } when(wsController.actions()).thenReturn(actions); controllers.add(wsController); } when(webServiceEngine.controllers()).thenReturn(controllers); underTest = new WebServiceFilter(webServiceEngine); } static final class WsUrl { private final String controller; private final String[] actions; private RequestHandler requestHandler = EmptyRequestHandler.INSTANCE; WsUrl(String controller, String... actions) { this.controller = controller; this.actions = actions; } WsUrl setHandler(RequestHandler requestHandler) { this.requestHandler = requestHandler; return this; } String getController() { return controller; } String[] getActions() { return actions; } RequestHandler getRequestHandler() { return requestHandler; } static WsUrl newWsUrl(String controller, String... actions) { return new WsUrl(controller, actions); } } private enum EmptyRequestHandler implements RequestHandler { INSTANCE; @Override public void handle(Request request, Response response) { // Nothing to do } } }
6,232
34.414773
108
java
sonarqube
sonarqube-master/server/sonar-webserver/src/test/java/org/sonar/server/platform/web/WebServiceReroutingFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this 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.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.web.FilterChain; import org.sonar.server.http.JavaxHttpRequest; import org.sonar.server.http.JavaxHttpResponse; import org.sonar.server.ws.ServletRequest; import org.sonar.server.ws.ServletResponse; import org.sonar.server.ws.WebServiceEngine; import static org.assertj.core.api.Assertions.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 WebServiceReroutingFilterTest { private final WebServiceEngine webServiceEngine = mock(WebServiceEngine.class); private final HttpServletRequest request = mock(HttpServletRequest.class); private final HttpServletResponse response = mock(HttpServletResponse.class); private final FilterChain chain = mock(FilterChain.class); private final ArgumentCaptor<ServletRequest> servletRequestCaptor = ArgumentCaptor.forClass(ServletRequest.class); private final WebServiceReroutingFilter underTest = new WebServiceReroutingFilter(webServiceEngine); @Before public void setUp() { when(request.getContextPath()).thenReturn("/sonarqube"); } @Test public void do_get_pattern() { assertThat(underTest.doGetPattern().matches("/api/components/update_key")).isTrue(); assertThat(underTest.doGetPattern().matches("/api/components/bulk_update_key")).isTrue(); assertThat(underTest.doGetPattern().matches("/api/projects/update_key")).isFalse(); } @Test public void redirect_components_update_key() { when(request.getServletPath()).thenReturn("/api/components/update_key"); when(request.getMethod()).thenReturn("POST"); underTest.doFilter(new JavaxHttpRequest(request), new JavaxHttpResponse(response), chain); assertRedirection("/api/projects/update_key", "POST"); } private void assertRedirection(String path, String method) { verify(webServiceEngine).execute(servletRequestCaptor.capture(), any(ServletResponse.class)); assertThat(servletRequestCaptor.getValue().getPath()).isEqualTo(path); assertThat(servletRequestCaptor.getValue().method()).isEqualTo(method); } }
3,203
39.556962
116
java
sonarqube
sonarqube-master/sonar-application/src/main/java/org/sonar/application/App.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.application; import org.slf4j.LoggerFactory; import org.sonar.application.command.CommandFactory; import org.sonar.application.command.CommandFactoryImpl; import org.sonar.application.config.AppSettings; import org.sonar.application.config.AppSettingsLoader; import org.sonar.application.config.AppSettingsLoaderImpl; import org.sonar.core.extension.ServiceLoaderWrapper; import org.sonar.process.System2; import org.sonar.process.SystemExit; import static org.sonar.application.config.SonarQubeVersionHelper.getSonarqubeVersion; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NAME; public class App { private final SystemExit systemExit = new SystemExit(); private StopRequestWatcher stopRequestWatcher = null; private StopRequestWatcher hardStopRequestWatcher = null; public void start(String[] cliArguments) { AppSettingsLoader settingsLoader = new AppSettingsLoaderImpl(System2.INSTANCE, cliArguments, new ServiceLoaderWrapper()); AppSettings settings = settingsLoader.load(); // order is important - logging must be configured before any other components (AppFileSystem, ...) AppLogging logging = new AppLogging(settings); logging.configure(); AppFileSystem fileSystem = new AppFileSystem(settings); try (AppState appState = new AppStateFactory(settings).create()) { appState.registerSonarQubeVersion(getSonarqubeVersion()); appState.registerClusterName(settings.getProps().nonNullValue(CLUSTER_NAME.getKey())); AppReloader appReloader = new AppReloaderImpl(settingsLoader, fileSystem, appState, logging); fileSystem.reset(); CommandFactory commandFactory = new CommandFactoryImpl(settings.getProps(), fileSystem.getTempDir(), System2.INSTANCE); try (ProcessLauncher processLauncher = new ProcessLauncherImpl(fileSystem.getTempDir())) { Scheduler scheduler = new SchedulerImpl(settings, appReloader, commandFactory, processLauncher, appState); scheduler.schedule(); stopRequestWatcher = StopRequestWatcherImpl.create(settings, scheduler, fileSystem); hardStopRequestWatcher = HardStopRequestWatcherImpl.create(scheduler, fileSystem); // intercepts CTRL-C Runtime.getRuntime().addShutdownHook(new ShutdownHook(scheduler)); stopRequestWatcher.startWatching(); hardStopRequestWatcher.startWatching(); scheduler.awaitTermination(); hardStopRequestWatcher.stopWatching(); } } catch (Exception e) { LoggerFactory.getLogger(App.class).error("Startup failure", e); } systemExit.exit(0); } public static void main(String[] args) { new App().start(args); } private class ShutdownHook extends Thread { private final Scheduler scheduler; public ShutdownHook(Scheduler scheduler) { super("Shutdown Hook"); this.scheduler = scheduler; } @Override public void run() { systemExit.setInShutdownHook(); stopRequestWatcher.stopWatching(); hardStopRequestWatcher.stopWatching(); // blocks until everything is corrected terminated scheduler.stop(); } } }
3,994
37.786408
125
java
sonarqube
sonarqube-master/sonar-application/src/main/java/org/sonar/application/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.application; import javax.annotation.ParametersAreNonnullByDefault;
961
39.083333
75
java
sonarqube
sonarqube-master/sonar-core/src/it/java/org/sonar/core/util/DefaultHttpDownloaderIT.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.util; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.util.Properties; import java.util.zip.GZIPOutputStream; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.junit.rules.DisableOnDebug; import org.junit.rules.TemporaryFolder; import org.junit.rules.TestRule; import org.junit.rules.Timeout; import org.simpleframework.http.Request; import org.simpleframework.http.Response; import org.simpleframework.http.core.Container; import org.simpleframework.http.core.ContainerServer; import org.simpleframework.transport.connect.SocketConnection; import org.sonar.api.CoreProperties; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.platform.Server; import org.sonar.api.utils.SonarException; 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 DefaultHttpDownloaderIT { @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); @Rule public TestRule safeguardTimeout = new DisableOnDebug(Timeout.seconds(60)); private static SocketConnection socketConnection; private static String baseUrl; @BeforeClass public static void startServer() throws IOException { socketConnection = new SocketConnection(new ContainerServer(new Container() { public void handle(Request req, Response resp) { try { if (req.getPath().getPath().contains("/redirect/")) { resp.setCode(303); resp.setValue("Location", "/redirected"); } else if (req.getPath().getPath().contains("/timeout/")) { try { Thread.sleep(500); writeDefaultResponse(req, resp); } catch (InterruptedException e) { throw new IllegalStateException(e); } } else if (req.getPath().getPath().contains("/gzip/")) { if (!"gzip".equals(req.getValue("Accept-Encoding"))) { throw new IllegalStateException("Should accept gzip"); } resp.setValue("Content-Encoding", "gzip"); GZIPOutputStream gzipOutputStream = new GZIPOutputStream(resp.getOutputStream()); gzipOutputStream.write("GZIP response".getBytes()); gzipOutputStream.close(); } else if (req.getPath().getPath().contains("/redirected")) { resp.getPrintStream().append("redirected"); } else { writeDefaultResponse(req, resp); } } catch (IOException e) { throw new IllegalStateException(e); } finally { try { resp.close(); } catch (IOException ignored) { } } } })); SocketAddress address = socketConnection.connect(new InetSocketAddress("localhost", 0)); baseUrl = String.format("http://%s:%d", ((InetSocketAddress) address).getAddress().getHostAddress(), ((InetSocketAddress) address).getPort()); } private static PrintStream writeDefaultResponse(Request req, Response resp) throws IOException { return resp.getPrintStream().append("agent=" + req.getValues("User-Agent").get(0)); } @AfterClass public static void stopServer() throws IOException { if (null != socketConnection) { socketConnection.close(); } } @Test(timeout = 10000) public void openStream_network_errors() throws IOException, URISyntaxException { // non routable address String url = "http://10.255.255.1"; assertThatThrownBy(() -> { DefaultHttpDownloader downloader = new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig(), 10, 10); downloader.openStream(new URI(url)); }) .isInstanceOf(SonarException.class) .isEqualToComparingFieldByField(new BaseMatcher<Exception>() { @Override public boolean matches(Object ex) { return ex instanceof SonarException && ((SonarException) ex).getCause() instanceof SocketTimeoutException; } @Override public void describeTo(Description arg0) { } }); } @Test public void downloadBytes() throws URISyntaxException { byte[] bytes = new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).readBytes(new URI(baseUrl)); assertThat(bytes.length).isGreaterThan(10); } @Test public void readString() throws URISyntaxException { String text = new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).readString(new URI(baseUrl), StandardCharsets.UTF_8); assertThat(text.length()).isGreaterThan(10); } @Test public void readGzipString() throws URISyntaxException { String text = new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).readString(new URI(baseUrl + "/gzip/"), StandardCharsets.UTF_8); assertThat(text).isEqualTo("GZIP response"); } @Test public void readStringWithDefaultTimeout() throws URISyntaxException { String text = new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).readString(new URI(baseUrl + "/timeout/"), StandardCharsets.UTF_8); assertThat(text.length()).isGreaterThan(10); } @Test public void readStringWithTimeout() throws URISyntaxException { assertThatThrownBy( () -> new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig(), null, 50).readString(new URI(baseUrl + "/timeout/"), StandardCharsets.UTF_8)) .isEqualToComparingFieldByField(new BaseMatcher<Exception>() { @Override public boolean matches(Object ex) { return ex instanceof SonarException && ((SonarException) ex).getCause() instanceof SocketTimeoutException; } @Override public void describeTo(Description arg0) { } }); } @Test public void downloadToFile() throws URISyntaxException, IOException { File toDir = temporaryFolder.newFolder(); File toFile = new File(toDir, "downloadToFile.txt"); new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).download(new URI(baseUrl), toFile); assertThat(toFile).exists(); assertThat(toFile.length()).isGreaterThan(10L); } @Test public void shouldNotCreateFileIfFailToDownload() throws Exception { File toDir = temporaryFolder.newFolder(); File toFile = new File(toDir, "downloadToFile.txt"); try { new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).download(new URI("http://localhost:1"), toFile); } catch (SonarException e) { assertThat(toFile).doesNotExist(); } } @Test public void userAgent_includes_version_and_SERVER_ID_when_server_is_provided() throws URISyntaxException, IOException { Server server = mock(Server.class); when(server.getVersion()).thenReturn("2.2"); MapSettings settings = new MapSettings(); settings.setProperty(CoreProperties.SERVER_ID, "blablabla"); InputStream stream = new DefaultHttpDownloader(server, settings.asConfig()).openStream(new URI(baseUrl)); Properties props = new Properties(); props.load(stream); stream.close(); assertThat(props.getProperty("agent")).isEqualTo("SonarQube 2.2 # blablabla"); } @Test public void userAgent_includes_only_version_when_there_is_no_SERVER_ID_and_server_is_provided() throws URISyntaxException, IOException { Server server = mock(Server.class); when(server.getVersion()).thenReturn("2.2"); InputStream stream = new DefaultHttpDownloader(server, new MapSettings().asConfig()).openStream(new URI(baseUrl)); Properties props = new Properties(); props.load(stream); stream.close(); assertThat(props.getProperty("agent")).isEqualTo("SonarQube 2.2 #"); } @Test public void followRedirect() throws URISyntaxException { String content = new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).readString(new URI(baseUrl + "/redirect/"), StandardCharsets.UTF_8); assertThat(content).isEqualTo("redirected"); } @Test public void supported_schemes() { assertThat(new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).getSupportedSchemes()).contains("http"); } @Test public void uri_description() throws URISyntaxException { String description = new DefaultHttpDownloader(mock(Server.class), new MapSettings().asConfig()).description(new URI("http://sonarsource.org")); assertThat(description).isEqualTo("http://sonarsource.org"); } }
9,780
37.356863
165
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/component/ComponentKeys.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.component; import java.util.regex.Pattern; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import static com.google.common.base.Preconditions.checkArgument; public final class ComponentKeys { /** * Should be in sync with DefaultIndexedFile.MAX_KEY_LENGTH */ public static final int MAX_COMPONENT_KEY_LENGTH = 400; public static final String ALLOWED_CHARACTERS_MESSAGE = "Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit"; public static final String MALFORMED_KEY_MESSAGE = "Malformed key for '%s'. %s."; /** * Allowed characters are alphanumeric, '-', '_', '.' and ':' */ private static final String VALID_PROJECT_KEY_CHARS = "\\p{Alnum}-_.:"; private static final Pattern INVALID_PROJECT_KEY_REGEXP = Pattern.compile("[^" + VALID_PROJECT_KEY_CHARS + "]"); /** * At least one non-digit is necessary */ private static final Pattern VALID_PROJECT_KEY_REGEXP = Pattern.compile("[" + VALID_PROJECT_KEY_CHARS + "]*[\\p{Alpha}\\-_.:]+[" + VALID_PROJECT_KEY_CHARS + "]*"); private static final String KEY_WITH_BRANCH_FORMAT = "%s:%s"; private static final String REPLACEMENT_CHARACTER = "_"; private ComponentKeys() { // only static stuff } public static String createEffectiveKey(String projectKey, @Nullable String path) { StringBuilder sb = new StringBuilder(MAX_COMPONENT_KEY_LENGTH); sb.append(projectKey); if (path != null) { sb.append(':').append(path); } return sb.toString(); } public static boolean isValidProjectKey(String keyCandidate) { return VALID_PROJECT_KEY_REGEXP.matcher(keyCandidate).matches(); } /** * Checks if given parameter is valid for a project following {@link #isValidProjectKey(String)} contract. * * @throws IllegalArgumentException if the format is incorrect */ public static void checkProjectKey(String keyCandidate) { checkArgument(isValidProjectKey(keyCandidate), MALFORMED_KEY_MESSAGE, keyCandidate, ALLOWED_CHARACTERS_MESSAGE); } public static String sanitizeProjectKey(String rawProjectKey) { return INVALID_PROJECT_KEY_REGEXP.matcher(rawProjectKey).replaceAll(REPLACEMENT_CHARACTER); } /** * Return the project key with potential branch */ public static String createKey(String keyWithoutBranch, @Nullable String branch) { if (StringUtils.isNotBlank(branch)) { return String.format(KEY_WITH_BRANCH_FORMAT, keyWithoutBranch, branch); } else { return keyWithoutBranch; } } public static String createKey(String projectKey, @Nullable String path, @Nullable String branch) { String key = createKey(projectKey, branch); return createEffectiveKey(key, path); } }
3,605
35.06
165
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/component/DefaultResourceTypes.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.component; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.ResourceType; import org.sonar.api.resources.ResourceTypeTree; import org.sonar.api.scanner.ScannerSide; import org.sonar.api.server.ServerSide; @ScannerSide @ServerSide @ComputeEngineSide public final class DefaultResourceTypes { private static final String CONFIGURABLE = "configurable"; private static final String UPDATABLE_KEY = "updatable_key"; public static final String IGNORED = "ignored"; private DefaultResourceTypes() { // only static methods } public static ResourceTypeTree get() { return ResourceTypeTree.builder() .addType(ResourceType.builder(Qualifiers.PROJECT) .setProperty("deletable", true) .setProperty("modifiable_history", true) .setProperty("hasRolePolicy", true) .setProperty(UPDATABLE_KEY, true) .setProperty("comparable", true) .setProperty(CONFIGURABLE, true) .build()) .addType(ResourceType.builder(Qualifiers.MODULE) .setProperty(UPDATABLE_KEY, true) .setProperty(CONFIGURABLE, true) .setProperty(IGNORED, true) .build()) .addType(ResourceType.builder(Qualifiers.DIRECTORY) .build()) .addType(ResourceType.builder(Qualifiers.FILE) .hasSourceCode() .build()) .addType(ResourceType.builder(Qualifiers.UNIT_TEST_FILE) .hasSourceCode() .build()) .addRelations(Qualifiers.PROJECT, Qualifiers.DIRECTORY) .addRelations(Qualifiers.DIRECTORY, Qualifiers.FILE, Qualifiers.UNIT_TEST_FILE) .build(); } }
2,522
34.041667
85
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/component/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.core.component; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/ComputeEngineProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.config; public class ComputeEngineProperties { private ComputeEngineProperties() { } public static final String CE_PARALLEL_PROJECT_TASKS_ENABLED = "sonar.ce.parallelProjectTasks"; }
1,059
34.333333
97
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/CorePropertyDefinitions.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.config; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.sonar.api.CoreProperties; import org.sonar.api.PropertyType; import org.sonar.api.config.EmailSettings; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; import org.sonar.core.documentation.DefaultDocumentationLinkGenerator; import org.sonar.core.extension.PluginRiskConsent; import static java.util.Arrays.asList; import static org.sonar.api.PropertyType.BOOLEAN; import static org.sonar.api.PropertyType.SINGLE_SELECT_LIST; import static org.sonar.api.PropertyType.STRING; import static org.sonar.api.PropertyType.TEXT; import static org.sonar.core.extension.PluginRiskConsent.NOT_ACCEPTED; public class CorePropertyDefinitions { public static final String SONAR_ANALYSIS = "sonar.analysis."; public static final String SONAR_PROJECTCREATION_MAINBRANCHNAME = "sonar.projectCreation.mainBranchName"; public static final String SONAR_ANALYSIS_DETECTEDSCM = "sonar.analysis.detectedscm"; public static final String SONAR_ANALYSIS_DETECTEDCI = "sonar.analysis.detectedci"; public static final String DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES = "sonar.builtInQualityProfiles.disableNotificationOnUpdate"; public static final String PLUGINS_RISK_CONSENT = "sonar.plugins.risk.consent"; public static final String DOCUMENTATION_BASE_URL = "sonar.documentation.baseUrl"; public static final String SUBCATEGORY_PROJECT_CREATION = "subProjectCreation"; private CorePropertyDefinitions() { // only static stuff } public static List<PropertyDefinition> all() { List<PropertyDefinition> defs = new ArrayList<>(); defs.addAll(IssueExclusionProperties.all()); defs.addAll(ExclusionProperties.all()); defs.addAll(SecurityProperties.all()); defs.addAll(DebtProperties.all()); defs.addAll(PurgeProperties.all()); defs.addAll(EmailSettings.definitions()); defs.addAll(ScannerProperties.all()); defs.addAll(asList( PropertyDefinition.builder(CoreProperties.MODULE_LEVEL_ARCHIVED_SETTINGS) .name("Archived Sub-Projects Settings") .description("DEPRECATED - List of the properties that were previously configured at sub-project / module level. " + "These properties are not used anymore and should now be configured at project level. When you've made the " + "necessary changes, clear this setting to prevent analysis from showing a warning about it.") .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_MODULES) .onlyOnQualifiers(Qualifiers.PROJECT) .type(TEXT) .build(), PropertyDefinition.builder(CoreProperties.SERVER_BASE_URL) .name("Server base URL") .description( "HTTP(S) URL of this SonarQube server, such as <i>https://yourhost.yourdomain/sonar</i>. " + "This value is used outside SonarQube itself, e.g. for PR decoration, emails, etc.") .category(CoreProperties.CATEGORY_GENERAL) .build(), PropertyDefinition.builder(SONAR_PROJECTCREATION_MAINBRANCHNAME) .name("Default main branch name") .category(CoreProperties.CATEGORY_GENERAL) .subCategory(SUBCATEGORY_PROJECT_CREATION) .description("Each project has a main branch at creation. This setting defines the instance-wide default main branch name. " + " A user can override this when creating a project. This setting does not apply to projects imported from a DevOps platform.") .type(STRING) .defaultValue("main") .build(), PropertyDefinition.builder(CoreProperties.ENCRYPTION_SECRET_KEY_PATH) .name("Encryption secret key path") .description("Path to a file that contains encryption secret key that is used to encrypting other settings.") .type(STRING) .hidden() .build(), PropertyDefinition.builder("sonar.authenticator.downcase") .name("Downcase login") .description("Downcase login during user authentication, typically for Active Directory") .type(BOOLEAN) .defaultValue(String.valueOf(false)) .hidden() .build(), PropertyDefinition.builder(DISABLE_NOTIFICATION_ON_BUILT_IN_QPROFILES) .name("Avoid quality profiles notification") .description("Avoid sending email notification on each update of built-in quality profiles to quality profile administrators.") .defaultValue(Boolean.toString(false)) .category(CoreProperties.CATEGORY_GENERAL) .type(BOOLEAN) .build(), PropertyDefinition.builder(PLUGINS_RISK_CONSENT) .name("State of user plugins risk consent") .description("Determine whether user is required to accept plugins risk consent") .defaultValue(NOT_ACCEPTED.name()) .options(Arrays.stream(PluginRiskConsent.values()).map(Enum::name).collect(Collectors.toList())) .hidden() .type(SINGLE_SELECT_LIST) .build(), PropertyDefinition.builder(DOCUMENTATION_BASE_URL) .name("Base URL of the documentation") .description("Base URL to be used in SonarQube documentation links, such as <i>https://docs.sonarqube.org/</i>") .defaultValue(DefaultDocumentationLinkGenerator.DOCUMENTATION_PUBLIC_URL) .hidden() .type(STRING) .build(), // WEB LOOK&FEEL PropertyDefinition.builder(WebConstants.SONAR_LF_LOGO_URL) .deprecatedKey("sonar.branding.image") .name("Logo URL") .description("URL to logo image. Any standard format is accepted.") .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_LOOKNFEEL) .build(), PropertyDefinition.builder(WebConstants.SONAR_LF_LOGO_WIDTH_PX) .deprecatedKey("sonar.branding.image.width") .name("Width of image in pixels") .description("Width in pixels, given that the height of the the image is constrained to 30px.") .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_LOOKNFEEL) .build(), PropertyDefinition.builder(WebConstants.SONAR_LF_ENABLE_GRAVATAR) .name("Enable support of gravatars") .description("Gravatars are profile pictures of users based on their email.") .type(BOOLEAN) .defaultValue(String.valueOf(false)) .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_LOOKNFEEL) .build(), PropertyDefinition.builder(WebConstants.SONAR_LF_GRAVATAR_SERVER_URL) .name("Gravatar URL") .description("Optional URL of custom Gravatar service. Accepted variables are {EMAIL_MD5} for MD5 hash of email and {SIZE} for the picture size in pixels.") .defaultValue("https://secure.gravatar.com/avatar/{EMAIL_MD5}.jpg?s={SIZE}&d=identicon") .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_LOOKNFEEL) .build(), // ISSUES PropertyDefinition.builder(CoreProperties.DEVELOPER_AGGREGATED_INFO_DISABLED) .name("Disable developer aggregated information") .description("Don't show issue facets aggregating information per developer") .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_ISSUES) .onQualifiers(Qualifiers.PROJECT) .type(BOOLEAN) .defaultValue(Boolean.toString(false)) .build(), PropertyDefinition.builder(CoreProperties.DEFAULT_ISSUE_ASSIGNEE) .name("Default Assignee") .description("New issues will be assigned to this user each time it is not possible to determine the user who is the author of the issue.") .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_ISSUES) .onQualifiers(Qualifiers.PROJECT) .type(PropertyType.USER_LOGIN) .build(), // QUALITY GATE PropertyDefinition.builder(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES) .name("Ignore duplication and coverage on small changes") .description("Quality Gate conditions about duplications in new code and coverage on new code are ignored until the number of new lines is at least 20.") .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_QUALITY_GATE) .onQualifiers(Qualifiers.PROJECT) .type(BOOLEAN) .defaultValue(Boolean.toString(true)) .build(), // CPD PropertyDefinition.builder(CoreProperties.CPD_CROSS_PROJECT) .defaultValue(Boolean.toString(false)) .name("Cross project duplication detection") .description("DEPRECATED - By default, SonarQube detects duplications at project level. This means that a block " + "duplicated on two different projects won't be reported. Setting this parameter to \"true\" " + "allows to detect duplicates across projects. Note that activating " + "this property will significantly increase each SonarQube analysis time, " + "and therefore badly impact the performances of report processing as more and more projects " + "are getting involved in this cross project duplication mechanism.") .onQualifiers(Qualifiers.PROJECT) .category(CoreProperties.CATEGORY_GENERAL) .subCategory(CoreProperties.SUBCATEGORY_DUPLICATIONS) .type(BOOLEAN) .build(), PropertyDefinition.builder(CoreProperties.CPD_EXCLUSIONS) .defaultValue("") .name("Duplication Exclusions") .description("Patterns used to exclude some source files from the duplication detection mechanism. " + "See below to know how to use wildcards to specify this property.") .onQualifiers(Qualifiers.PROJECT) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_DUPLICATIONS_EXCLUSIONS) .multiValues(true) .build())); return defs; } }
11,001
48.116071
164
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/DebtProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.config; import java.util.List; import org.sonar.api.CoreProperties; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyFieldDefinition; class DebtProperties { private DebtProperties() { // only static stuff } static List<PropertyDefinition> all() { return List.of( PropertyDefinition.builder(CoreProperties.DEVELOPMENT_COST) .defaultValue("" + CoreProperties.DEVELOPMENT_COST_DEF_VALUE) .name("Development cost") .description("Cost to develop one line of code (LOC). Example: if the cost to develop 1 LOC has been estimated " + "at 30 minutes, then the value of this property would be 30.") .category(CoreProperties.CATEGORY_TECHNICAL_DEBT) .deprecatedKey("workUnitsBySizePoint") .build(), PropertyDefinition.builder(CoreProperties.RATING_GRID) .defaultValue("" + CoreProperties.RATING_GRID_DEF_VALUES) .name("Maintainability rating grid") .description("Maintainability ratings range from A (very good) to E (very bad). The rating is determined by the value of " + "the Technical Debt Ratio, which compares the technical debt on a project to the cost it would take to rewrite " + "the code from scratch. The default values for A through D are 0.05,0.1,0.2,0.5. Anything over 0.5 is an E. " + "Example: assuming the development cost is 30 minutes, a project with a technical debt of 24,000 minutes for " + "2,500 LOC will have a technical debt ratio of 24000/(30 * 2,500) = 0.32. That yields a maintainability rating of D.") .category(CoreProperties.CATEGORY_TECHNICAL_DEBT) .deprecatedKey("ratingGrid") .build(), PropertyDefinition.builder(CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS) .name("Language specific parameters") .description("DEPRECATED - The parameters specified here for a given language will override the general parameters defined in this section.") .category(CoreProperties.CATEGORY_TECHNICAL_DEBT) .deprecatedKey("languageSpecificParameters") .fields( PropertyFieldDefinition.build(CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY) .name("Language Key") .description("Ex: java, cs, cpp...") .type(PropertyType.STRING) .build(), PropertyFieldDefinition.build(CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY) .name("Development cost") .description("If left blank, the generic value defined in this section will be used.") .type(PropertyType.FLOAT) .build()) .build()); } }
3,589
46.236842
149
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/ExclusionProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.config; import java.util.List; import org.sonar.api.CoreProperties; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; public class ExclusionProperties { private ExclusionProperties() { // only static stuff } public static List<PropertyDefinition> all() { return List.of( // COVERAGE PropertyDefinition.builder(CoreProperties.PROJECT_COVERAGE_EXCLUSIONS_PROPERTY) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_COVERAGE_EXCLUSIONS) .type(PropertyType.STRING) .multiValues(true) .onQualifiers(Qualifiers.PROJECT) .build(), // FILES PropertyDefinition.builder(CoreProperties.GLOBAL_EXCLUSIONS_PROPERTY) .name("Global Source File Exclusions") .multiValues(true) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_FILES_EXCLUSIONS) .index(0) .build(), PropertyDefinition.builder(CoreProperties.GLOBAL_TEST_EXCLUSIONS_PROPERTY) .name("Global Test File Exclusions") .multiValues(true) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_FILES_EXCLUSIONS) .index(1) .build(), PropertyDefinition.builder(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY) .name("Source File Exclusions") .multiValues(true) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_FILES_EXCLUSIONS) .onQualifiers(Qualifiers.PROJECT) .index(0) .build(), PropertyDefinition.builder(CoreProperties.PROJECT_INCLUSIONS_PROPERTY) .name("Source File Inclusions") .multiValues(true) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_FILES_EXCLUSIONS) .onQualifiers(Qualifiers.PROJECT) .index(1) .build(), PropertyDefinition.builder(CoreProperties.PROJECT_TEST_EXCLUSIONS_PROPERTY) .name("Test File Exclusions") .multiValues(true) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_FILES_EXCLUSIONS) .onQualifiers(Qualifiers.PROJECT) .index(2) .build(), PropertyDefinition.builder(CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY) .name("Test File Inclusions") .multiValues(true) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(CoreProperties.SUBCATEGORY_FILES_EXCLUSIONS) .onQualifiers(Qualifiers.PROJECT) .index(3) .build() ); } }
3,601
35.383838
85
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/Frequency.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.config; public enum Frequency { WEEKLY("Weekly", 7), MONTHLY("Monthly", 30), TRIMESTRIAL("Trimestrial", 90), YEARLY("Yearly", 365); final String description; final int days; public String getDescription() { return this.description; } public int getDays() { return this.days; } Frequency(String description, int days) { this.description = description; this.days = days; } }
1,284
28.204545
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/IssueExclusionProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.config; import java.util.List; import org.sonar.api.CoreProperties; import org.sonar.api.PropertyType; import org.sonar.api.config.PropertyDefinition; import org.sonar.api.config.PropertyFieldDefinition; import org.sonar.api.resources.Qualifiers; public final class IssueExclusionProperties { public static final String SUB_CATEGORY_IGNORE_ISSUES = "issues"; public static final String EXCLUSION_KEY_PREFIX = "sonar.issue.ignore"; public static final String INCLUSION_KEY_PREFIX = "sonar.issue.enforce"; public static final String MULTICRITERIA_SUFFIX = ".multicriteria"; public static final String PATTERNS_MULTICRITERIA_EXCLUSION_KEY = EXCLUSION_KEY_PREFIX + MULTICRITERIA_SUFFIX; public static final String PATTERNS_MULTICRITERIA_INCLUSION_KEY = INCLUSION_KEY_PREFIX + MULTICRITERIA_SUFFIX; public static final String RESOURCE_KEY = "resourceKey"; private static final String PROPERTY_FILE_PATH_PATTERN = "File Path Pattern"; public static final String RULE_KEY = "ruleKey"; private static final String PROPERTY_RULE_KEY_PATTERN = "Rule Key Pattern"; private static final String PROPERTY_RULE_KEY_PATTERN_HELP = "<br/>A rule key pattern consists of the rule repository name, followed by a colon, followed by a rule key " + "or rule name fragment. For example:" + "<ul><li>java:S1195</li><li>java:*Naming*</li></ul>"; public static final String BLOCK_SUFFIX = ".block"; public static final String PATTERNS_BLOCK_KEY = EXCLUSION_KEY_PREFIX + BLOCK_SUFFIX; public static final String BEGIN_BLOCK_REGEXP = "beginBlockRegexp"; public static final String END_BLOCK_REGEXP = "endBlockRegexp"; public static final String ALLFILE_SUFFIX = ".allfile"; public static final String PATTERNS_ALLFILE_KEY = EXCLUSION_KEY_PREFIX + ALLFILE_SUFFIX; public static final String FILE_REGEXP = "fileRegexp"; private IssueExclusionProperties() { // only static } public static List<PropertyDefinition> all() { return List.of( PropertyDefinition.builder(PATTERNS_MULTICRITERIA_EXCLUSION_KEY) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(SUB_CATEGORY_IGNORE_ISSUES) .name("Ignore Issues on Multiple Criteria") .description("Patterns to ignore issues on certain components and for certain coding rules." + PROPERTY_RULE_KEY_PATTERN_HELP) .onQualifiers(Qualifiers.PROJECT) .index(3) .fields( PropertyFieldDefinition.build(RULE_KEY) .name(PROPERTY_RULE_KEY_PATTERN) .description("Pattern to match rules which should be ignored.") .type(PropertyType.STRING) .build(), PropertyFieldDefinition.build(RESOURCE_KEY) .name(PROPERTY_FILE_PATH_PATTERN) .description("Pattern to match files which should be ignored.") .type(PropertyType.STRING) .build() ) .build(), PropertyDefinition.builder(PATTERNS_BLOCK_KEY) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(SUB_CATEGORY_IGNORE_ISSUES) .name("Ignore Issues in Blocks") .description("Patterns to ignore all issues on specific blocks of code, " + "while continuing to scan and mark issues on the remainder of the file.") .onQualifiers(Qualifiers.PROJECT) .index(2) .fields( PropertyFieldDefinition.build(BEGIN_BLOCK_REGEXP) .name("Regular Expression for Start of Block") .description("If this regular expression is found in a file, then following lines are ignored until end of block.") .type(PropertyType.STRING) .build(), PropertyFieldDefinition.build(END_BLOCK_REGEXP) .name("Regular Expression for End of Block") .description("If specified, this regular expression is used to determine the end of code blocks to ignore. If not, then block ends at the end of file.") .type(PropertyType.STRING) .build() ) .build(), PropertyDefinition.builder(PATTERNS_ALLFILE_KEY) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(SUB_CATEGORY_IGNORE_ISSUES) .name("Ignore Issues on Files") .description("Patterns to ignore all issues on files that contain a block of code matching a given regular expression.") .onQualifiers(Qualifiers.PROJECT) .index(1) .fields( PropertyFieldDefinition.build(FILE_REGEXP) .name("Regular Expression") .description("If this regular expression is found in a file, then the whole file is ignored.") .type(PropertyType.STRING) .build() ) .build(), PropertyDefinition.builder(PATTERNS_MULTICRITERIA_INCLUSION_KEY) .category(CoreProperties.CATEGORY_EXCLUSIONS) .subCategory(SUB_CATEGORY_IGNORE_ISSUES) .name("Restrict Scope of Coding Rules") .description("Patterns to restrict the application of a rule to only certain components, ignoring all others." + PROPERTY_RULE_KEY_PATTERN_HELP) .onQualifiers(Qualifiers.PROJECT) .index(4) .fields( PropertyFieldDefinition.build(RULE_KEY) .name(PROPERTY_RULE_KEY_PATTERN) .description("Pattern used to match rules which should be restricted.") .type(PropertyType.STRING) .build(), PropertyFieldDefinition.build(RESOURCE_KEY) .name(PROPERTY_FILE_PATH_PATTERN) .description("Pattern used to match files to which the rules should be restricted.") .type(PropertyType.STRING) .build() ) .build() ); } }
6,572
45.617021
171
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/Logback.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.core.config; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.joran.JoranConfigurator; import ch.qos.logback.core.joran.spi.JoranException; import ch.qos.logback.core.util.StatusPrinter; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.slf4j.LoggerFactory; /** * Configure Logback * * @since 2.12 */ public class Logback { private Logback() { // only statics } public static void configure(String classloaderPath, Map<String, String> substitutionVariables) { InputStream input = Logback.class.getResourceAsStream(classloaderPath); if (input == null) { throw new IllegalArgumentException("Logback configuration not found in classloader: " + classloaderPath); } configure(input, substitutionVariables); } public static void configure(File logbackFile, Map<String, String> substitutionVariables) { try { FileInputStream input = FileUtils.openInputStream(logbackFile); configure(input, substitutionVariables); } catch (IOException e) { throw new IllegalArgumentException("Fail to load the Logback configuration: " + logbackFile, e); } } /** * Note that this method closes the input stream */ private static void configure(InputStream input, Map<String, String> substitutionVariables) { LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); try { JoranConfigurator configurator = new JoranConfigurator(); configurator.setContext(configureContext(lc, substitutionVariables)); configurator.doConfigure(input); } catch (JoranException e) { // StatusPrinter will handle this } finally { IOUtils.closeQuietly(input); } StatusPrinter.printInCaseOfErrorsOrWarnings(lc); } private static LoggerContext configureContext(LoggerContext context, Map<String, String> substitutionVariables) { context.reset(); for (Map.Entry<String, String> entry : substitutionVariables.entrySet()) { context.putProperty(entry.getKey(), entry.getValue()); } return context; } }
3,089
33.719101
115
java