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/sonar-core/src/main/java/org/sonar/core/config/MaxTokenLifetimeOption.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.Map; import java.util.Optional; import java.util.stream.Stream; import static java.util.function.UnaryOperator.identity; import static java.util.stream.Collectors.toMap; public enum MaxTokenLifetimeOption { THIRTY_DAYS("30 days", 30), NINETY_DAYS("90 days", 90), ONE_YEAR("1 year", 365), NO_EXPIRATION("No expiration"); private static final Map<String, MaxTokenLifetimeOption> INTERVALS_MAP; static { INTERVALS_MAP = Stream.of(MaxTokenLifetimeOption.values()) .collect(toMap(MaxTokenLifetimeOption::getName, identity())); } private final String name; private final Integer days; MaxTokenLifetimeOption(String name) { this.name = name; this.days = null; } MaxTokenLifetimeOption(String name, Integer days) { this.name = name; this.days = days; } public String getName() { return name; } public Optional<Integer> getDays() { return Optional.ofNullable(days); } public static MaxTokenLifetimeOption get(String name) { return Optional.ofNullable(INTERVALS_MAP.get(name)) .orElseThrow(() -> new IllegalArgumentException("No token expiration interval with name \"" + name + "\" found.")); } }
2,072
29.043478
121
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/PurgeConstants.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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 interface PurgeConstants { String HOURS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_DAY = "sonar.dbcleaner.hoursBeforeKeepingOnlyOneSnapshotByDay"; String WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_WEEK = "sonar.dbcleaner.weeksBeforeKeepingOnlyOneSnapshotByWeek"; String WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_MONTH = "sonar.dbcleaner.weeksBeforeKeepingOnlyOneSnapshotByMonth"; String WEEKS_BEFORE_KEEPING_ONLY_ANALYSES_WITH_VERSION = "sonar.dbcleaner.weeksBeforeKeepingOnlyAnalysesWithVersion"; String WEEKS_BEFORE_DELETING_ALL_SNAPSHOTS = "sonar.dbcleaner.weeksBeforeDeletingAllSnapshots"; String DAYS_BEFORE_DELETING_CLOSED_ISSUES = "sonar.dbcleaner.daysBeforeDeletingClosedIssues"; String DAYS_BEFORE_DELETING_INACTIVE_BRANCHES_AND_PRS = "sonar.dbcleaner.daysBeforeDeletingInactiveBranchesAndPRs"; String BRANCHES_TO_KEEP_WHEN_INACTIVE = "sonar.dbcleaner.branchesToKeepWhenInactive"; String AUDIT_HOUSEKEEPING_FREQUENCY = "sonar.dbcleaner.auditHousekeeping"; }
1,860
53.735294
119
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/PurgeProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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; import static java.util.Arrays.asList; import static org.sonar.core.config.Frequency.MONTHLY; public final class PurgeProperties { public static final String DEFAULT_FREQUENCY = MONTHLY.getDescription(); private PurgeProperties() { } public static List<PropertyDefinition> all() { return asList( PropertyDefinition.builder(PurgeConstants.HOURS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_DAY) .defaultValue("24") .name("Keep only one analysis a day after") .description("After this number of hours, if there are several analyses during the same day, " + "the DbCleaner keeps the most recent one and fully deletes the other ones.") .type(PropertyType.INTEGER) .onQualifiers(Qualifiers.PROJECT) .category(CoreProperties.CATEGORY_HOUSEKEEPING) .subCategory(CoreProperties.SUBCATEGORY_GENERAL) .index(1) .build(), PropertyDefinition.builder(PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_WEEK) .defaultValue("4") .name("Keep only one analysis a week after") .description("After this number of weeks, if there are several analyses during the same week, " + "the DbCleaner keeps the most recent one and fully deletes the other ones") .type(PropertyType.INTEGER) .onQualifiers(Qualifiers.PROJECT) .category(CoreProperties.CATEGORY_HOUSEKEEPING) .subCategory(CoreProperties.SUBCATEGORY_GENERAL) .index(2) .build(), PropertyDefinition.builder(PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ONE_SNAPSHOT_BY_MONTH) .defaultValue("52") .name("Keep only one analysis a month after") .description("After this number of weeks, if there are several analyses during the same month, " + "the DbCleaner keeps the most recent one and fully deletes the other ones.") .type(PropertyType.INTEGER) .onQualifiers(Qualifiers.PROJECT) .category(CoreProperties.CATEGORY_HOUSEKEEPING) .subCategory(CoreProperties.SUBCATEGORY_GENERAL) .index(3) .build(), PropertyDefinition.builder(PurgeConstants.WEEKS_BEFORE_KEEPING_ONLY_ANALYSES_WITH_VERSION) .defaultValue("104") .name("Keep only analyses with a version event after") .description("After this number of weeks, the DbCleaner keeps only analyses with a version event associated.") .type(PropertyType.INTEGER) .onQualifiers(Qualifiers.PROJECT) .category(CoreProperties.CATEGORY_HOUSEKEEPING) .subCategory(CoreProperties.SUBCATEGORY_GENERAL) .index(4) .build(), PropertyDefinition.builder(PurgeConstants.WEEKS_BEFORE_DELETING_ALL_SNAPSHOTS) .defaultValue("260") .name("Delete all analyses after") .description("After this number of weeks, all analyses are fully deleted.") .type(PropertyType.INTEGER) .onQualifiers(Qualifiers.PROJECT) .category(CoreProperties.CATEGORY_HOUSEKEEPING) .subCategory(CoreProperties.SUBCATEGORY_GENERAL) .index(5) .build(), PropertyDefinition.builder(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES) .defaultValue("30") .name("Delete closed issues after") .description("Issues that have been closed for more than this number of days will be deleted.") .type(PropertyType.INTEGER) .onQualifiers(Qualifiers.PROJECT) .category(CoreProperties.CATEGORY_HOUSEKEEPING) .subCategory(CoreProperties.SUBCATEGORY_GENERAL) .index(6) .build()); } }
4,664
41.798165
118
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/ScannerProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.config.PropertyDefinition; import org.sonar.api.resources.Qualifiers; import static java.util.Arrays.asList; import static org.sonar.api.PropertyType.BOOLEAN; import static org.sonar.api.PropertyType.INTEGER; public class ScannerProperties { public static final String BRANCHES_DOC_LINK_SUFFIX = "/analyzing-source-code/branches/branch-analysis/"; public static final String BRANCH_NAME = "sonar.branch.name"; public static final String PULL_REQUEST_KEY = "sonar.pullrequest.key"; public static final String PULL_REQUEST_BRANCH = "sonar.pullrequest.branch"; public static final String PULL_REQUEST_BASE = "sonar.pullrequest.base"; public static final String FILE_SIZE_LIMIT = "sonar.filesize.limit"; public static final String LINKS_SOURCES_DEV = "sonar.links.scm_dev"; public static final String DISABLE_PROJECT_AND_ORG_AUTODETECTION = "sonar.keys_autodetection.disabled"; private ScannerProperties() { // only static stuff } public static List<PropertyDefinition> all() { return asList( PropertyDefinition.builder(CoreProperties.SCM_DISABLED_KEY) .name("Disable the SCM Sensor") .description("Disable the retrieval of blame information from Source Control Manager") .category(CoreProperties.CATEGORY_SCM) .type(BOOLEAN) .onQualifiers(Qualifiers.PROJECT) .defaultValue(String.valueOf(false)) .build(), PropertyDefinition.builder(CoreProperties.SCM_PROVIDER_KEY) .name("Key of the SCM provider for this project") .description("Force the provider to be used to get SCM information for this project. By default auto-detection is done. Example: svn, git.") .category(CoreProperties.CATEGORY_SCM) .onlyOnQualifiers(Qualifiers.PROJECT) .build(), PropertyDefinition.builder(BRANCH_NAME) .name("Optional name of SonarQube/SCM branch") .description("Provide a name for the branch being analyzed. It might match an existing branch of the project, otherwise a new branch will be created.") .hidden() .build(), PropertyDefinition.builder(PULL_REQUEST_BRANCH) .name("Optional name of pull request") .description("Provide a name for the pull request being analyzed. It might match an existing pull request of the project, otherwise a new pull request will be created.") .hidden() .build(), PropertyDefinition.builder(PULL_REQUEST_BASE) .name("Optional name of target branch to merge into") .description( "Defines the target branch of the pull request being analyzed. " + "If no target is defined, the main branch is used as the target.") .hidden() .build(), PropertyDefinition.builder(DISABLE_PROJECT_AND_ORG_AUTODETECTION) .name("Disables project auto-detection") .description("Disables auto-detection of project keys from scanner execution environment.") .type(BOOLEAN) .hidden() .build(), PropertyDefinition.builder(FILE_SIZE_LIMIT) .name("Limit of a file size excluded from analysis in MB") .type(INTEGER) .defaultValue("20") .description( "Allows discarding files from analysis exceeding certain sizes.") .hidden() .build()); } }
4,271
43.041237
177
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/SecurityProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.PropertyType; import org.sonar.api.config.PropertyDefinition; import static java.util.Arrays.asList; import static org.sonar.api.CoreProperties.CATEGORY_SECURITY; import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_DEFAULT_VALUE; import static org.sonar.api.CoreProperties.CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE; import static org.sonar.api.CoreProperties.CORE_FORCE_AUTHENTICATION_PROPERTY; import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE; import static org.sonar.api.CoreProperties.SONAR_VALIDATE_WEBHOOKS_PROPERTY; class SecurityProperties { private SecurityProperties() { // only static stuff } static List<PropertyDefinition> all() { return asList( PropertyDefinition.builder(CORE_FORCE_AUTHENTICATION_PROPERTY) .defaultValue(Boolean.toString(CORE_FORCE_AUTHENTICATION_DEFAULT_VALUE)) .name("Force user authentication") .description( "Forcing user authentication prevents anonymous users from accessing the SonarQube UI, or project data via the Web API. " + "Some specific read-only Web APIs, including those required to prompt authentication, are still available anonymously." + "<br><strong>Disabling this setting can expose the instance to security risks.</strong>") .type(PropertyType.BOOLEAN) .category(CATEGORY_SECURITY) .build(), PropertyDefinition.builder(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_PROPERTY) .defaultValue(Boolean.toString(CORE_ALLOW_PERMISSION_MANAGEMENT_FOR_PROJECT_ADMINS_DEFAULT_VALUE)) .name("Enable permission management for project administrators") .description( "Set if users with 'Administer' role in a project should be allowed to change project permissions. By default users with 'Administer' " + "role are allowed to change both project configuration and project permissions.") .type(PropertyType.BOOLEAN) .category(CATEGORY_SECURITY) .build(), PropertyDefinition.builder(SONAR_VALIDATE_WEBHOOKS_PROPERTY) .defaultValue(Boolean.toString(SONAR_VALIDATE_WEBHOOKS_DEFAULT_VALUE)) .name("Enable local webhooks validation") .description( "Forcing local webhooks validation prevents the creation and triggering of local webhooks" + "<br><strong>Disabling this setting can expose the instance to security risks.</strong>") .type(PropertyType.BOOLEAN) .category(CATEGORY_SECURITY) .build() ); } }
3,606
47.093333
147
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/SvnProperties.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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 SvnProperties { public static final String USER_PROP_KEY = "sonar.svn.username"; public static final String PRIVATE_KEY_PATH_PROP_KEY = "sonar.svn.privateKeyPath"; public static final String PASSWORD_PROP_KEY = "sonar.svn.password.secured"; public static final String PASSPHRASE_PROP_KEY = "sonar.svn.passphrase.secured"; private SvnProperties() { //private only } }
1,273
37.606061
84
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/TokenExpirationConstants.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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 final class TokenExpirationConstants { public static final String MAX_ALLOWED_TOKEN_LIFETIME = "sonar.auth.token.max.allowed.lifetime"; private TokenExpirationConstants() { } }
1,067
35.827586
98
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/WebConstants.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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; /** * List of web setting keys not defined in {@link org.sonar.api.CoreProperties} */ public final class WebConstants { public static final String SONAR_LF_ENABLE_GRAVATAR = "sonar.lf.enableGravatar"; public static final String SONAR_LF_GRAVATAR_SERVER_URL = "sonar.lf.gravatarServerUrl"; public static final String SONAR_LF_LOGO_URL = "sonar.lf.logoUrl"; public static final String SONAR_LF_LOGO_WIDTH_PX = "sonar.lf.logoWidthPx"; public static final String SONAR_LOGIN_MESSAGE = "sonar.login.message"; public static final String SONAR_LOGIN_DISPLAY_MESSAGE = "sonar.login.displayMessage"; private WebConstants() { } }
1,515
39.972973
89
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/config/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.config; import javax.annotation.ParametersAreNonnullByDefault;
962
37.52
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/documentation/DefaultDocumentationLinkGenerator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.documentation; import java.util.Optional; import javax.annotation.Nullable; import org.sonar.api.config.Configuration; import org.sonar.api.utils.Version; import org.sonar.core.config.CorePropertyDefinitions; import org.sonar.core.platform.SonarQubeVersion; public class DefaultDocumentationLinkGenerator implements DocumentationLinkGenerator { public static final String DOCUMENTATION_PUBLIC_URL = "https://docs.sonarqube.org/"; private final String documentationBaseUrl; public DefaultDocumentationLinkGenerator(SonarQubeVersion sonarQubeVersion, Configuration configuration) { this.documentationBaseUrl = completeUrl(configuration.get(CorePropertyDefinitions.DOCUMENTATION_BASE_URL) .orElse(DOCUMENTATION_PUBLIC_URL), sonarQubeVersion.get()); } private static String completeUrl(String baseUrl, Version version) { String url = baseUrl; if (!url.endsWith("/")) { url += "/"; } if (version.qualifier().equals("SNAPSHOT")) { url += "latest"; } else { url += version.major() + "." + version.minor(); } return url; } @Override public String getDocumentationLink(@Nullable String suffix) { return documentationBaseUrl + Optional.ofNullable(suffix).orElse(""); } }
2,111
36.052632
109
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/documentation/DocumentationLinkGenerator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.documentation; import javax.annotation.Nullable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.scanner.ScannerSide; import org.sonar.api.server.ServerSide; @ServerSide @ComputeEngineSide @ScannerSide public interface DocumentationLinkGenerator { String getDocumentationLink(@Nullable String suffix); }
1,192
33.085714
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/documentation/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. */ /** * Provides support of DI (Dependency Injection) container and management of plugins. */ @ParametersAreNonnullByDefault package org.sonar.core.documentation; import javax.annotation.ParametersAreNonnullByDefault;
1,063
37
85
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/CoreExtension.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.extension; import com.google.common.collect.ImmutableMap; import java.util.Collection; import java.util.Map; import org.sonar.api.SonarRuntime; import org.sonar.api.config.Configuration; import static java.util.Arrays.asList; public interface CoreExtension { /** * Name of the core extension. * <p> * Used in the same fashion as the key for a plugin. */ String getName(); interface Context { SonarRuntime getRuntime(); Configuration getBootConfiguration(); Context addExtension(Object component); <T> Context addExtensions(Collection<T> o); default Context addExtensions(Object component, Object... otherComponents) { addExtension(component); addExtensions(asList(otherComponents)); return this; } } void load(Context context); /** * Properties with (optionally) default values defined by the extension. * @return map of property names as keys and property default value as values */ default Map<String, String> getExtensionProperties() { return ImmutableMap.of(); } }
1,929
28.692308
80
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/CoreExtensionRepository.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.extension; import java.util.Set; import java.util.stream.Stream; public interface CoreExtensionRepository { /** * Register the loaded Core Extensions in the repository. * * @throws IllegalStateException if the setCoreExtensionNames has already been called */ void setLoadedCoreExtensions(Set<CoreExtension> coreExtensions); /** * @return a {@link Stream} of the loaded Core Extensions (if any). * * @see CoreExtension#getName() * @throws IllegalStateException if {@link #setLoadedCoreExtensions(Set)} has not been called yet */ Stream<CoreExtension> loadedCoreExtensions(); /** * Register that the specified Core Extension has been installed. * * @throws IllegalArgumentException if the specified {@link CoreExtension} has not been loaded prior to this call * ({@link #setLoadedCoreExtensions(Set)} * @throws IllegalStateException if {@link #setLoadedCoreExtensions(Set)} has not been called yet */ void installed(CoreExtension coreExtension); /** * Tells whether the repository knows of Core Extension with this exact name. * * @see CoreExtension#getName() * @throws IllegalStateException if {@link #setLoadedCoreExtensions(Set)} has not been called yet */ boolean isInstalled(String coreExtensionName); }
2,162
36.293103
115
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/CoreExtensionRepositoryImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.extension; import com.google.common.collect.ImmutableSet; import java.util.HashSet; import java.util.Set; import java.util.stream.Stream; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; public class CoreExtensionRepositoryImpl implements CoreExtensionRepository { private Set<CoreExtension> coreExtensions = null; private Set<CoreExtension> installedCoreExtensions = null; @Override public void setLoadedCoreExtensions(Set<CoreExtension> coreExtensions) { checkState(this.coreExtensions == null, "Repository has already been initialized"); this.coreExtensions = ImmutableSet.copyOf(coreExtensions); this.installedCoreExtensions = new HashSet<>(coreExtensions.size()); } @Override public Stream<CoreExtension> loadedCoreExtensions() { checkInitialized(); return coreExtensions.stream(); } @Override public void installed(CoreExtension coreExtension) { checkInitialized(); requireNonNull(coreExtension, "coreExtension can't be null"); checkArgument(coreExtensions.contains(coreExtension), "Specified CoreExtension has not been loaded first"); this.installedCoreExtensions.add(coreExtension); } @Override public boolean isInstalled(String coreExtensionName) { checkInitialized(); return installedCoreExtensions.stream() .anyMatch(t -> coreExtensionName.equals(t.getName())); } private void checkInitialized() { checkState(coreExtensions != null, "Repository has not been initialized yet"); } }
2,484
34
111
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/CoreExtensionsInstaller.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.extension; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Collection; import java.util.Optional; import java.util.function.Predicate; import org.sonar.api.SonarRuntime; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.utils.AnnotationUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.platform.ExtensionContainer; import static java.util.Objects.requireNonNull; public abstract class CoreExtensionsInstaller { private static final Logger LOG = LoggerFactory.getLogger(CoreExtensionsInstaller.class); private final SonarRuntime sonarRuntime; private final CoreExtensionRepository coreExtensionRepository; private final Class<? extends Annotation> supportedAnnotationType; protected CoreExtensionsInstaller(SonarRuntime sonarRuntime, CoreExtensionRepository coreExtensionRepository, Class<? extends Annotation> supportedAnnotationType) { this.sonarRuntime = sonarRuntime; this.coreExtensionRepository = coreExtensionRepository; this.supportedAnnotationType = supportedAnnotationType; } public static Predicate<Object> noExtensionFilter() { return t -> true; } public static Predicate<Object> noAdditionalSideFilter() { return t -> true; } /** * @param container the container into which extensions will be installed * @param extensionFilter filters extensions added to {@link CoreExtension.Context}. When it returns false, the * extension is ignored as if it had never been added to the context. * @param additionalSideFilter applied on top of filtering on {@link #supportedAnnotationType} to decide whether * extension should be added to container as an object or only as a PropertyDefinition. */ public void install(ExtensionContainer container, Predicate<Object> extensionFilter, Predicate<Object> additionalSideFilter) { coreExtensionRepository.loadedCoreExtensions() .forEach(coreExtension -> install(container, extensionFilter, additionalSideFilter, coreExtension)); } private void install(ExtensionContainer container, Predicate<Object> extensionFilter, Predicate<Object> additionalSideFilter, CoreExtension coreExtension) { String coreExtensionName = coreExtension.getName(); try { addDeclaredExtensions(container, extensionFilter, additionalSideFilter, coreExtension); LOG.debug("Installed core extension: " + coreExtensionName); coreExtensionRepository.installed(coreExtension); } catch (Exception e) { throw new RuntimeException("Failed to load core extension " + coreExtensionName, e); } } private void addDeclaredExtensions(ExtensionContainer container, Predicate<Object> extensionFilter, Predicate<Object> additionalSideFilter, CoreExtension coreExtension) { ContextImpl context = new ContextImpl(container, extensionFilter, additionalSideFilter, coreExtension.getName()); coreExtension.load(context); } private class ContextImpl implements CoreExtension.Context { private final ExtensionContainer container; private final Predicate<Object> extensionFilter; private final Predicate<Object> additionalSideFilter; private final String extensionCategory; public ContextImpl(ExtensionContainer container, Predicate<Object> extensionFilter, Predicate<Object> additionalSideFilter, String extensionCategory) { this.container = container; this.extensionFilter = extensionFilter; this.additionalSideFilter = additionalSideFilter; this.extensionCategory = extensionCategory; } @Override public SonarRuntime getRuntime() { return sonarRuntime; } @Override public Configuration getBootConfiguration() { return Optional.ofNullable(container.getComponentByType(Configuration.class)) .orElseGet(() -> new MapSettings().asConfig()); } @Override public CoreExtension.Context addExtension(Object component) { requireNonNull(component, "component can't be null"); if (!extensionFilter.test(component)) { return this; } if (!addSupportedExtension(container, additionalSideFilter, extensionCategory, component)) { container.declareExtension(extensionCategory, component); } return this; } @Override public final CoreExtension.Context addExtensions(Object component, Object... otherComponents) { addExtension(component); Arrays.stream(otherComponents).forEach(this::addExtension); return this; } @Override public <T> CoreExtension.Context addExtensions(Collection<T> components) { requireNonNull(components, "components can't be null"); components.forEach(this::addExtension); return this; } private <T> boolean addSupportedExtension(ExtensionContainer container, Predicate<Object> additionalSideFilter, String extensionCategory, T component) { if (hasSupportedAnnotation(component) && additionalSideFilter.test(component)) { container.addExtension(extensionCategory, component); return true; } return false; } private <T> boolean hasSupportedAnnotation(T component) { return AnnotationUtils.getAnnotation(component, supportedAnnotationType) != null; } } }
6,254
40.151316
172
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/CoreExtensionsLoader.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.extension; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static com.google.common.base.Preconditions.checkState; /** * Load {@link CoreExtension} and register them into the {@link CoreExtensionRepository}. */ public class CoreExtensionsLoader { private static final Logger LOG = LoggerFactory.getLogger(CoreExtensionsLoader.class); private final CoreExtensionRepository coreExtensionRepository; private final ServiceLoaderWrapper serviceLoaderWrapper; @Inject public CoreExtensionsLoader(CoreExtensionRepository coreExtensionRepository) { this(coreExtensionRepository, new ServiceLoaderWrapper()); } CoreExtensionsLoader(CoreExtensionRepository coreExtensionRepository, ServiceLoaderWrapper serviceLoaderWrapper) { this.coreExtensionRepository = coreExtensionRepository; this.serviceLoaderWrapper = serviceLoaderWrapper; } public void load() { Set<CoreExtension> coreExtensions = serviceLoaderWrapper.load(getClass().getClassLoader()); ensureNoDuplicateName(coreExtensions); coreExtensionRepository.setLoadedCoreExtensions(coreExtensions); if (!coreExtensions.isEmpty()) { LOG.info("Loaded core extensions: {}", coreExtensions.stream().map(CoreExtension::getName).collect(Collectors.joining(", "))); } } private static void ensureNoDuplicateName(Set<CoreExtension> coreExtensions) { Map<String, Long> nameCounts = coreExtensions.stream() .map(CoreExtension::getName) .collect(Collectors.groupingBy(t -> t, Collectors.counting())); Set<String> duplicatedNames = nameCounts.entrySet().stream() .filter(t -> t.getValue() > 1) .map(Map.Entry::getKey) .collect(Collectors.toSet()); checkState(duplicatedNames.isEmpty(), "Multiple core extensions declare the following names: %s", duplicatedNames.stream().sorted().collect(Collectors.joining(", "))); } }
2,868
38.30137
132
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/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.core.extension; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface PlatformLevel { /** * Supported values are: 1, 2, 3 and 4. */ int value() default 4; }
1,269
33.324324
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/PlatformLevelPredicates.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.extension; import java.util.function.Predicate; import javax.annotation.Nullable; import org.sonar.api.utils.AnnotationUtils; public final class PlatformLevelPredicates { private PlatformLevelPredicates() { // prevents instantiation } public static Predicate<Object> hasPlatformLevel(int i) { checkSupportedLevel(i, null); return o -> { PlatformLevel platformLevel = AnnotationUtils.getAnnotation(o, PlatformLevel.class); return platformLevel != null && checkSupportedLevel(platformLevel.value(), o) == i; }; } private static int checkSupportedLevel(int i, @Nullable Object annotatedObject) { boolean supported = i >= 1 && i <= 4; if (supported) { return i; } throw new IllegalArgumentException(buildErrorMsgFrom(annotatedObject)); } private static String buildErrorMsgFrom(@Nullable Object annotatedObject) { String baseErrorMsg = "Only level 1, 2, 3 and 4 are supported"; if (annotatedObject == null) { return baseErrorMsg; } else if (annotatedObject instanceof Class) { return String.format("Invalid value for annotation %s on class '%s'. %s", PlatformLevel.class.getName(), ((Class) annotatedObject).getName(), baseErrorMsg); } else { return String.format("Invalid value for annotation %s on object of type %s. %s", PlatformLevel.class.getName(), annotatedObject.getClass().getName(), baseErrorMsg); } } public static Predicate<Object> hasPlatformLevel4OrNone() { return o -> { PlatformLevel platformLevel = AnnotationUtils.getAnnotation(o, PlatformLevel.class); return platformLevel == null || checkSupportedLevel(platformLevel.value(), o) == 4; }; } }
2,583
36.449275
91
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/PluginRiskConsent.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.extension; public enum PluginRiskConsent { NOT_ACCEPTED, REQUIRED, ACCEPTED }
951
34.259259
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/ServiceLoaderWrapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.extension; import com.google.common.collect.ImmutableSet; import java.util.ServiceLoader; import java.util.Set; import javax.annotation.Nullable; public class ServiceLoaderWrapper { public Set<CoreExtension> load(@Nullable ClassLoader classLoader) { ServiceLoader<CoreExtension> loader = ServiceLoader.load(CoreExtension.class, classLoader); return ImmutableSet.copyOf(loader.iterator()); } public Set<CoreExtension> load() { return load(null); } }
1,338
35.189189
95
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/extension/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.extension; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/hash/LineRange.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.hash; import com.google.common.base.Preconditions; public class LineRange { private final int startOffset; private final int endOffset; public LineRange(int startOffset, int endOffset) { Preconditions.checkArgument(startOffset >= 0, "Start offset not valid: %s", startOffset); Preconditions.checkArgument(startOffset <= endOffset, "Line range is not valid: %s must be greater or equal than %s", endOffset, startOffset); this.startOffset = startOffset; this.endOffset = endOffset; } public int startOffset() { return startOffset; } public int endOffset() { return endOffset; } }
1,489
33.651163
146
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/hash/SourceHashComputer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.hash; import java.security.MessageDigest; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import static java.nio.charset.StandardCharsets.UTF_8; /** * Computes the hash of the source lines of a file by simply added lines of that file one by one in order with * {@link #addLine(String, boolean)}. */ public class SourceHashComputer { private final MessageDigest md5Digest = DigestUtils.getMd5Digest(); public void addLine(String line, boolean hasNextLine) { String lineToHash = hasNextLine ? (line + '\n') : line; this.md5Digest.update(lineToHash.getBytes(UTF_8)); } public String getHash() { return Hex.encodeHexString(md5Digest.digest()); } }
1,588
35.113636
110
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/hash/SourceLineHashesComputer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.hash; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.commons.codec.binary.Hex; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.StringUtils; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Objects.requireNonNull; /** * Computes the hash of each line of a given file by simply added lines of that file one by one in order with * {@link #addLine(String)}. */ public class SourceLineHashesComputer { private final MessageDigest md5Digest = DigestUtils.getMd5Digest(); private final List<String> lineHashes; public SourceLineHashesComputer() { this.lineHashes = new ArrayList<>(); } public SourceLineHashesComputer(int expectedLineCount) { this.lineHashes = new ArrayList<>(expectedLineCount); } public void addLine(String line) { requireNonNull(line, "line can not be null"); lineHashes.add(computeHash(line)); } public List<String> getLineHashes() { return Collections.unmodifiableList(lineHashes); } private String computeHash(String line) { String reducedLine = StringUtils.replaceChars(line, "\t ", ""); if (reducedLine.isEmpty()) { return ""; } return Hex.encodeHexString(md5Digest.digest(reducedLine.getBytes(UTF_8))); } }
2,222
32.681818
109
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/hash/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.hash; import javax.annotation.ParametersAreNonnullByDefault;
960
37.44
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/i18n/DefaultI18n.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.i18n; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.MessageFormat; import java.text.NumberFormat; import java.util.Collection; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.io.IOUtils; import org.sonar.api.Startable; import org.sonar.api.utils.SonarException; import org.sonar.api.utils.System2; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; import static java.nio.charset.StandardCharsets.UTF_8; public class DefaultI18n implements I18n, Startable { private static final Logger LOG = LoggerFactory.getLogger(DefaultI18n.class); private static final String BUNDLE_PACKAGE = "org.sonar.l10n."; private final PluginRepository pluginRepository; private final ResourceBundle.Control control; private final System2 system2; // the following fields are available after startup private ClassLoader classloader; private Map<String, String> propertyToBundles; public DefaultI18n(PluginRepository pluginRepository, System2 system2) { this.pluginRepository = pluginRepository; this.system2 = system2; // SONAR-2927 this.control = new ResourceBundle.Control() { @Override public Locale getFallbackLocale(String baseName, Locale locale) { Preconditions.checkNotNull(baseName); Locale defaultLocale = Locale.ENGLISH; return locale.equals(defaultLocale) ? null : defaultLocale; } }; } @Override public void start() { doStart(new I18nClassloader(pluginRepository)); } @VisibleForTesting protected void doStart(ClassLoader classloader) { this.classloader = classloader; this.propertyToBundles = new HashMap<>(); initialize(); LOG.debug("Loaded {} properties from l10n bundles", propertyToBundles.size()); } protected void initialize() { // org.sonar.l10n.core bundle is provided by sonar-core module initPlugin("core"); Collection<PluginInfo> infos = pluginRepository.getPluginInfos(); for (PluginInfo plugin : infos) { initPlugin(plugin.getKey()); } } protected void initPlugin(String pluginKey) { try { String bundleKey = BUNDLE_PACKAGE + pluginKey; ResourceBundle bundle = ResourceBundle.getBundle(bundleKey, Locale.ENGLISH, this.classloader, control); Enumeration<String> keys = bundle.getKeys(); while (keys.hasMoreElements()) { String key = keys.nextElement(); propertyToBundles.put(key, bundleKey); } } catch (MissingResourceException e) { // ignore } } @Override public void stop() { if (classloader instanceof Closeable) { IOUtils.closeQuietly((Closeable) classloader); } classloader = null; propertyToBundles = null; } @Override @CheckForNull public String message(Locale locale, String key, @Nullable String defaultValue, Object... parameters) { String bundleKey = propertyToBundles.get(key); String value = null; if (bundleKey != null) { try { ResourceBundle resourceBundle = ResourceBundle.getBundle(bundleKey, locale, classloader, control); value = resourceBundle.getString(key); } catch (MissingResourceException e1) { // ignore } } if (value == null) { value = defaultValue; } return formatMessage(value, parameters); } @Override public String age(Locale locale, long durationInMillis) { DurationLabel.Result duration = DurationLabel.label(durationInMillis); return message(locale, duration.key(), null, duration.value()); } @Override public String age(Locale locale, Date fromDate, Date toDate) { return age(locale, toDate.getTime() - fromDate.getTime()); } @Override public String ageFromNow(Locale locale, Date date) { return age(locale, system2.now() - date.getTime()); } /** * Format date for the given locale. JVM timezone is used. */ @Override public String formatDateTime(Locale locale, Date date) { return DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT, locale).format(date); } @Override public String formatDate(Locale locale, Date date) { return DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(date); } @Override public String formatDouble(Locale locale, Double value) { NumberFormat format = DecimalFormat.getNumberInstance(locale); format.setMinimumFractionDigits(1); format.setMaximumFractionDigits(1); return format.format(value); } @Override public String formatInteger(Locale locale, Integer value) { return NumberFormat.getNumberInstance(locale).format(value); } /** * Only the given locale is searched. Contrary to java.util.ResourceBundle, no strategy for locating the bundle is implemented in * this method. */ String messageFromFile(Locale locale, String filename, String relatedProperty) { String result = null; String bundleBase = propertyToBundles.get(relatedProperty); if (bundleBase == null) { // this property has no translation return null; } String filePath = bundleBase.replace('.', '/'); if (!"en".equals(locale.getLanguage())) { filePath += "_" + locale.getLanguage(); } filePath += "/" + filename; InputStream input = classloader.getResourceAsStream(filePath); if (input != null) { result = readInputStream(filePath, input); } return result; } private static String readInputStream(String filePath, InputStream input) { String result; try { result = IOUtils.toString(input, UTF_8); } catch (IOException e) { throw new SonarException("Fail to load file: " + filePath, e); } finally { IOUtils.closeQuietly(input); } return result; } public Set<String> getPropertyKeys() { return propertyToBundles.keySet(); } public Locale getEffectiveLocale(Locale locale) { Locale bundleLocale = ResourceBundle.getBundle(BUNDLE_PACKAGE + "core", locale, this.classloader, this.control).getLocale(); locale.getISO3Language(); return bundleLocale.getLanguage().isEmpty() ? Locale.ENGLISH : bundleLocale; } @CheckForNull private static String formatMessage(@Nullable String message, Object... parameters) { if (message == null || parameters.length == 0) { return message; } return MessageFormat.format(message.replaceAll("'", "''"), parameters); } }
7,785
31.173554
131
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/i18n/DurationLabel.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.i18n; import javax.annotation.CheckForNull; import javax.annotation.Nullable; class DurationLabel { private DurationLabel() { // Utility class } public static Result label(long durationInMillis) { double nbSeconds = durationInMillis / 1000.0; double nbMinutes = nbSeconds / 60; double nbHours = nbMinutes / 60; double nbDays = nbHours / 24; double nbYears = nbDays / 365; return getMessage(nbSeconds, nbMinutes, nbHours, nbDays, nbYears); } private static Result getMessage(double nbSeconds, double nbMinutes, double nbHours, double nbDays, double nbYears) { if (nbSeconds < 45) { return message("seconds"); } else if (nbSeconds < 90) { return message("minute"); } else if (nbMinutes < 45) { return message("minutes", Math.round(nbMinutes)); } else if (nbMinutes < 90) { return message("hour"); } else if (nbHours < 24) { return message("hours", Math.round(nbHours)); } else if (nbHours < 48) { return message("day"); } else if (nbDays < 30) { return message("days", (long) (Math.floor(nbDays))); } else if (nbDays < 60) { return message("month"); } else if (nbDays < 365) { return message("months", (long) (Math.floor(nbDays / 30))); } else if (nbYears < 2) { return message("year"); } return message("years", (long) (Math.floor(nbYears))); } private static Result message(String key) { return message(key, null); } private static Result message(String key, @Nullable Long value) { String durationPrefix = "duration."; return new Result(durationPrefix + key, value); } static class Result { private String key; private Long value; public Result(String key, @Nullable Long value) { this.key = key; this.value = value; } public String key() { return key; } @CheckForNull public Long value() { return value; } } }
2,822
29.031915
119
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/i18n/I18n.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.i18n; import java.util.Date; import java.util.Locale; import javax.annotation.Nullable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; @ServerSide @ComputeEngineSide public interface I18n { /** * Searches the message of the <code>key</code> for the <code>locale</code> in the list of available bundles. * <br> * If not found in any bundle, <code>defaultValue</code> is returned. * <br> * If additional parameters are given (in the objects list), the result is used as a message pattern * to use in a MessageFormat object along with the given parameters. * * @param locale the locale to translate into * @param key the key of the pattern to translate * @param defaultValue the default pattern returned when the key is not found in any bundle * @param parameters the parameters used to format the message from the translated pattern. * @return the message formatted with the translated pattern and the given parameters */ String message(final Locale locale, final String key, @Nullable final String defaultValue, final Object... parameters); /** * Return the distance in time for a duration in milliseconds. * <br> * Examples : * <ul> * <li>age(Locale.ENGLISH, 1000) -&gt; less than a minute</li> * <li>age(Locale.ENGLISH, 60000) -&gt; about a minute</li> * <li>age(Locale.ENGLISH, 120000) -&gt; 2 minutes</li> * <li>age(Locale.ENGLISH, 3600000) -&gt; about an hour</li> * <li>age(Locale.ENGLISH, 7200000) -&gt; 2 hours</li> * <li>age(Locale.ENGLISH, 86400000) -&gt; a day</li> * <li>age(Locale.ENGLISH, 172800000) -&gt; 2 days</li> * </ul> * * @since 4.2 */ String age(Locale locale, long durationInMillis); /** * Return the distance in time between two dates. * * @see I18n#age(java.util.Locale, long durationInMillis) * @since 4.2 */ String age(Locale locale, Date fromDate, Date toDate); /** * Reports the distance in time a date and now. * * @see I18n#age(java.util.Locale, java.util.Date, java.util.Date) * @since 4.2 */ String ageFromNow(Locale locale, Date date); /** * Return the formatted datetime. * <p> * Example: {@code formatDateTime(Locale.ENGLISH, DateUtils.parseDateTime("2014-01-22T19:10:03+0100"))} * returns {@code "Jan 22, 2014 7:10 PM"}. * </p> * * @since 4.2 */ String formatDateTime(Locale locale, Date date); /** * Return the formatted date. * <br> * Example: {@code formatDateTime(Locale.ENGLISH, DateUtils.parseDateTime("2014-01-22"))} * returns {@code "Jan 22, 2014"}. * * @since 4.2 */ String formatDate(Locale locale, Date date); /** * Return the formatted decimal, with always one fraction digit. * <br> * Example: {@code formatDouble(Locale.FRENCH, 10.56)} returns {@code "10,6"}. * * @since 4.4 */ String formatDouble(Locale locale, Double value); /** * Return the formatted integer. * <br> * Example: {@code formatInteger(Locale.ENGLISH, 100000)} returns {@code "100,000"}. * * @since 4.4 */ String formatInteger(Locale locale, Integer value); }
4,035
32.081967
121
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/i18n/I18nClassloader.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.i18n; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; import java.net.URL; import java.net.URLClassLoader; import java.util.List; import org.sonar.api.Plugin; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; /** * Aggregation of all plugin and core classloaders, used to search for all l10n bundles */ class I18nClassloader extends URLClassLoader { private final ClassLoader[] pluginClassloaders; public I18nClassloader(PluginRepository pluginRepository) { this(allPluginClassloaders(pluginRepository)); } @VisibleForTesting I18nClassloader(List<ClassLoader> pluginClassloaders) { super(new URL[0]); this.pluginClassloaders = pluginClassloaders.toArray(new ClassLoader[pluginClassloaders.size()]); } @Override public URL getResource(String name) { for (ClassLoader pluginClassloader : pluginClassloaders) { URL url = pluginClassloader.getResource(name); if (url != null) { return url; } } return getClass().getClassLoader().getResource(name); } @Override protected synchronized Class loadClass(String s, boolean b) throws ClassNotFoundException { throw new UnsupportedOperationException("I18n classloader does support only resources, but not classes"); } @Override public String toString() { return "i18n-classloader"; } private static List<ClassLoader> allPluginClassloaders(PluginRepository pluginRepository) { // accepted limitation: some plugins extend base plugins, sharing the same classloader, so // there may be duplicated classloaders in the list. List<ClassLoader> list = Lists.newArrayList(); for (PluginInfo info : pluginRepository.getPluginInfos()) { Plugin plugin = pluginRepository.getPluginInstance(info.getKey()); list.add(plugin.getClass().getClassLoader()); } list.add(I18nClassloader.class.getClassLoader()); return list; } }
2,846
34.148148
109
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/i18n/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.i18n; import javax.annotation.ParametersAreNonnullByDefault;
960
37.44
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssue.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.apache.commons.lang.builder.ToStringStyle; import org.sonar.api.code.CodeCharacteristic; import org.sonar.api.issue.Issue; import org.sonar.api.issue.IssueComment; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.Duration; import org.sonar.core.issue.tracking.Trackable; import static org.sonar.api.utils.DateUtils.truncateToSeconds; public class DefaultIssue implements Issue, Trackable, org.sonar.api.ce.measure.Issue { private String key = null; private RuleType type = null; private String componentUuid = null; private String componentKey = null; private String projectUuid = null; private String projectKey = null; private RuleKey ruleKey = null; private String language = null; private String severity = null; private boolean manualSeverity = false; private String message = null; private Object messageFormattings = null; private Integer line = null; private Double gap = null; private Duration effort = null; private String status = null; private String resolution = null; private String assigneeUuid = null; private String assigneeLogin = null; private String checksum = null; private String authorLogin = null; private List<DefaultIssueComment> comments = null; private Set<String> tags = null; private Set<String> codeVariants = null; // temporarily an Object as long as DefaultIssue is used by sonar-batch private Object locations = null; private boolean isFromExternalRuleEngine = false; // FUNCTIONAL DATES private Date creationDate = null; private Date updateDate = null; private Date closeDate = null; // Current changes private FieldDiffs currentChange = null; // all changes // -- contains only current change (if any) on CE side unless reopening a closed issue or copying issue from base branch // when analyzing a branch from the first time private List<FieldDiffs> changes = null; // true if the issue did not exist in the previous scan. private boolean isNew = true; // true if the issue is on a changed line on a branch using the reference branch new code strategy private boolean isOnChangedLine = false; // true if the issue is being copied between branch private boolean isCopied = false; // true if any of the locations have changed (ignoring hashes) private boolean locationsChanged = false; // True if the issue did exist in the previous scan but not in the current one. That means // that this issue should be closed. private boolean beingClosed = false; private boolean onDisabledRule = false; // true if some fields have been changed since the previous scan private boolean isChanged = false; // true if notifications have to be sent private boolean sendNotifications = false; // Date when issue was loaded from db (only when isNew=false) private Long selectedAt = null; private boolean quickFixAvailable = false; private boolean isNewCodeReferenceIssue = false; // true if the issue is no longer new in its branch private boolean isNoLongerNewCodeReferenceIssue = false; private String ruleDescriptionContextKey = null; @Override public String key() { return key; } public DefaultIssue setKey(String key) { this.key = key; return this; } @Override public RuleType type() { return type; } @CheckForNull @Override public CodeCharacteristic characteristic() { return null; } public DefaultIssue setType(RuleType type) { this.type = type; return this; } /** * Can be null on Views or Devs */ @Override @CheckForNull public String componentUuid() { return componentUuid; } public DefaultIssue setComponentUuid(@Nullable String s) { this.componentUuid = s; return this; } @Override public String componentKey() { return componentKey; } public DefaultIssue setComponentKey(String s) { this.componentKey = s; return this; } @Override public String projectUuid() { return projectUuid; } public DefaultIssue setProjectUuid(String s) { this.projectUuid = s; return this; } @Override public String projectKey() { return projectKey; } public DefaultIssue setProjectKey(String projectKey) { this.projectKey = projectKey; return this; } @Override public RuleKey ruleKey() { return ruleKey; } public DefaultIssue setRuleKey(RuleKey k) { this.ruleKey = k; return this; } @Override @CheckForNull public String language() { return language; } public DefaultIssue setLanguage(@Nullable String l) { this.language = l; return this; } @Override public String severity() { return severity; } public DefaultIssue setSeverity(@Nullable String s) { Preconditions.checkArgument(s == null || Severity.ALL.contains(s), "Not a valid severity: " + s); this.severity = s; return this; } public boolean manualSeverity() { return manualSeverity; } public DefaultIssue setManualSeverity(boolean b) { this.manualSeverity = b; return this; } public boolean isFromExternalRuleEngine() { return isFromExternalRuleEngine; } public DefaultIssue setIsFromExternalRuleEngine(boolean isFromExternalRuleEngine) { this.isFromExternalRuleEngine = isFromExternalRuleEngine; return this; } @Override @CheckForNull public String message() { return message; } public DefaultIssue setMessage(@Nullable String s) { this.message = StringUtils.abbreviate(s, MESSAGE_MAX_SIZE); return this; } @CheckForNull public <T> T getMessageFormattings() { return (T) messageFormattings; } public DefaultIssue setMessageFormattings(@Nullable Object messageFormattings) { this.messageFormattings = messageFormattings; return this; } @Override @CheckForNull public Integer line() { return line; } public DefaultIssue setLine(@Nullable Integer l) { Preconditions.checkArgument(l == null || l > 0, "Line must be null or greater than zero (got %s)", l); this.line = l; return this; } @Override @CheckForNull public Double gap() { return gap; } public DefaultIssue setGap(@Nullable Double d) { Preconditions.checkArgument(d == null || d >= 0, "Gap must be greater than or equal 0 (got %s)", d); this.gap = d; return this; } /** * Elapsed time to fix the issue */ @Override @CheckForNull public Duration effort() { return effort; } @CheckForNull public Long effortInMinutes() { return effort != null ? effort.toMinutes() : null; } public DefaultIssue setEffort(@Nullable Duration t) { this.effort = t; return this; } @Override public String status() { return status; } public DefaultIssue setStatus(String s) { Preconditions.checkArgument(!Strings.isNullOrEmpty(s), "Status must be set"); this.status = s; return this; } @Override @CheckForNull public String resolution() { return resolution; } public DefaultIssue setResolution(@Nullable String s) { this.resolution = s; return this; } @Override @CheckForNull public String assignee() { return assigneeUuid; } public DefaultIssue setAssigneeUuid(@Nullable String s) { this.assigneeUuid = s; return this; } @CheckForNull public String assigneeLogin() { return assigneeLogin; } public DefaultIssue setAssigneeLogin(@Nullable String s) { this.assigneeLogin = s; return this; } @Override public Date creationDate() { return creationDate; } public DefaultIssue setCreationDate(Date d) { this.creationDate = truncateToSeconds(d); return this; } @Override @CheckForNull public Date updateDate() { return updateDate; } public DefaultIssue setUpdateDate(@Nullable Date d) { this.updateDate = truncateToSeconds(d); return this; } @Override @CheckForNull public Date closeDate() { return closeDate; } public DefaultIssue setCloseDate(@Nullable Date d) { this.closeDate = truncateToSeconds(d); return this; } @CheckForNull public String checksum() { return checksum; } public DefaultIssue setChecksum(@Nullable String s) { this.checksum = s; return this; } @Override public boolean isNew() { return isNew; } public boolean isOnChangedLine() { return isOnChangedLine; } @Override public boolean isCopied() { return isCopied; } public DefaultIssue setCopied(boolean b) { isCopied = b; return this; } public boolean locationsChanged() { return locationsChanged; } public DefaultIssue setLocationsChanged(boolean locationsChanged) { this.locationsChanged = locationsChanged; return this; } public DefaultIssue setNew(boolean b) { isNew = b; return this; } public DefaultIssue setIsOnChangedLine(boolean b) { isOnChangedLine = b; return this; } /** * True when one of the following conditions is true : * <ul> * <li>the related component has been deleted or renamed</li> * <li>the rule has been deleted (eg. on plugin uninstall)</li> * <li>the rule has been disabled in the Quality profile</li> * </ul> */ public boolean isBeingClosed() { return beingClosed; } public DefaultIssue setBeingClosed(boolean b) { beingClosed = b; return this; } public boolean isOnDisabledRule() { return onDisabledRule; } public DefaultIssue setOnDisabledRule(boolean b) { onDisabledRule = b; return this; } public boolean isChanged() { return isChanged; } public DefaultIssue setChanged(boolean b) { isChanged = b; return this; } public boolean mustSendNotifications() { return sendNotifications; } public DefaultIssue setSendNotifications(boolean b) { sendNotifications = b; return this; } /** * @deprecated since 9.4, attribute was already not returning any element since 5.2 */ @Deprecated @Override @CheckForNull public String attribute(String key) { return null; } /** * @deprecated since 9.4, attribute was already not returning any element since 5.2 */ @Deprecated @Override public Map<String, String> attributes() { return new HashMap<>(); } @Override @CheckForNull public String authorLogin() { return authorLogin; } public DefaultIssue setAuthorLogin(@Nullable String s) { this.authorLogin = s; return this; } public DefaultIssue setFieldChange(IssueChangeContext context, String field, @Nullable Serializable oldValue, @Nullable Serializable newValue) { if (!Objects.equals(oldValue, newValue)) { if (currentChange == null) { currentChange = new FieldDiffs(); currentChange.setUserUuid(context.userUuid()); currentChange.setCreationDate(context.date()); currentChange.setWebhookSource(context.getWebhookSource()); currentChange.setExternalUser(context.getExternalUser()); addChange(currentChange); } currentChange.setDiff(field, oldValue, newValue); } return this; } public DefaultIssue setCurrentChange(FieldDiffs currentChange) { this.currentChange = currentChange; addChange(currentChange); return this; } public DefaultIssue setCurrentChangeWithoutAddChange(@Nullable FieldDiffs currentChange) { this.currentChange = currentChange; return this; } public boolean isQuickFixAvailable() { return quickFixAvailable; } public DefaultIssue setQuickFixAvailable(boolean quickFixAvailable) { this.quickFixAvailable = quickFixAvailable; return this; } public boolean isNewCodeReferenceIssue() { return isNewCodeReferenceIssue; } public DefaultIssue setIsNewCodeReferenceIssue(boolean isNewCodeReferenceIssue) { this.isNewCodeReferenceIssue = isNewCodeReferenceIssue; return this; } public boolean isNoLongerNewCodeReferenceIssue() { return isNoLongerNewCodeReferenceIssue; } public DefaultIssue setIsNoLongerNewCodeReferenceIssue(boolean isNoLongerNewCodeReferenceIssue) { this.isNoLongerNewCodeReferenceIssue = isNoLongerNewCodeReferenceIssue; return this; } // true if the issue is new on a reference branch, // but it's not persisted as such due to being created before the SQ 9.3 migration public boolean isToBeMigratedAsNewCodeReferenceIssue() { return isOnChangedLine && !isNewCodeReferenceIssue && !isNoLongerNewCodeReferenceIssue; } @CheckForNull public FieldDiffs currentChange() { return currentChange; } public DefaultIssue addChange(@Nullable FieldDiffs change) { if (change == null) { return this; } if (changes == null) { changes = new ArrayList<>(); } changes.add(change); return this; } public List<FieldDiffs> changes() { if (changes == null) { return Collections.emptyList(); } return ImmutableList.copyOf(changes); } public DefaultIssue addComment(DefaultIssueComment comment) { if (comments == null) { comments = new ArrayList<>(); } comments.add(comment); return this; } /** * @deprecated since 7.2, comments are not more available */ @Override @Deprecated public List<IssueComment> comments() { return Collections.emptyList(); } public List<DefaultIssueComment> defaultIssueComments() { if (comments == null) { return Collections.emptyList(); } return ImmutableList.copyOf(comments); } @CheckForNull public Long selectedAt() { return selectedAt; } public DefaultIssue setSelectedAt(@Nullable Long d) { this.selectedAt = d; return this; } @CheckForNull public <T> T getLocations() { return (T) locations; } public DefaultIssue setLocations(@Nullable Object locations) { this.locations = locations; return this; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DefaultIssue that = (DefaultIssue) o; return Objects.equals(key, that.key); } @Override public int hashCode() { return key != null ? key.hashCode() : 0; } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); } @Override public Set<String> tags() { if (tags == null) { return Set.of(); } else { return ImmutableSet.copyOf(tags); } } public DefaultIssue setTags(Collection<String> tags) { this.tags = new LinkedHashSet<>(tags); return this; } @Override public Set<String> codeVariants() { if (codeVariants == null) { return Set.of(); } else { return ImmutableSet.copyOf(codeVariants); } } public DefaultIssue setCodeVariants(Collection<String> codeVariants) { this.codeVariants = new LinkedHashSet<>(codeVariants); return this; } public Optional<String> getRuleDescriptionContextKey() { return Optional.ofNullable(ruleDescriptionContextKey); } public DefaultIssue setRuleDescriptionContextKey(@Nullable String ruleDescriptionContextKey) { this.ruleDescriptionContextKey = ruleDescriptionContextKey; return this; } @Override public Integer getLine() { return line; } @Override public String getMessage() { return message; } @Override public String getLineHash() { return checksum; } @Override public RuleKey getRuleKey() { return ruleKey; } @Override public String getStatus() { return status; } @Override public Date getUpdateDate() { return updateDate; } }
17,308
22.646175
146
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/DefaultIssueComment.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue; import java.io.Serializable; import java.util.Date; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.core.util.Uuids; /** * PLUGINS MUST NOT BE USED THIS CLASS * * @since 3.6 */ public class DefaultIssueComment implements Serializable { private String issueKey; private String userUuid; private Date createdAt; private Date updatedAt; private String key; private String markdownText; private boolean isNew; public static DefaultIssueComment create(String issueKey, @Nullable String userUuid, String markdownText) { DefaultIssueComment comment = new DefaultIssueComment(); comment.setIssueKey(issueKey); comment.setKey(Uuids.create()); Date now = new Date(); comment.setUserUuid(userUuid); comment.setMarkdownText(markdownText); comment.setCreatedAt(now).setUpdatedAt(now); comment.setNew(true); return comment; } public String markdownText() { return markdownText; } public DefaultIssueComment setMarkdownText(String s) { this.markdownText = s; return this; } public String issueKey() { return issueKey; } public DefaultIssueComment setIssueKey(String s) { this.issueKey = s; return this; } public String key() { return key; } public DefaultIssueComment setKey(String key) { this.key = key; return this; } /** * The user uuid who created the comment. Null if it was automatically generated during project scan. */ @CheckForNull public String userUuid() { return userUuid; } public DefaultIssueComment setUserUuid(@Nullable String userUuid) { this.userUuid = userUuid; return this; } public Date createdAt() { return createdAt; } public DefaultIssueComment setCreatedAt(Date createdAt) { this.createdAt = createdAt; return this; } public Date updatedAt() { return updatedAt; } public DefaultIssueComment setUpdatedAt(@Nullable Date updatedAt) { this.updatedAt = updatedAt; return this; } public boolean isNew() { return isNew; } public DefaultIssueComment setNew(boolean b) { isNew = b; return this; } }
3,043
23.747967
109
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/FieldDiffs.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import static com.google.common.base.Strings.emptyToNull; import static com.google.common.base.Strings.isNullOrEmpty; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.apache.commons.lang.StringUtils.trimToNull; /** * PLUGINS MUST NOT USE THIS CLASS, EXCEPT FOR UNIT TESTING. * * @since 3.6 */ public class FieldDiffs implements Serializable { private static final String CHAR_TO_ESCAPE = "|,{}=:"; private static final String ASSIGNEE = "assignee"; private static final String ENCODING_PREFIX = "{base64:"; private static final String ENCODING_SUFFIX = "}"; private static final String WEBHOOK_SOURCE = "webhookSource"; private static final String EXTERNAL_USER_KEY = "externalUser"; private final Map<String, Diff> diffs = new LinkedHashMap<>(); private String issueKey = null; private String userUuid = null; private Date creationDate = null; private String externalUser = null; private String webhookSource = null; public Map<String, Diff> diffs() { if (diffs.containsKey(ASSIGNEE)) { Map<String, Diff> result = new LinkedHashMap<>(diffs); result.put(ASSIGNEE, decode(result.get(ASSIGNEE))); return result; } return diffs; } public Diff get(String field) { if (field.equals(ASSIGNEE)) { return decode(diffs.get(ASSIGNEE)); } return diffs.get(field); } public Optional<String> userUuid() { return Optional.ofNullable(userUuid); } public FieldDiffs setUserUuid(@Nullable String s) { this.userUuid = s; return this; } public Date creationDate() { return creationDate; } public FieldDiffs setCreationDate(Date creationDate) { this.creationDate = creationDate; return this; } public Optional<String> issueKey() { return Optional.ofNullable(issueKey); } public FieldDiffs setIssueKey(@Nullable String issueKey) { this.issueKey = issueKey; return this; } public Optional<String> externalUser() { return Optional.ofNullable(externalUser); } public FieldDiffs setExternalUser(@Nullable String externalUser) { this.externalUser = externalUser; return this; } public Optional<String> webhookSource() { return Optional.ofNullable(webhookSource); } public FieldDiffs setWebhookSource(@Nullable String webhookSource) { this.webhookSource = webhookSource; return this; } @SuppressWarnings("unchecked") public FieldDiffs setDiff(String field, @Nullable Serializable oldValue, @Nullable Serializable newValue) { Diff diff = diffs.get(field); if (field.equals(ASSIGNEE)) { oldValue = encodeField(oldValue); newValue = encodeField(newValue); } if (diff == null) { diff = new Diff(oldValue, newValue); diffs.put(field, diff); } else { diff.setNewValue(newValue); } return this; } public String toEncodedString() { return serialize(true); } @Override public String toString() { return serialize(false); } private String serialize(boolean shouldEncode) { List<String> serializedStrings = new ArrayList<>(); if (isNotBlank(webhookSource)) { serializedStrings.add(WEBHOOK_SOURCE + "=" + webhookSource); } if (isNotBlank(externalUser)) { serializedStrings.add(EXTERNAL_USER_KEY + "=" + externalUser); } diffs.entrySet().stream() .map(entry -> serializeKeyValuePair(shouldEncode, entry.getKey(), entry.getValue())) .forEach(serializedStrings::add); return StringUtils.join(serializedStrings, ","); } private static String serializeKeyValuePair(boolean shouldEncode, String key, Diff values) { String serializedValues = shouldEncode ? values.toEncodedString() : values.toString(); return key + "=" + serializedValues; } public static FieldDiffs parse(@Nullable String s) { FieldDiffs diffs = new FieldDiffs(); if (isNullOrEmpty(s)) { return diffs; } for (String field : s.split(",")) { if (field.isEmpty()) { continue; } String[] keyValues = field.split("=", 2); String key = keyValues[0]; if (keyValues.length == 2) { String values = keyValues[1]; if (EXTERNAL_USER_KEY.equals(key)) { diffs.setExternalUser(trimToNull(values)); } else if (WEBHOOK_SOURCE.equals(key)) { diffs.setWebhookSource(trimToNull(values)); } else { addDiff(diffs, key, values); } } else { diffs.setDiff(key, null, null); } } return diffs; } private static void addDiff(FieldDiffs diffs, String key, String values) { int split = values.indexOf('|'); if (split > -1) { diffs.setDiff(key, emptyToNull(values.substring(0, split)), emptyToNull(values.substring(split + 1))); } else { diffs.setDiff(key, null, emptyToNull(values)); } } @SuppressWarnings("unchecked") Diff decode(Diff encoded) { return new Diff( decodeField(encoded.oldValue), decodeField(encoded.newValue) ); } private static Serializable decodeField(@Nullable Serializable field) { if (field == null || !isEncoded(field)) { return field; } String encodedField = field.toString(); String value = encodedField.substring(ENCODING_PREFIX.length(), encodedField.indexOf(ENCODING_SUFFIX)); return new String(Base64.getDecoder().decode(value), StandardCharsets.UTF_8); } private static Serializable encodeField(@Nullable Serializable field) { if (field == null || !shouldEncode(field.toString())) { return field; } return ENCODING_PREFIX + Base64.getEncoder().encodeToString(field.toString().getBytes(StandardCharsets.UTF_8)) + ENCODING_SUFFIX; } private static boolean shouldEncode(String field) { return !field.isEmpty() && !isEncoded(field) && containsCharToEscape(field); } private static boolean containsCharToEscape(Serializable s) { return StringUtils.containsAny(s.toString(), CHAR_TO_ESCAPE); } private static boolean isEncoded(Serializable field) { return field.toString().startsWith(ENCODING_PREFIX) && field.toString().endsWith(ENCODING_SUFFIX); } public static class Diff<T extends Serializable> implements Serializable { private T oldValue; private T newValue; public Diff(@Nullable T oldValue, @Nullable T newValue) { this.oldValue = oldValue; this.newValue = newValue; } @CheckForNull public T oldValue() { return oldValue; } @CheckForNull public Long oldValueLong() { return toLong(oldValue); } @CheckForNull public T newValue() { return newValue; } @CheckForNull public Long newValueLong() { return toLong(newValue); } void setNewValue(@Nullable T t) { this.newValue = t; } @CheckForNull private static Long toLong(@Nullable Serializable value) { if (value != null && !"".equals(value)) { try { return Long.valueOf((String) value); } catch (ClassCastException e) { return (Long) value; } } return null; } private String toEncodedString() { return serialize(true); } @Override public String toString() { return serialize(false); } private String serialize(boolean shouldEncode) { StringBuilder sb = new StringBuilder(); if (oldValue != null) { sb.append(shouldEncode ? oldValue : decodeField(oldValue)); sb.append('|'); } if (newValue != null) { sb.append(shouldEncode ? newValue : decodeField(newValue)); } return sb.toString(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Diff<?> diff = (Diff<?>) o; return Objects.equals(oldValue, diff.oldValue) && Objects.equals(newValue, diff.newValue); } @Override public int hashCode() { return Objects.hash(oldValue, newValue); } } }
9,352
27.428571
133
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/IssueChangeContext.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue; import java.io.Serializable; import java.util.Date; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static java.util.Objects.requireNonNull; public class IssueChangeContext implements Serializable { private final String userUuid; private final Date date; private final boolean scan; private final boolean refreshMeasures; private final String externalUser; private final String webhookSource; private IssueChangeContext(Date date, boolean scan, boolean refreshMeasures, @Nullable String userUuid, @Nullable String externalUser, @Nullable String webhookSource) { this.userUuid = userUuid; this.date = requireNonNull(date); this.scan = scan; this.refreshMeasures = refreshMeasures; this.externalUser = externalUser; this.webhookSource = webhookSource; } @CheckForNull public String userUuid() { return userUuid; } public Date date() { return date; } public boolean scan() { return scan; } public boolean refreshMeasures() { return refreshMeasures; } @Nullable public String getExternalUser() { return externalUser; } @Nullable public String getWebhookSource() { return webhookSource; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IssueChangeContext that = (IssueChangeContext) o; return scan == that.scan && refreshMeasures == that.refreshMeasures && Objects.equals(userUuid, that.userUuid) && date.equals(that.date) && Objects.equals(externalUser, that.getExternalUser()) && Objects.equals(webhookSource, that.getWebhookSource()); } @Override public int hashCode() { return Objects.hash(userUuid, date, scan, refreshMeasures, externalUser, webhookSource); } public static IssueChangeContextBuilder newBuilder() { return new IssueChangeContextBuilder(); } public static IssueChangeContextBuilder issueChangeContextByScanBuilder(Date date) { return newBuilder().withScan().setUserUuid(null).setDate(date); } public static IssueChangeContextBuilder issueChangeContextByUserBuilder(Date date, @Nullable String userUuid) { return newBuilder().setUserUuid(userUuid).setDate(date); } public static final class IssueChangeContextBuilder { private String userUuid; private Date date; private boolean scan = false; private boolean refreshMeasures = false; private String externalUser; private String webhookSource; private IssueChangeContextBuilder() { } public IssueChangeContextBuilder setUserUuid(@Nullable String userUuid) { this.userUuid = userUuid; return this; } public IssueChangeContextBuilder setDate(Date date) { this.date = date; return this; } public IssueChangeContextBuilder withScan() { this.scan = true; return this; } public IssueChangeContextBuilder withRefreshMeasures() { this.refreshMeasures = true; return this; } public IssueChangeContextBuilder setExternalUser(@Nullable String externalUser) { this.externalUser = externalUser; return this; } public IssueChangeContextBuilder setWebhookSource(@Nullable String webhookSource) { this.webhookSource = webhookSource; return this; } public IssueChangeContext build() { return new IssueChangeContext(date, scan, refreshMeasures, userUuid, externalUser, webhookSource); } } }
4,434
28.177632
141
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/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.issue; import javax.annotation.ParametersAreNonnullByDefault;
961
37.48
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/AbstractTracker.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Objects; import java.util.function.Function; import javax.annotation.Nonnull; import org.apache.commons.lang.StringUtils; import org.sonar.api.rule.RuleKey; import static java.util.Comparator.comparing; public class AbstractTracker<RAW extends Trackable, BASE extends Trackable> { protected void match(Tracking<RAW, BASE> tracking, Function<Trackable, SearchKey> searchKeyFactory) { if (tracking.isComplete()) { return; } Multimap<SearchKey, BASE> baseSearch = ArrayListMultimap.create(); tracking.getUnmatchedBases() .forEach(base -> baseSearch.put(searchKeyFactory.apply(base), base)); tracking.getUnmatchedRaws().forEach(raw -> { SearchKey rawKey = searchKeyFactory.apply(raw); Collection<BASE> bases = baseSearch.get(rawKey); bases.stream() // Choose the more recently updated issue first to get the latest changes in siblings .sorted(comparing(Trackable::getUpdateDate).reversed()) .findFirst() .ifPresent(match -> { tracking.match(raw, match); baseSearch.remove(rawKey, match); }); }); } protected interface SearchKey { } protected static class LineAndLineHashKey implements SearchKey { private final RuleKey ruleKey; private final String lineHash; private final Integer line; protected LineAndLineHashKey(Trackable trackable) { this.ruleKey = trackable.getRuleKey(); this.line = trackable.getLine(); this.lineHash = StringUtils.defaultString(trackable.getLineHash(), ""); } @Override public boolean equals(@Nonnull Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LineAndLineHashKey that = (LineAndLineHashKey) o; // start with most discriminant field return Objects.equals(line, that.line) && lineHash.equals(that.lineHash) && ruleKey.equals(that.ruleKey); } @Override public int hashCode() { return Objects.hash(ruleKey, lineHash, line != null ? line : 0); } } protected static class LineAndLineHashAndMessage implements SearchKey { private final RuleKey ruleKey; private final String lineHash; private final String message; private final Integer line; protected LineAndLineHashAndMessage(Trackable trackable) { this.ruleKey = trackable.getRuleKey(); this.line = trackable.getLine(); this.message = trackable.getMessage(); this.lineHash = StringUtils.defaultString(trackable.getLineHash(), ""); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LineAndLineHashAndMessage that = (LineAndLineHashAndMessage) o; // start with most discriminant field return Objects.equals(line, that.line) && lineHash.equals(that.lineHash) && Objects.equals(message, that.message) && ruleKey.equals(that.ruleKey); } @Override public int hashCode() { return Objects.hash(ruleKey, lineHash, message, line != null ? line : 0); } } protected static class LineHashAndMessageKey implements SearchKey { private final RuleKey ruleKey; private final String message; private final String lineHash; LineHashAndMessageKey(Trackable trackable) { this.ruleKey = trackable.getRuleKey(); this.message = trackable.getMessage(); this.lineHash = StringUtils.defaultString(trackable.getLineHash(), ""); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LineHashAndMessageKey that = (LineHashAndMessageKey) o; // start with most discriminant field return lineHash.equals(that.lineHash) && Objects.equals(message, that.message) && ruleKey.equals(that.ruleKey); } @Override public int hashCode() { return Objects.hash(ruleKey, message, lineHash); } } protected static class LineAndMessageKey implements SearchKey { private final RuleKey ruleKey; private final String message; private final Integer line; LineAndMessageKey(Trackable trackable) { this.ruleKey = trackable.getRuleKey(); this.message = trackable.getMessage(); this.line = trackable.getLine(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LineAndMessageKey that = (LineAndMessageKey) o; // start with most discriminant field return Objects.equals(line, that.line) && Objects.equals(message, that.message) && ruleKey.equals(that.ruleKey); } @Override public int hashCode() { return Objects.hash(ruleKey, message, line != null ? line : 0); } } protected static class LineHashKey implements SearchKey { private final RuleKey ruleKey; private final String lineHash; LineHashKey(Trackable trackable) { this.ruleKey = trackable.getRuleKey(); this.lineHash = StringUtils.defaultString(trackable.getLineHash(), ""); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LineHashKey that = (LineHashKey) o; // start with most discriminant field return lineHash.equals(that.lineHash) && ruleKey.equals(that.ruleKey); } @Override public int hashCode() { return Objects.hash(ruleKey, lineHash); } } }
6,763
30.90566
152
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/BlockHashSequence.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import java.util.List; import javax.annotation.Nullable; public class BlockHashSequence { public static final int DEFAULT_HALF_BLOCK_SIZE = 5; /** * Hashes of blocks around lines. Line 1 is at index 0. */ private final int[] blockHashes; BlockHashSequence(LineHashSequence lineHashSequence, int halfBlockSize) { this.blockHashes = new int[lineHashSequence.length()]; BlockHashFactory blockHashFactory = new BlockHashFactory(lineHashSequence.getHashes(), halfBlockSize); for (int line = 1; line <= lineHashSequence.length(); line++) { blockHashes[line - 1] = blockHashFactory.getHash(); if (line - halfBlockSize > 0) { blockHashFactory.remove(lineHashSequence.getHashForLine(line - halfBlockSize).hashCode()); } if (line + 1 + halfBlockSize <= lineHashSequence.length()) { blockHashFactory.add(lineHashSequence.getHashForLine(line + 1 + halfBlockSize).hashCode()); } else { blockHashFactory.add(0); } } } public static BlockHashSequence create(LineHashSequence lineHashSequence) { return new BlockHashSequence(lineHashSequence, DEFAULT_HALF_BLOCK_SIZE); } /** * Hash of block around line. Line must be in range of valid lines. It starts with 1. */ public int getBlockHashForLine(int line) { return blockHashes[line - 1]; } public boolean hasLine(@Nullable Integer line) { return (line != null) && (line > 0) && (line <= blockHashes.length); } private static class BlockHashFactory { private static final int PRIME_BASE = 31; private final int power; private int hash = 0; public BlockHashFactory(List<String> hashes, int halfBlockSize) { int pow = 1; for (int i = 0; i < halfBlockSize * 2; i++) { pow = pow * PRIME_BASE; } this.power = pow; for (int i = 1; i <= Math.min(hashes.size(), halfBlockSize + 1); i++) { add(hashes.get(i - 1).hashCode()); } } public void add(int value) { hash = hash * PRIME_BASE + value; } public void remove(int value) { hash = hash - power * value; } public int getHash() { return hash; } } }
3,060
30.885417
106
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/BlockRecognizer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Stream; class BlockRecognizer<RAW extends Trackable, BASE extends Trackable> { /** * If base source code is available, then detect code moves through block hashes. * Only the issues associated to a line can be matched here. */ void match(Input<RAW> rawInput, Input<BASE> baseInput, Tracking<RAW, BASE> tracking) { BlockHashSequence rawHashSequence = rawInput.getBlockHashSequence(); BlockHashSequence baseHashSequence = baseInput.getBlockHashSequence(); Multimap<Integer, RAW> rawsByLine = groupByLine(tracking.getUnmatchedRaws(), rawHashSequence); Multimap<Integer, BASE> basesByLine = groupByLine(tracking.getUnmatchedBases(), baseHashSequence); Map<Integer, HashOccurrence> occurrencesByHash = new HashMap<>(); for (Integer line : basesByLine.keySet()) { int hash = baseHashSequence.getBlockHashForLine(line); HashOccurrence hashOccurrence = occurrencesByHash.get(hash); if (hashOccurrence == null) { // first occurrence in base hashOccurrence = new HashOccurrence(); hashOccurrence.baseLine = line; hashOccurrence.baseCount = 1; occurrencesByHash.put(hash, hashOccurrence); } else { hashOccurrence.baseCount++; } } for (Integer line : rawsByLine.keySet()) { int hash = rawHashSequence.getBlockHashForLine(line); HashOccurrence hashOccurrence = occurrencesByHash.get(hash); if (hashOccurrence != null) { hashOccurrence.rawLine = line; hashOccurrence.rawCount++; } } for (HashOccurrence hashOccurrence : occurrencesByHash.values()) { if (hashOccurrence.baseCount == 1 && hashOccurrence.rawCount == 1) { // Guaranteed that baseLine has been moved to rawLine, so we can map all issues on baseLine to all issues on rawLine map(rawsByLine.get(hashOccurrence.rawLine), basesByLine.get(hashOccurrence.baseLine), tracking); basesByLine.removeAll(hashOccurrence.baseLine); rawsByLine.removeAll(hashOccurrence.rawLine); } } // Check if remaining number of lines exceeds threshold. It avoids processing too many combinations. if (isOverLimit(basesByLine.keySet().size(), rawsByLine.keySet().size())) { return; } List<LinePair> possibleLinePairs = Lists.newArrayList(); for (Integer baseLine : basesByLine.keySet()) { for (Integer rawLine : rawsByLine.keySet()) { int weight = lengthOfMaximalBlock(baseInput.getLineHashSequence(), baseLine, rawInput.getLineHashSequence(), rawLine); if (weight > 0) { possibleLinePairs.add(new LinePair(baseLine, rawLine, weight)); } } } Collections.sort(possibleLinePairs, LinePairComparator.INSTANCE); for (LinePair linePair : possibleLinePairs) { // High probability that baseLine has been moved to rawLine, so we can map all issues on baseLine to all issues on rawLine map(rawsByLine.get(linePair.rawLine), basesByLine.get(linePair.baseLine), tracking); } } static boolean isOverLimit(long a, long b) { return Math.multiplyExact(a, b) >= 250_000; } /** * @param startLineA number of line from first version of text (numbering starts from 1) * @param startLineB number of line from second version of text (numbering starts from 1) */ static int lengthOfMaximalBlock(LineHashSequence hashesA, int startLineA, LineHashSequence hashesB, int startLineB) { if (!hashesA.getHashForLine(startLineA).equals(hashesB.getHashForLine(startLineB))) { return 0; } int length = 0; int ai = startLineA; int bi = startLineB; while (ai <= hashesA.length() && bi <= hashesB.length() && hashesA.getHashForLine(ai).equals(hashesB.getHashForLine(bi))) { ai++; bi++; length++; } ai = startLineA; bi = startLineB; while (ai > 0 && bi > 0 && hashesA.getHashForLine(ai).equals(hashesB.getHashForLine(bi))) { ai--; bi--; length++; } // Note that position (startA, startB) was counted twice return length - 1; } private void map(Collection<RAW> raws, Collection<BASE> bases, Tracking<RAW, BASE> result) { for (RAW raw : raws) { for (BASE base : bases) { if (result.containsUnmatchedBase(base) && base.getRuleKey().equals(raw.getRuleKey())) { result.match(raw, base); break; } } } } private static <T extends Trackable> Multimap<Integer, T> groupByLine(Stream<T> trackables, BlockHashSequence hashSequence) { // must use a MultiMap implementation which is not based on a Set collection because when T is a DefaultIssue // its hashcode method returns the same value for all instances because it is based only on the DefaultIssue's // key field which is not yet set when we do Issue Tracking Multimap<Integer, T> result = ArrayListMultimap.create(); trackables.forEach(trackable -> { Integer line = trackable.getLine(); if (hashSequence.hasLine(line)) { result.put(line, trackable); } }); return result; } private static class LinePair { int baseLine; int rawLine; int weight; public LinePair(int baseLine, int rawLine, int weight) { this.baseLine = baseLine; this.rawLine = rawLine; this.weight = weight; } } private static class HashOccurrence { int baseLine; int rawLine; int baseCount; int rawCount; } private enum LinePairComparator implements Comparator<LinePair> { INSTANCE; @Override public int compare(LinePair o1, LinePair o2) { int weightDiff = o2.weight - o1.weight; if (weightDiff != 0) { return weightDiff; } else { return Math.abs(o1.baseLine - o1.rawLine) - Math.abs(o2.baseLine - o2.rawLine); } } } }
7,010
36.095238
128
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/FilteringBaseInputWrapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import java.util.Collection; import java.util.List; import java.util.function.Predicate; import java.util.stream.Collectors; class FilteringBaseInputWrapper<BASE extends Trackable> implements Input<BASE> { private final Input<BASE> baseInput; private final List<BASE> nonClosedIssues; public FilteringBaseInputWrapper(Input<BASE> baseInput, Predicate<BASE> baseInputFilter) { this.baseInput = baseInput; Collection<BASE> baseIssues = baseInput.getIssues(); this.nonClosedIssues = baseIssues.stream() .filter(baseInputFilter) .collect(Collectors.toList()); } @Override public LineHashSequence getLineHashSequence() { return baseInput.getLineHashSequence(); } @Override public BlockHashSequence getBlockHashSequence() { return baseInput.getBlockHashSequence(); } @Override public Collection<BASE> getIssues() { return nonClosedIssues; } }
1,787
32.111111
92
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/Input.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import java.util.Collection; public interface Input<ISSUE extends Trackable> { LineHashSequence getLineHashSequence(); BlockHashSequence getBlockHashSequence(); Collection<ISSUE> getIssues(); }
1,088
32
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/LazyInput.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import java.util.Collection; import java.util.List; public abstract class LazyInput<ISSUE extends Trackable> implements Input<ISSUE> { private List<ISSUE> issues; private LineHashSequence lineHashSeq; private BlockHashSequence blockHashSeq; @Override public LineHashSequence getLineHashSequence() { if (lineHashSeq == null) { lineHashSeq = loadLineHashSequence(); } return lineHashSeq; } @Override public BlockHashSequence getBlockHashSequence() { if (blockHashSeq == null) { blockHashSeq = BlockHashSequence.create(getLineHashSequence()); } return blockHashSeq; } @Override public Collection<ISSUE> getIssues() { if (issues == null) { issues = loadIssues(); } return issues; } protected abstract LineHashSequence loadLineHashSequence(); protected abstract List<ISSUE> loadIssues(); }
1,757
28.79661
82
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/LineHashSequence.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import com.google.common.collect.SetMultimap; import com.google.common.collect.HashMultimap; import com.google.common.base.Strings; import java.util.List; import java.util.Set; import org.sonar.core.hash.SourceLineHashesComputer; /** * Sequence of hash of lines for a given file */ public class LineHashSequence { /** * Hashes of lines. Line 1 is at index 0. No null elements. */ private final List<String> hashes; private final SetMultimap<String, Integer> lineByHash; public LineHashSequence(List<String> hashes) { this.hashes = hashes; this.lineByHash = HashMultimap.create(); int lineNo = 1; for (String hash : hashes) { lineByHash.put(hash, lineNo); lineNo++; } } /** * Number of lines */ public int length() { return hashes.size(); } /** * Checks if the line, starting with 1, is defined. */ public boolean hasLine(int line) { return 0 < line && line <= hashes.size(); } /** * The lines, starting with 1, that matches the given hash. */ public Set<Integer> getLinesForHash(String hash) { return lineByHash.get(hash); } /** * Hash of the given line, which starts with 1. Return empty string * is the line does not exist. */ public String getHashForLine(int line) { if (line > 0 && line <= hashes.size()) { return Strings.nullToEmpty(hashes.get(line - 1)); } return ""; } List<String> getHashes() { return hashes; } public static LineHashSequence createForLines(List<String> lines) { SourceLineHashesComputer hashesComputer = new SourceLineHashesComputer(lines.size()); for (String line : lines) { hashesComputer.addLine(line); } return new LineHashSequence(hashesComputer.getLineHashes()); } }
2,669
25.969697
89
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/NonClosedTracking.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import org.sonar.api.issue.Issue; public class NonClosedTracking<RAW extends Trackable, BASE extends Trackable> extends Tracking<RAW, BASE> { private final Input<RAW> rawInput; private final Input<BASE> baseInput; private NonClosedTracking(Input<RAW> rawInput, Input<BASE> baseInput) { super(rawInput.getIssues(), baseInput.getIssues()); this.rawInput = rawInput; this.baseInput = baseInput; } public static <RAW extends Trackable, BASE extends Trackable> NonClosedTracking<RAW, BASE> of(Input<RAW> rawInput, Input<BASE> baseInput) { Input<BASE> nonClosedBaseInput = new FilteringBaseInputWrapper<>(baseInput, t -> !Issue.STATUS_CLOSED.equals(t.getStatus())); return new NonClosedTracking<>(rawInput, nonClosedBaseInput); } Input<RAW> getRawInput() { return rawInput; } Input<BASE> getBaseInput() { return baseInput; } }
1,757
36.404255
141
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/SimpleTracker.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import java.util.Collection; /** * A simplified version of {@link Tracker}, which doesn't use line hash sequences nor block hash sequences and * only has two steps instead of 5 steps. */ public class SimpleTracker<RAW extends Trackable, BASE extends Trackable> extends AbstractTracker<RAW, BASE> { public Tracking<RAW, BASE> track(Collection<RAW> rawInput, Collection<BASE> baseInput) { Tracking<RAW, BASE> tracking = new Tracking<>(rawInput, baseInput); // 1. match issues with same rule, same line and same line hash, but not necessarily with same message match(tracking, LineAndLineHashKey::new); // 2. match issues with same rule, same message and same line hash match(tracking, LineHashAndMessageKey::new); return tracking; } }
1,652
38.357143
110
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/Trackable.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import java.util.Date; import javax.annotation.CheckForNull; import org.sonar.api.rule.RuleKey; import org.sonar.core.issue.DefaultIssue; public interface Trackable { /** * The line index, starting with 1. Null means that * issue does not relate to a line (file issue for example). */ @CheckForNull Integer getLine(); /** * Trimmed message of issue */ @CheckForNull String getMessage(); @CheckForNull String getLineHash(); RuleKey getRuleKey(); String getStatus(); /** * Functional update date for the issue. See {@link DefaultIssue#updateDate()} */ Date getUpdateDate(); }
1,509
26.962963
80
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/Tracker.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import org.sonar.api.issue.Issue; import org.sonar.api.scanner.ScannerSide; @ScannerSide public class Tracker<RAW extends Trackable, BASE extends Trackable> extends AbstractTracker<RAW, BASE> { public NonClosedTracking<RAW, BASE> trackNonClosed(Input<RAW> rawInput, Input<BASE> baseInput) { NonClosedTracking<RAW, BASE> tracking = NonClosedTracking.of(rawInput, baseInput); // 1. match by rule, line, line hash and message match(tracking, LineAndLineHashAndMessage::new); // 2. match issues with same rule, same line and same line hash, but not necessarily with same message match(tracking, LineAndLineHashKey::new); // 3. detect code moves by comparing blocks of codes detectCodeMoves(rawInput, baseInput, tracking); // 4. match issues with same rule, same message and same line hash match(tracking, LineHashAndMessageKey::new); // 5. match issues with same rule, same line and same message match(tracking, LineAndMessageKey::new); // 6. match issues with same rule and same line hash but different line and different message. // See SONAR-2812 match(tracking, LineHashKey::new); return tracking; } public Tracking<RAW, BASE> trackClosed(NonClosedTracking<RAW, BASE> nonClosedTracking, Input<BASE> baseInput) { ClosedTracking<RAW, BASE> closedTracking = ClosedTracking.of(nonClosedTracking, baseInput); match(closedTracking, LineAndLineHashAndMessage::new); return mergedTracking(nonClosedTracking, closedTracking); } private void detectCodeMoves(Input<RAW> rawInput, Input<BASE> baseInput, Tracking<RAW, BASE> tracking) { if (!tracking.isComplete()) { new BlockRecognizer<RAW, BASE>().match(rawInput, baseInput, tracking); } } private static class ClosedTracking<RAW extends Trackable, BASE extends Trackable> extends Tracking<RAW, BASE> { private final Input<BASE> baseInput; ClosedTracking(NonClosedTracking<RAW, BASE> nonClosedTracking, Input<BASE> closedBaseInput) { super(nonClosedTracking.getRawInput().getIssues(), closedBaseInput.getIssues(), nonClosedTracking.rawToBase, nonClosedTracking.baseToRaw); this.baseInput = closedBaseInput; } public static <RAW extends Trackable, BASE extends Trackable> ClosedTracking<RAW, BASE> of(NonClosedTracking<RAW, BASE> nonClosedTracking, Input<BASE> baseInput) { Input<BASE> closedBaseInput = new FilteringBaseInputWrapper<>(baseInput, t -> Issue.STATUS_CLOSED.equals(t.getStatus())); return new ClosedTracking<>(nonClosedTracking, closedBaseInput); } public Input<BASE> getBaseInput() { return baseInput; } } private Tracking<RAW, BASE> mergedTracking(NonClosedTracking<RAW, BASE> nonClosedTracking, ClosedTracking<RAW, BASE> closedTracking) { return new Tracking<>(nonClosedTracking.getRawInput().getIssues(), concatIssues(nonClosedTracking, closedTracking), closedTracking.rawToBase, closedTracking.baseToRaw); } private static <RAW extends Trackable, BASE extends Trackable> List<BASE> concatIssues( NonClosedTracking<RAW, BASE> nonClosedTracking, ClosedTracking<RAW, BASE> closedTracking) { Collection<BASE> nonClosedIssues = nonClosedTracking.getBaseInput().getIssues(); Collection<BASE> closeIssues = closedTracking.getBaseInput().getIssues(); return Stream.concat(nonClosedIssues.stream(), closeIssues.stream()) .collect(Collectors.toList()); } }
4,431
42.45098
167
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/Tracking.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.issue.tracking; import com.google.common.base.MoreObjects; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Map; import java.util.stream.Stream; import javax.annotation.CheckForNull; public class Tracking<RAW extends Trackable, BASE extends Trackable> { /** * Matched issues -> a raw issue is associated to a base issue */ protected final IdentityHashMap<RAW, BASE> rawToBase; protected final IdentityHashMap<BASE, RAW> baseToRaw; private final Collection<RAW> raws; private final Collection<BASE> bases; Tracking(Collection<RAW> rawInput, Collection<BASE> baseInput) { this(rawInput, baseInput, new IdentityHashMap<>(), new IdentityHashMap<>()); } protected Tracking(Collection<RAW> rawInput, Collection<BASE> baseInput, IdentityHashMap<RAW, BASE> rawToBase, IdentityHashMap<BASE, RAW> baseToRaw) { this.raws = rawInput; this.bases = baseInput; this.rawToBase = rawToBase; this.baseToRaw = baseToRaw; } /** * Returns an Iterable to be traversed when matching issues. That means * that the traversal does not fail if method {@link #match(Trackable, Trackable)} * is called. */ public Stream<RAW> getUnmatchedRaws() { return raws.stream().filter(raw -> !rawToBase.containsKey(raw)); } public Map<RAW, BASE> getMatchedRaws() { return rawToBase; } @CheckForNull public BASE baseFor(RAW raw) { return rawToBase.get(raw); } /** * The base issues that are not matched by a raw issue and that need to be closed. */ public Stream<BASE> getUnmatchedBases() { return bases.stream().filter(base -> !baseToRaw.containsKey(base)); } boolean containsUnmatchedBase(BASE base) { return !baseToRaw.containsKey(base); } void match(RAW raw, BASE base) { if (!rawToBase.containsKey(raw)) { rawToBase.put(raw, base); baseToRaw.put(base, raw); } } public boolean isComplete() { return rawToBase.size() == raws.size(); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("rawToBase", rawToBase.size()) .add("baseToRaw", baseToRaw.size()) .add("raws", raws.size()) .add("bases", bases.size()) .toString(); } }
3,112
29.821782
84
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/issue/tracking/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.issue.tracking; import javax.annotation.ParametersAreNonnullByDefault;
970
37.84
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/language/LanguagesProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.language; import java.util.List; import java.util.Optional; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.springframework.context.annotation.Bean; public class LanguagesProvider { @Bean("Languages") public Languages provide(Optional<List<Language>> languages) { if (languages.isPresent()) { return new Languages(languages.get().toArray(new Language[0])); } else { return new Languages(); } } }
1,341
33.410256
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/language/UnanalyzedLanguages.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.language; public enum UnanalyzedLanguages { C("C"), CPP("C++"); String label; UnanalyzedLanguages(String label) { this.label = label; } @Override public String toString() { return label; } }
1,083
29.111111
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/language/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.language; import javax.annotation.ParametersAreNonnullByDefault;
964
37.6
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/metric/ScannerMetrics.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.metric; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.concurrent.Immutable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metrics; import org.sonar.api.scanner.ScannerSide; import org.springframework.beans.factory.annotation.Autowired; import static org.sonar.api.measures.CoreMetrics.CLASSES; import static org.sonar.api.measures.CoreMetrics.COGNITIVE_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_CLASSES; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS; import static org.sonar.api.measures.CoreMetrics.EXECUTABLE_LINES_DATA; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION; import static org.sonar.api.measures.CoreMetrics.GENERATED_LINES; import static org.sonar.api.measures.CoreMetrics.GENERATED_NCLOC; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.api.measures.CoreMetrics.NCLOC_DATA; import static org.sonar.api.measures.CoreMetrics.PUBLIC_API; import static org.sonar.api.measures.CoreMetrics.PUBLIC_UNDOCUMENTED_API; import static org.sonar.api.measures.CoreMetrics.SKIPPED_TESTS; import static org.sonar.api.measures.CoreMetrics.STATEMENTS; import static org.sonar.api.measures.CoreMetrics.TESTS; import static org.sonar.api.measures.CoreMetrics.TEST_ERRORS; import static org.sonar.api.measures.CoreMetrics.TEST_EXECUTION_TIME; import static org.sonar.api.measures.CoreMetrics.TEST_FAILURES; /** * This class is used to know the list of metrics that can be sent in the analysis report. * <p/> * Scanners should not send other metrics, and the Compute Engine should not allow other metrics. */ @Immutable @ComputeEngineSide @ScannerSide public class ScannerMetrics { private static final Set<Metric> ALLOWED_CORE_METRICS = ImmutableSet.of( GENERATED_LINES, NCLOC, NCLOC_DATA, GENERATED_NCLOC, COMMENT_LINES, PUBLIC_API, PUBLIC_UNDOCUMENTED_API, CLASSES, FUNCTIONS, STATEMENTS, COMPLEXITY, COMPLEXITY_IN_CLASSES, COMPLEXITY_IN_FUNCTIONS, COGNITIVE_COMPLEXITY, FILE_COMPLEXITY_DISTRIBUTION, FUNCTION_COMPLEXITY_DISTRIBUTION, TESTS, SKIPPED_TESTS, TEST_ERRORS, TEST_FAILURES, TEST_EXECUTION_TIME, EXECUTABLE_LINES_DATA); private final Set<Metric> metrics; @Autowired(required = false) public ScannerMetrics() { this.metrics = ALLOWED_CORE_METRICS; } @Autowired(required = false) public ScannerMetrics(Metrics[] metricsRepositories) { this.metrics = Stream.concat(getPluginMetrics(metricsRepositories), ALLOWED_CORE_METRICS.stream()).collect(Collectors.toSet()); } /** * The metrics allowed in scanner analysis reports. The measures that don't relate to * these metrics are not loaded by Compute Engine. */ public Set<Metric> getMetrics() { return metrics; } private static Stream<Metric> getPluginMetrics(Metrics[] metricsRepositories) { return Arrays.stream(metricsRepositories) .map(Metrics::getMetrics) .filter(Objects::nonNull) .flatMap(List::stream); } }
4,450
34.608
131
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/metric/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.metric; import javax.annotation.ParametersAreNonnullByDefault;
962
37.52
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/ClassDerivedBeanDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.lang.reflect.Constructor; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.lang.Nullable; /** * Taken from Spring's GenericApplicationContext.ClassDerivedBeanDefinition. * The goal is to support multiple constructors when adding extensions for plugins when no annotations are present. * Spring will pick the constructor with the highest number of arguments that it can inject. */ public class ClassDerivedBeanDefinition extends RootBeanDefinition { public ClassDerivedBeanDefinition(Class<?> beanClass) { super(beanClass); } public ClassDerivedBeanDefinition(ClassDerivedBeanDefinition original) { super(original); } /** * This method gets called from AbstractAutowireCapableBeanFactory#createBeanInstance when a bean is instantiated. * It first tries to look at annotations or any other methods provided by bean post processors. If a constructor can't be determined, it will fallback to this method. */ @Override @Nullable public Constructor<?>[] getPreferredConstructors() { Class<?> clazz = getBeanClass(); Constructor<?> primaryCtor = BeanUtils.findPrimaryConstructor(clazz); if (primaryCtor != null) { return new Constructor<?>[] {primaryCtor}; } Constructor<?>[] publicCtors = clazz.getConstructors(); if (publicCtors.length > 0) { return publicCtors; } return null; } @Override public RootBeanDefinition cloneBeanDefinition() { return new ClassDerivedBeanDefinition(this); } }
2,461
36.876923
168
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/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.platform; import java.util.HashSet; import java.util.Set; import java.util.regex.Pattern; import org.sonar.core.util.Uuids; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ComponentKeys { private static final Logger LOG = LoggerFactory.getLogger(ComponentKeys.class); private static final Pattern IDENTITY_HASH_PATTERN = Pattern.compile(".+@[a-f0-9]+"); private final Set<Class> objectsWithoutToString = new HashSet<>(); Object of(Object component) { return of(component, LOG); } Object of(Object component, Logger log) { if (component instanceof Class) { return component; } return ofInstance(component, log); } public String ofInstance(Object component) { return ofInstance(component, LOG); } public String ofClass(Class<?> clazz) { return clazz.getClassLoader() + "-" + clazz.getCanonicalName(); } String ofInstance(Object component, Logger log) { String key = component.toString(); if (IDENTITY_HASH_PATTERN.matcher(key).matches()) { if (!objectsWithoutToString.add(component.getClass())) { log.warn(String.format("Bad component key: %s. Please implement toString() method on class %s", key, component.getClass().getName())); } key += Uuids.create(); } return ofClass(component.getClass()) + "-" + key; } }
2,204
33.453125
142
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/Container.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.util.List; import java.util.Optional; public interface Container { Container add(Object... objects); <T> T getComponentByType(Class<T> type); <T> Optional<T> getOptionalComponentByType(Class<T> type); <T> List<T> getComponentsByType(Class<T> type); Container getParent(); }
1,178
31.75
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/ContainerPopulator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; @FunctionalInterface public interface ContainerPopulator<T extends Container> { void populateContainer(T container); }
998
37.423077
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/EditionProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.util.Optional; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.scanner.ScannerSide; import org.sonar.api.server.ServerSide; @ServerSide @ComputeEngineSide @ScannerSide public interface EditionProvider { enum Edition { COMMUNITY("Community"), DEVELOPER("Developer"), ENTERPRISE("Enterprise"), DATACENTER("Data Center"); private final String label; Edition(String label) { this.label = label; } public String getLabel() { return label; } } Optional<Edition> get(); }
1,429
27.6
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/ExplodedPlugin.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.io.File; import java.util.Collection; public class ExplodedPlugin { private final PluginInfo pluginInfo; private final String key; private final File main; private final Collection<File> libs; public ExplodedPlugin(PluginInfo pluginInfo, String key, File main, Collection<File> libs) { this.pluginInfo = pluginInfo; this.key = key; this.main = main; this.libs = libs; } public String getKey() { return key; } public File getMain() { return main; } public Collection<File> getLibs() { return libs; } public PluginInfo getPluginInfo() { return pluginInfo; } }
1,513
27.037037
94
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/ExtensionContainer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public interface ExtensionContainer extends Container { ExtensionContainer addExtension(@Nullable PluginInfo pluginInfo, Object extension); ExtensionContainer addExtension(@Nullable String defaultCategory, Object extension); ExtensionContainer declareExtension(@Nullable PluginInfo pluginInfo, Object extension); ExtensionContainer declareExtension(@Nullable String defaultCategory, Object extension); @CheckForNull ExtensionContainer getParent(); }
1,416
37.297297
90
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/LazyStrategy.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import javax.annotation.Nullable; import org.springframework.beans.factory.config.BeanDefinition; public class LazyStrategy extends SpringInitStrategy { @Override protected boolean isLazyInit(BeanDefinition beanDefinition, @Nullable Class<?> clazz) { return true; } }
1,156
36.322581
89
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/LazyUnlessStartableStrategy.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import org.sonar.api.Startable; import org.springframework.beans.factory.config.BeanDefinition; import javax.annotation.Nullable; public class LazyUnlessStartableStrategy extends SpringInitStrategy { @Override protected boolean isLazyInit(BeanDefinition beanDefinition, @Nullable Class<?> clazz) { return clazz == null || !Startable.class.isAssignableFrom(clazz); } }
1,257
37.121212
89
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/ListContainer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import com.google.common.collect.Iterables; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import static java.util.Collections.unmodifiableList; /** * Intended to be used in tests */ public class ListContainer implements ExtensionContainer { private final List<Object> objects = new ArrayList<>(); @Override public Container add(Object... objects) { for (Object o : objects) { if (o instanceof Module) { ((Module) o).configure(this); } else if (o instanceof Iterable) { add(Iterables.toArray((Iterable<?>) o, Object.class)); } else { this.objects.add(o); } } return this; } public List<Object> getAddedObjects() { return unmodifiableList(new ArrayList<>(objects)); } @Override public <T> T getComponentByType(Class<T> type) { throw new UnsupportedOperationException(); } @Override public <T> Optional<T> getOptionalComponentByType(Class<T> type) { throw new UnsupportedOperationException(); } @Override public <T> List<T> getComponentsByType(Class<T> type) { throw new UnsupportedOperationException(); } @Override public ExtensionContainer addExtension(@Nullable PluginInfo pluginInfo, Object extension) { add(extension); return this; } @Override public ExtensionContainer addExtension(@Nullable String defaultCategory, Object extension) { add(extension); return this; } @Override public ExtensionContainer declareExtension(@Nullable PluginInfo pluginInfo, Object extension) { return this; } @Override public ExtensionContainer declareExtension(@Nullable String defaultCategory, Object extension) { return this; } @Override public ExtensionContainer getParent() { throw new UnsupportedOperationException(); } }
2,731
27.458333
98
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/Module.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; public abstract class Module { private Container container; public Module configure(Container container) { this.container = checkNotNull(container); configureModule(); return this; } protected abstract void configureModule(); protected void add(@Nullable Object... objects) { if (objects == null) { return; } for (Object object : objects) { if (object != null) { container.add(object); } } } }
1,443
27.88
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/PlatformEditionProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.util.Optional; public class PlatformEditionProvider implements EditionProvider { @Override public Optional<Edition> get() { return Optional.of(Edition.COMMUNITY); } }
1,067
34.6
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/PluginClassLoader.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import java.io.Closeable; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.apache.commons.lang.SystemUtils; import org.sonar.api.Plugin; import org.slf4j.LoggerFactory; import org.sonar.updatecenter.common.Version; import static java.util.Collections.singleton; /** * Loads the plugin JAR files by creating the appropriate classloaders and by instantiating * the entry point classes as defined in manifests. It assumes that JAR files are compatible with current * environment (minimal sonarqube version, compatibility between plugins, ...): * <ul> * <li>server verifies compatibility of JARs before deploying them at startup (see ServerPluginRepository)</li> * <li>batch loads only the plugins deployed on server (see BatchPluginRepository)</li> * </ul> * <p/> * Plugins have their own isolated classloader, inheriting only from API classes. * Some plugins can extend a "base" plugin, sharing the same classloader. * <p/> * This class is stateless. It does not keep pointers to classloaders and {@link org.sonar.api.Plugin}. */ public class PluginClassLoader { private static final String[] DEFAULT_SHARED_RESOURCES = {"org/sonar/plugins", "com/sonar/plugins", "com/sonarsource/plugins"}; private static final Version COMPATIBILITY_MODE_MAX_VERSION = Version.create("5.2"); private final PluginClassloaderFactory classloaderFactory; public PluginClassLoader(PluginClassloaderFactory classloaderFactory) { this.classloaderFactory = classloaderFactory; } public Map<String, Plugin> load(Collection<ExplodedPlugin> plugins) { return load(plugins.stream().collect(Collectors.toMap(ExplodedPlugin::getKey, x -> x))); } public Map<String, Plugin> load(Map<String, ExplodedPlugin> pluginsByKey) { Collection<PluginClassLoaderDef> defs = defineClassloaders(pluginsByKey); Map<PluginClassLoaderDef, ClassLoader> classloaders = classloaderFactory.create(defs); return instantiatePluginClasses(classloaders); } /** * Defines the different classloaders to be created. Number of classloaders can be * different than number of plugins. */ @VisibleForTesting Collection<PluginClassLoaderDef> defineClassloaders(Map<String, ExplodedPlugin> pluginsByKey) { Map<String, PluginClassLoaderDef> classloadersByBasePlugin = new HashMap<>(); for (ExplodedPlugin plugin : pluginsByKey.values()) { PluginInfo info = plugin.getPluginInfo(); String baseKey = basePluginKey(info, pluginsByKey); PluginClassLoaderDef def = classloadersByBasePlugin.get(baseKey); if (def == null) { def = new PluginClassLoaderDef(baseKey); classloadersByBasePlugin.put(baseKey, def); } def.addFiles(singleton(plugin.getMain())); def.addFiles(plugin.getLibs()); def.addMainClass(info.getKey(), info.getMainClass()); for (String defaultSharedResource : DEFAULT_SHARED_RESOURCES) { def.getExportMask().addInclusion(String.format("%s/%s/api/", defaultSharedResource, info.getKey())); } // The plugins that extend other plugins can only add some files to classloader. // They can't change metadata like ordering strategy or compatibility mode. if (Strings.isNullOrEmpty(info.getBasePlugin())) { if (info.isUseChildFirstClassLoader()) { LoggerFactory.getLogger(getClass()).warn("Plugin {} [{}] uses a child first classloader which is deprecated", info.getName(), info.getKey()); } def.setSelfFirstStrategy(info.isUseChildFirstClassLoader()); Version minSonarPluginApiVersion = info.getMinimalSonarPluginApiVersion(); boolean compatibilityMode = minSonarPluginApiVersion != null && minSonarPluginApiVersion.compareToIgnoreQualifier(COMPATIBILITY_MODE_MAX_VERSION) < 0; if (compatibilityMode) { LoggerFactory.getLogger(getClass()).warn("API compatibility mode is no longer supported. In case of error, plugin {} [{}] should package its dependencies.", info.getName(), info.getKey()); } } } return classloadersByBasePlugin.values(); } /** * Instantiates collection of {@link org.sonar.api.Plugin} according to given metadata and classloaders * * @return the instances grouped by plugin key * @throws IllegalStateException if at least one plugin can't be correctly loaded */ private static Map<String, Plugin> instantiatePluginClasses(Map<PluginClassLoaderDef, ClassLoader> classloaders) { // instantiate plugins Map<String, Plugin> instancesByPluginKey = new HashMap<>(); for (Map.Entry<PluginClassLoaderDef, ClassLoader> entry : classloaders.entrySet()) { PluginClassLoaderDef def = entry.getKey(); ClassLoader classLoader = entry.getValue(); // the same classloader can be used by multiple plugins for (Map.Entry<String, String> mainClassEntry : def.getMainClassesByPluginKey().entrySet()) { String pluginKey = mainClassEntry.getKey(); String mainClass = mainClassEntry.getValue(); try { instancesByPluginKey.put(pluginKey, (Plugin) classLoader.loadClass(mainClass).getDeclaredConstructor().newInstance()); } catch (UnsupportedClassVersionError e) { throw new IllegalStateException(String.format("The plugin [%s] does not support Java %s", pluginKey, SystemUtils.JAVA_VERSION_TRIMMED), e); } catch (Throwable e) { throw new IllegalStateException(String.format("Fail to instantiate class [%s] of plugin [%s]", mainClass, pluginKey), e); } } } return instancesByPluginKey; } public void unload(Collection<Plugin> plugins) { for (Plugin plugin : plugins) { ClassLoader classLoader = plugin.getClass().getClassLoader(); if (classLoader instanceof Closeable && classLoader != classloaderFactory.baseClassLoader()) { try { ((Closeable) classLoader).close(); } catch (Exception e) { LoggerFactory.getLogger(getClass()).error("Fail to close classloader " + classLoader.toString(), e); } } } } /** * Get the root key of a tree of plugins. For example if plugin C depends on B, which depends on A, then * B and C must be attached to the classloader of A. The method returns A in the three cases. */ private static String basePluginKey(PluginInfo plugin, Map<String, ExplodedPlugin> pluginsByKey) { String base = plugin.getKey(); String parentKey = plugin.getBasePlugin(); while (!Strings.isNullOrEmpty(parentKey)) { PluginInfo parentPlugin = pluginsByKey.get(parentKey).getPluginInfo(); base = parentPlugin.getKey(); parentKey = parentPlugin.getBasePlugin(); } return base; } }
7,731
44.482353
166
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/PluginClassLoaderDef.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.sonar.classloader.Mask; /** * Temporary information about the classLoader to be created for a plugin (or a group of plugins). */ class PluginClassLoaderDef { private final String basePluginKey; private final Map<String, String> mainClassesByPluginKey = new HashMap<>(); private final List<File> files = new ArrayList<>(); private final Mask mask = new Mask(); private boolean selfFirstStrategy = false; PluginClassLoaderDef(String basePluginKey) { Preconditions.checkArgument(!Strings.isNullOrEmpty(basePluginKey)); this.basePluginKey = basePluginKey; } String getBasePluginKey() { return basePluginKey; } List<File> getFiles() { return files; } void addFiles(Collection<File> f) { this.files.addAll(f); } Mask getExportMask() { return mask; } boolean isSelfFirstStrategy() { return selfFirstStrategy; } void setSelfFirstStrategy(boolean selfFirstStrategy) { this.selfFirstStrategy = selfFirstStrategy; } Map<String, String> getMainClassesByPluginKey() { return mainClassesByPluginKey; } void addMainClass(String pluginKey, @Nullable String mainClass) { if (!Strings.isNullOrEmpty(mainClass)) { mainClassesByPluginKey.put(pluginKey, mainClass); } } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PluginClassLoaderDef that = (PluginClassLoaderDef) o; return basePluginKey.equals(that.basePluginKey); } @Override public int hashCode() { return basePluginKey.hashCode(); } }
2,792
26.93
98
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/PluginClassloaderFactory.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.sonar.api.scanner.ScannerSide; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.classloader.ClassloaderBuilder; import org.sonar.classloader.Mask; import static org.sonar.classloader.ClassloaderBuilder.LoadingOrder.PARENT_FIRST; import static org.sonar.classloader.ClassloaderBuilder.LoadingOrder.SELF_FIRST; /** * Builds the graph of classloaders to be used to instantiate plugins. It deals with: * <ul> * <li>isolation of plugins against core classes (except api)</li> * <li>sharing of some packages between plugins</li> * <li>loading of the libraries embedded in plugin JAR files (directory META-INF/libs)</li> * </ul> */ @ScannerSide @ServerSide @ComputeEngineSide public class PluginClassloaderFactory { // underscores are used to not conflict with plugin keys (if someday a plugin key is "api") private static final String API_CLASSLOADER_KEY = "_api_"; /** * Creates as many classloaders as requested by the input parameter. */ public Map<PluginClassLoaderDef, ClassLoader> create(Collection<PluginClassLoaderDef> defs) { ClassLoader baseClassLoader = baseClassLoader(); ClassloaderBuilder builder = new ClassloaderBuilder(); builder.newClassloader(API_CLASSLOADER_KEY, baseClassLoader); builder.setMask(API_CLASSLOADER_KEY, apiMask()); for (PluginClassLoaderDef def : defs) { builder.newClassloader(def.getBasePluginKey()); builder.setParent(def.getBasePluginKey(), API_CLASSLOADER_KEY, new Mask()); builder.setLoadingOrder(def.getBasePluginKey(), def.isSelfFirstStrategy() ? SELF_FIRST : PARENT_FIRST); for (File jar : def.getFiles()) { builder.addURL(def.getBasePluginKey(), fileToUrl(jar)); } exportResources(def, builder, defs); } return build(defs, builder); } /** * A plugin can export some resources to other plugins */ private static void exportResources(PluginClassLoaderDef def, ClassloaderBuilder builder, Collection<PluginClassLoaderDef> allPlugins) { // export the resources to all other plugins builder.setExportMask(def.getBasePluginKey(), def.getExportMask()); for (PluginClassLoaderDef other : allPlugins) { if (!other.getBasePluginKey().equals(def.getBasePluginKey())) { builder.addSibling(def.getBasePluginKey(), other.getBasePluginKey(), new Mask()); } } } /** * Builds classloaders and verifies that all of them are correctly defined */ private static Map<PluginClassLoaderDef, ClassLoader> build(Collection<PluginClassLoaderDef> defs, ClassloaderBuilder builder) { Map<PluginClassLoaderDef, ClassLoader> result = new HashMap<>(); Map<String, ClassLoader> classloadersByBasePluginKey = builder.build(); for (PluginClassLoaderDef def : defs) { ClassLoader classloader = classloadersByBasePluginKey.get(def.getBasePluginKey()); if (classloader == null) { throw new IllegalStateException(String.format("Fail to create classloader for plugin [%s]", def.getBasePluginKey())); } result.put(def, classloader); } return result; } ClassLoader baseClassLoader() { return getClass().getClassLoader(); } private static URL fileToUrl(File file) { try { return file.toURI().toURL(); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } } /** * The resources (packages) that API exposes to plugins. Other core classes (SonarQube, MyBatis, ...) * can't be accessed. * <p>To sum-up, these are the classes packaged in sonar-plugin-api.jar or available as * a transitive dependency of sonar-plugin-api</p> */ private static Mask apiMask() { return new Mask() .addInclusion("org/sonar/api/") .addInclusion("org/sonar/check/") .addInclusion("org/codehaus/stax2/") .addInclusion("org/codehaus/staxmate/") .addInclusion("com/ctc/wstx/") .addInclusion("org/slf4j/") // SLF4J bridges. Do not let plugins re-initialize and configure their logging system .addInclusion("org/apache/commons/logging/") .addInclusion("org/apache/log4j/") .addInclusion("ch/qos/logback/") // Exposed by org.sonar.api.server.authentication.IdentityProvider .addInclusion("javax/servlet/") // required for some internal SonarSource plugins (billing, orchestrator, ...) .addInclusion("org/sonar/server/platform/") // required for commercial plugins at SonarSource .addInclusion("com/sonarsource/plugins/license/api/") // API exclusions .addExclusion("org/sonar/api/internal/"); } }
5,680
36.873333
138
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/PluginInfo.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.collect.ComparisonChain; import com.google.common.collect.Ordering; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.HashSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.jar.JarFile; import java.util.regex.Pattern; import java.util.zip.ZipEntry; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.utils.MessageException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.updatecenter.common.PluginManifest; import org.sonar.updatecenter.common.Version; import static java.util.Objects.requireNonNull; public class PluginInfo implements Comparable<PluginInfo> { private static final Logger LOGGER = LoggerFactory.getLogger(PluginInfo.class); private static final Joiner SLASH_JOINER = Joiner.on(" / ").skipNulls(); private final String key; private String name; @CheckForNull private File jarFile; @CheckForNull private String mainClass; @CheckForNull private Version version; private String displayVersion; @CheckForNull private Version minimalSonarPluginApiVersion; @CheckForNull private String description; @CheckForNull private String organizationName; @CheckForNull private String organizationUrl; @CheckForNull private String license; @CheckForNull private String homepageUrl; @CheckForNull private String issueTrackerUrl; private boolean useChildFirstClassLoader; @CheckForNull private String basePlugin; @CheckForNull private String implementationBuild; @CheckForNull private boolean sonarLintSupported; @CheckForNull private String documentationPath; private final Set<RequiredPlugin> requiredPlugins = new HashSet<>(); public PluginInfo(String key) { requireNonNull(key, "Plugin key is missing from manifest"); this.key = key; this.name = key; } public PluginInfo setJarFile(@Nullable File f) { this.jarFile = f; return this; } @CheckForNull public File getJarFile() { return jarFile; } public File getNonNullJarFile() { requireNonNull(jarFile); return jarFile; } public String getKey() { return key; } public String getName() { return name; } @CheckForNull public Version getVersion() { return version; } @CheckForNull public String getDisplayVersion() { return displayVersion; } public PluginInfo setDisplayVersion(@Nullable String displayVersion) { this.displayVersion = displayVersion; return this; } @CheckForNull public Version getMinimalSonarPluginApiVersion() { return minimalSonarPluginApiVersion; } @CheckForNull public String getMainClass() { return mainClass; } @CheckForNull public String getDescription() { return description; } @CheckForNull public String getOrganizationName() { return organizationName; } @CheckForNull public String getOrganizationUrl() { return organizationUrl; } @CheckForNull public String getLicense() { return license; } @CheckForNull public String getHomepageUrl() { return homepageUrl; } @CheckForNull public String getIssueTrackerUrl() { return issueTrackerUrl; } public boolean isUseChildFirstClassLoader() { return useChildFirstClassLoader; } public boolean isSonarLintSupported() { return sonarLintSupported; } public String getDocumentationPath() { return documentationPath; } @CheckForNull public String getBasePlugin() { return basePlugin; } @CheckForNull public String getImplementationBuild() { return implementationBuild; } public Set<RequiredPlugin> getRequiredPlugins() { return requiredPlugins; } public PluginInfo setName(@Nullable String name) { this.name = (name != null ? name : this.key); return this; } public PluginInfo setVersion(Version version) { this.version = version; return this; } public PluginInfo setMinimalSonarPluginApiVersion(@Nullable Version v) { this.minimalSonarPluginApiVersion = v; return this; } public PluginInfo setDocumentationPath(@Nullable String documentationPath) { this.documentationPath = documentationPath; return this; } /** * Required */ public PluginInfo setMainClass(String mainClass) { this.mainClass = mainClass; return this; } public PluginInfo setDescription(@Nullable String description) { this.description = description; return this; } public PluginInfo setOrganizationName(@Nullable String s) { this.organizationName = s; return this; } public PluginInfo setOrganizationUrl(@Nullable String s) { this.organizationUrl = s; return this; } public PluginInfo setLicense(@Nullable String license) { this.license = license; return this; } public PluginInfo setHomepageUrl(@Nullable String s) { this.homepageUrl = s; return this; } public PluginInfo setIssueTrackerUrl(@Nullable String s) { this.issueTrackerUrl = s; return this; } public PluginInfo setUseChildFirstClassLoader(boolean b) { this.useChildFirstClassLoader = b; return this; } public PluginInfo setSonarLintSupported(boolean sonarLintPlugin) { this.sonarLintSupported = sonarLintPlugin; return this; } public PluginInfo setBasePlugin(@Nullable String s) { if ("l10nen".equals(s)) { LOGGER.info("Plugin [{}] defines 'l10nen' as base plugin. " + "This metadata can be removed from manifest of l10n plugins since version 5.2.", key); basePlugin = null; } else { basePlugin = s; } return this; } public PluginInfo setImplementationBuild(@Nullable String implementationBuild) { this.implementationBuild = implementationBuild; return this; } public PluginInfo addRequiredPlugin(RequiredPlugin p) { this.requiredPlugins.add(p); return this; } /** * Find out if this plugin is compatible with a given version of Sonar Plugin API. * The version of plugin api embedded in SQ must be greater than or equal to the minimal version * needed by the plugin. */ public boolean isCompatibleWith(String runtimePluginApiVersion) { if (null == this.minimalSonarPluginApiVersion) { // no constraint defined on the plugin return true; } Version effectiveMin = Version.create(minimalSonarPluginApiVersion.getName()).removeQualifier(); Version effectiveVersion = Version.create(runtimePluginApiVersion).removeQualifier(); if (runtimePluginApiVersion.endsWith("-SNAPSHOT")) { // check only the major and minor versions (two first fields) effectiveMin = Version.create(effectiveMin.getMajor() + "." + effectiveMin.getMinor()); } return effectiveVersion.compareTo(effectiveMin) >= 0; } @Override public String toString() { return String.format("[%s]", SLASH_JOINER.join(key, version, implementationBuild)); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PluginInfo info = (PluginInfo) o; return Objects.equals(key, info.key) && Objects.equals(version, info.version); } @Override public int hashCode() { return Objects.hash(key, version); } @Override public int compareTo(PluginInfo that) { return ComparisonChain.start() .compare(this.name, that.name) .compare(this.version, that.version, Ordering.natural().nullsFirst()) .result(); } public static PluginInfo create(File jarFile) { try { PluginManifest manifest = new PluginManifest(jarFile); return create(jarFile, manifest); } catch (IOException e) { throw new IllegalStateException("Fail to extract plugin metadata from file: " + jarFile, e); } } @VisibleForTesting static PluginInfo create(File jarFile, PluginManifest manifest) { validateManifest(jarFile, manifest); PluginInfo info = new PluginInfo(manifest.getKey()); info.fillFields(jarFile, manifest); return info; } private static void validateManifest(File jarFile, PluginManifest manifest) { if (StringUtils.isBlank(manifest.getKey())) { throw MessageException.of(String.format("File is not a plugin. Please delete it and restart: %s", jarFile.getAbsolutePath())); } } protected void fillFields(File jarFile, PluginManifest manifest) { setJarFile(jarFile); setName(manifest.getName()); setMainClass(manifest.getMainClass()); setVersion(Version.create(manifest.getVersion())); setDocumentationPath(getDocumentationPath(jarFile)); // optional fields setDescription(manifest.getDescription()); setLicense(manifest.getLicense()); setOrganizationName(manifest.getOrganization()); setOrganizationUrl(manifest.getOrganizationUrl()); setDisplayVersion(manifest.getDisplayVersion()); String minSonarPluginApiVersion = manifest.getSonarVersion(); if (minSonarPluginApiVersion != null) { setMinimalSonarPluginApiVersion(Version.create(minSonarPluginApiVersion)); } setHomepageUrl(manifest.getHomepage()); setIssueTrackerUrl(manifest.getIssueTrackerUrl()); setUseChildFirstClassLoader(manifest.isUseChildFirstClassLoader()); setSonarLintSupported(manifest.isSonarLintSupported()); setBasePlugin(manifest.getBasePlugin()); setImplementationBuild(manifest.getImplementationBuild()); String[] requiredPluginsFromManifest = manifest.getRequirePlugins(); if (requiredPluginsFromManifest != null) { Arrays.stream(requiredPluginsFromManifest) .map(RequiredPlugin::parse) .filter(t -> !"license".equals(t.key)) .forEach(this::addRequiredPlugin); } } private static String getDocumentationPath(File file) { try (JarFile jarFile = new JarFile(file)) { return Optional.ofNullable(jarFile.getEntry("static/documentation.md")) .map(ZipEntry::getName) .orElse(null); } catch (IOException e) { LOGGER.warn("Could not retrieve documentation path from " + file, e); } return null; } public static class RequiredPlugin { private static final Pattern PARSER = Pattern.compile("\\w+:.+"); private final String key; private final Version minimalVersion; public RequiredPlugin(String key, Version minimalVersion) { this.key = key; this.minimalVersion = minimalVersion; } public String getKey() { return key; } public Version getMinimalVersion() { return minimalVersion; } public static RequiredPlugin parse(String s) { if (!PARSER.matcher(s).matches()) { throw new IllegalArgumentException("Manifest field does not have correct format: " + s); } String[] fields = StringUtils.split(s, ':'); return new RequiredPlugin(fields[0], Version.create(fields[1]).removeQualifier()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RequiredPlugin that = (RequiredPlugin) o; return key.equals(that.key); } @Override public int hashCode() { return key.hashCode(); } @Override public String toString() { return key + ':' + minimalVersion.getName(); } } }
12,492
25.412262
132
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/PluginJarExploder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.io.File; import java.util.Collection; import java.util.Collections; import java.util.function.Predicate; import java.util.zip.ZipEntry; import static org.apache.commons.io.FileUtils.listFiles; public abstract class PluginJarExploder { protected static final String LIB_RELATIVE_PATH_IN_JAR = "META-INF/lib"; public abstract ExplodedPlugin explode(PluginInfo plugin); protected Predicate<ZipEntry> newLibFilter() { return ze -> ze.getName().startsWith(LIB_RELATIVE_PATH_IN_JAR); } protected ExplodedPlugin explodeFromUnzippedDir(PluginInfo pluginInfo, File jarFile, File unzippedDir) { File libDir = new File(unzippedDir, PluginJarExploder.LIB_RELATIVE_PATH_IN_JAR); Collection<File> libs; if (libDir.isDirectory() && libDir.exists()) { libs = listFiles(libDir, null, false); } else { libs = Collections.emptyList(); } return new ExplodedPlugin(pluginInfo, pluginInfo.getKey(), jarFile, libs); } }
1,844
35.176471
106
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/PluginRepository.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.util.Collection; import org.sonar.api.Plugin; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.scanner.ScannerSide; import org.sonar.api.server.ServerSide; /** * Provides information about the plugins installed in the dependency injection container */ @ScannerSide @ServerSide @ComputeEngineSide public interface PluginRepository { Collection<PluginInfo> getPluginInfos(); /** * @throws IllegalArgumentException if the plugin does not exist */ PluginInfo getPluginInfo(String key); /** * @return the instance of {@link Plugin} for the given plugin key. Never return null. */ Plugin getPluginInstance(String key); Collection<Plugin> getPluginInstances(); boolean hasPlugin(String key); }
1,625
30.269231
89
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/PriorityBeanFactory.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.springframework.beans.BeanWrapper; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.RootBeanDefinition; public class PriorityBeanFactory extends DefaultListableBeanFactory { /** * Determines highest priority of the bean candidates. * Does not take into account the @Primary annotations. * This gets called from {@link DefaultListableBeanFactory#determineAutowireCandidate} when the bean factory is finding the beans to autowire. That method * checks for @Primary before calling this method. * * The strategy is to look at the @Priority annotations. If there are ties, we give priority to components that were added to child containers over their parents. * If there are still ties, null is returned, which will ultimately cause Spring to throw a NoUniqueBeanDefinitionException. */ @Override @Nullable protected String determineHighestPriorityCandidate(Map<String, Object> candidates, Class<?> requiredType) { List<Bean> candidateBeans = candidates.entrySet().stream() .filter(e -> e.getValue() != null) .map(e -> new Bean(e.getKey(), e.getValue())) .collect(Collectors.toList()); List<Bean> beansAfterPriority = highestPriority(candidateBeans, b -> getPriority(b.getInstance())); if (beansAfterPriority.isEmpty()) { return null; } else if (beansAfterPriority.size() == 1) { return beansAfterPriority.get(0).getName(); } List<Bean> beansAfterHierarchy = highestPriority(beansAfterPriority, b -> getHierarchyPriority(b.getName())); if (beansAfterHierarchy.size() == 1) { return beansAfterHierarchy.get(0).getName(); } return null; } private static List<Bean> highestPriority(List<Bean> candidates, PriorityFunction function) { List<Bean> highestPriorityBeans = new ArrayList<>(); Integer highestPriority = null; for (Bean candidate : candidates) { Integer candidatePriority = function.classify(candidate); if (candidatePriority == null) { candidatePriority = Integer.MAX_VALUE; } if (highestPriority == null) { highestPriority = candidatePriority; highestPriorityBeans.add(candidate); } else if (candidatePriority < highestPriority) { highestPriorityBeans.clear(); highestPriority = candidatePriority; highestPriorityBeans.add(candidate); } else if (candidatePriority.equals(highestPriority)) { highestPriorityBeans.add(candidate); } } return highestPriorityBeans; } @CheckForNull private Integer getHierarchyPriority(String beanName) { DefaultListableBeanFactory factory = this; int i = 1; while (factory != null) { if (factory.containsBeanDefinition(beanName)) { return i; } factory = (DefaultListableBeanFactory) factory.getParentBeanFactory(); i++; } return null; } /** * A common mistake when migrating from Pico Container to Spring is to forget to add @Inject or @Autowire annotations to classes that have multiple constructors. * Spring will fail if there is no default no-arg constructor, but it will silently use the no-arg constructor if there is one, never calling the other constructors. * We override this method to fail fast if a class has multiple constructors. */ @Override protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) { if (mbd.hasBeanClass() && mbd.getBeanClass().getConstructors().length > 1) { throw new IllegalStateException("Constructor annotations missing in: " + mbd.getBeanClass()); } return super.instantiateBean(beanName, mbd); } private static class Bean { private final String name; private final Object instance; public Bean(String name, Object instance) { this.name = name; this.instance = instance; } public String getName() { return name; } public Object getInstance() { return instance; } } @FunctionalInterface private interface PriorityFunction { @CheckForNull Integer classify(Bean candidate); } }
5,225
36.597122
167
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/RemotePluginFile.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; public class RemotePluginFile { private String filename; private String hash; public RemotePluginFile(String filename, String hash) { this.filename = filename; this.hash = hash; } public String getFilename() { return filename; } public String getHash() { return hash; } }
1,185
28.65
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/ServerId.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import com.google.common.collect.ImmutableSet; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Objects; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.CoreProperties; import static com.google.common.base.Preconditions.checkArgument; import static org.sonar.core.platform.ServerId.Format.DEPRECATED; import static org.sonar.core.platform.ServerId.Format.NO_DATABASE_ID; import static org.sonar.core.platform.ServerId.Format.WITH_DATABASE_ID; @Immutable public final class ServerId { public static final char SPLIT_CHARACTER = '-'; public static final int DATABASE_ID_LENGTH = 8; public static final int DEPRECATED_SERVER_ID_LENGTH = 14; public static final int NOT_UUID_DATASET_ID_LENGTH = 15; public static final int UUID_DATASET_ID_LENGTH = 20; private static final Set<Integer> ALLOWED_LENGTHS = ImmutableSet.of( DEPRECATED_SERVER_ID_LENGTH, NOT_UUID_DATASET_ID_LENGTH, NOT_UUID_DATASET_ID_LENGTH + 1 + DATABASE_ID_LENGTH, UUID_DATASET_ID_LENGTH, UUID_DATASET_ID_LENGTH + 1 + DATABASE_ID_LENGTH); public enum Format { /* server id format before 6.1 (see SONAR-6992) */ DEPRECATED, /* server id format before 6.7.5 and 7.3 (see LICENSE-96) */ NO_DATABASE_ID, WITH_DATABASE_ID } private final String databaseId; private final String datasetId; private final Format format; private ServerId(@Nullable String databaseId, String datasetId) { this.databaseId = databaseId; this.datasetId = datasetId; this.format = computeFormat(databaseId, datasetId); } public Optional<String> getDatabaseId() { return Optional.ofNullable(databaseId); } public String getDatasetId() { return datasetId; } public Format getFormat() { return format; } private static Format computeFormat(@Nullable String databaseId, String datasetId) { if (databaseId != null) { return WITH_DATABASE_ID; } if (isDate(datasetId)) { return DEPRECATED; } return NO_DATABASE_ID; } public static ServerId parse(String serverId) { String trimmed = serverId.trim(); int length = trimmed.length(); checkArgument(length > 0, "serverId can't be empty"); checkArgument(ALLOWED_LENGTHS.contains(length), "serverId does not have a supported length"); if (length == DEPRECATED_SERVER_ID_LENGTH || length == UUID_DATASET_ID_LENGTH || length == NOT_UUID_DATASET_ID_LENGTH) { return new ServerId(null, trimmed); } int splitCharIndex = trimmed.indexOf(SPLIT_CHARACTER); if (splitCharIndex == -1) { return new ServerId(null, trimmed); } checkArgument(splitCharIndex == DATABASE_ID_LENGTH, "Unrecognized serverId format. Parts have wrong length"); return of(trimmed.substring(0, splitCharIndex), trimmed.substring(splitCharIndex + 1)); } public static ServerId of(@Nullable String databaseId, String datasetId) { if (databaseId != null) { int databaseIdLength = databaseId.length(); checkArgument(databaseIdLength == DATABASE_ID_LENGTH, "Illegal databaseId length (%s)", databaseIdLength); } int datasetIdLength = datasetId.length(); checkArgument(datasetIdLength == DEPRECATED_SERVER_ID_LENGTH || datasetIdLength == NOT_UUID_DATASET_ID_LENGTH || datasetIdLength == UUID_DATASET_ID_LENGTH, "Illegal datasetId length (%s)", datasetIdLength); return new ServerId(databaseId, datasetId); } /** * Checks whether the specified value is a date according to the old format of the {@link CoreProperties#SERVER_ID}. */ private static boolean isDate(String value) { try { new SimpleDateFormat("yyyyMMddHHmmss").parse(value); return true; } catch (ParseException e) { return false; } } @Override public String toString() { if (databaseId == null) { return datasetId; } return databaseId + SPLIT_CHARACTER + datasetId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ServerId serverId = (ServerId) o; return Objects.equals(databaseId, serverId.databaseId) && Objects.equals(datasetId, serverId.datasetId); } @Override public int hashCode() { return Objects.hash(databaseId, datasetId); } }
5,320
32.049689
124
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/SonarQubeVersion.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import javax.annotation.concurrent.Immutable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.scanner.ScannerSide; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.Version; import static java.util.Objects.requireNonNull; @ScannerSide @ServerSide @ComputeEngineSide @Immutable public class SonarQubeVersion { private final Version version; public SonarQubeVersion(Version version) { requireNonNull(version); this.version = version; } public Version get() { return this.version; } public boolean isGreaterThanOrEqual(Version than) { return this.version.isGreaterThanOrEqual(than); } @Override public String toString() { return version.toString(); } }
1,607
27.714286
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/SpringComponentContainer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.function.Supplier; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.utils.System2; import org.springframework.beans.factory.NoSuchBeanDefinitionException; import org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import static java.util.Collections.emptyList; import static java.util.Optional.ofNullable; public class SpringComponentContainer implements StartableContainer { protected final AnnotationConfigApplicationContext context; @Nullable protected final SpringComponentContainer parent; protected final List<SpringComponentContainer> children = new ArrayList<>(); private final PropertyDefinitions propertyDefinitions; private final ComponentKeys componentKeys = new ComponentKeys(); public SpringComponentContainer() { this(null, new PropertyDefinitions(System2.INSTANCE), emptyList(), new LazyUnlessStartableStrategy()); } protected SpringComponentContainer(List<?> externalExtensions) { this(null, new PropertyDefinitions(System2.INSTANCE), externalExtensions, new LazyUnlessStartableStrategy()); } protected SpringComponentContainer(SpringComponentContainer parent) { this(parent, parent.propertyDefinitions, emptyList(), new LazyUnlessStartableStrategy()); } protected SpringComponentContainer(SpringComponentContainer parent, SpringInitStrategy initStrategy) { this(parent, parent.propertyDefinitions, emptyList(), initStrategy); } protected SpringComponentContainer(@Nullable SpringComponentContainer parent, PropertyDefinitions propertyDefs, List<?> externalExtensions, SpringInitStrategy initStrategy) { this.parent = parent; this.propertyDefinitions = propertyDefs; this.context = new AnnotationConfigApplicationContext(new PriorityBeanFactory()); this.context.setAllowBeanDefinitionOverriding(false); ((AbstractAutowireCapableBeanFactory) context.getBeanFactory()).setParameterNameDiscoverer(null); if (parent != null) { context.setParent(parent.context); parent.children.add(this); } add(initStrategy); add(this); add(new StartableBeanPostProcessor()); add(externalExtensions); add(propertyDefs); } /** * Beans need to have a unique name, otherwise they'll override each other. * The strategy is: * - For classes, use the classloader + fully qualified class name as the name of the bean * - For instances, use the Classloader + FQCN + toString() * - If the object is a collection, iterate through the elements and apply the same strategy for each of them */ @Override public Container add(Object... objects) { for (Object o : objects) { if (o instanceof Class) { Class<?> clazz = (Class<?>) o; if (Module.class.isAssignableFrom(clazz)) { throw new IllegalStateException("Modules should be added as instances"); } context.registerBean(componentKeys.ofClass(clazz), clazz); declareExtension("", o); } else if (o instanceof Module) { ((Module) o).configure(this); } else if (o instanceof Iterable) { add(Iterables.toArray((Iterable<?>) o, Object.class)); } else { registerInstance(o); declareExtension("", o); } } return this; } private <T> void registerInstance(T instance) { Supplier<T> supplier = () -> instance; Class<T> clazz = (Class<T>) instance.getClass(); context.registerBean(componentKeys.ofInstance(instance), clazz, supplier); } /** * Extensions are usually added by plugins and we assume they don't support any injection-related annotations. * Spring contexts supporting annotations will fail if multiple constructors are present without any annotations indicating which one to use for injection. * For that reason, we need to create the beans ourselves, using ClassDerivedBeanDefinition, which will declare that all constructors can be used for injection. */ private Container addExtension(Object o) { if (o instanceof Class) { Class<?> clazz = (Class<?>) o; ClassDerivedBeanDefinition bd = new ClassDerivedBeanDefinition(clazz); context.registerBeanDefinition(componentKeys.ofClass(clazz), bd); } else if (o instanceof Iterable) { ((Iterable<?>) o).forEach(this::addExtension); } else { registerInstance(o); } return this; } @Override public <T> T getComponentByType(Class<T> type) { try { return context.getBean(type); } catch (Exception t) { throw new IllegalStateException("Unable to load component " + type, t); } } @Override public <T> Optional<T> getOptionalComponentByType(Class<T> type) { try { return Optional.of(context.getBean(type)); } catch (NoSuchBeanDefinitionException t) { return Optional.empty(); } } @Override public <T> List<T> getComponentsByType(Class<T> type) { try { return new ArrayList<>(context.getBeansOfType(type).values()); } catch (Exception t) { throw new IllegalStateException("Unable to load components " + type, t); } } public AnnotationConfigApplicationContext context() { return context; } public void execute() { RuntimeException r = null; try { startComponents(); } catch (RuntimeException e) { r = e; } finally { try { stopComponents(); } catch (RuntimeException e) { if (r == null) { r = e; } } } if (r != null) { throw r; } } @Override public SpringComponentContainer startComponents() { doBeforeStart(); context.refresh(); doAfterStart(); return this; } public SpringComponentContainer stopComponents() { try { stopChildren(); if (context.isActive()) { context.close(); } } finally { if (parent != null) { parent.children.remove(this); } } return this; } private void stopChildren() { // loop over a copy of list of children in reverse order Lists.reverse(new ArrayList<>(this.children)).forEach(SpringComponentContainer::stopComponents); } public SpringComponentContainer createChild() { return new SpringComponentContainer(this); } @Override @CheckForNull public SpringComponentContainer getParent() { return parent; } @Override public SpringComponentContainer addExtension(@Nullable PluginInfo pluginInfo, Object extension) { addExtension(extension); declareExtension(pluginInfo, extension); return this; } @Override public SpringComponentContainer addExtension(@Nullable String defaultCategory, Object extension) { addExtension(extension); declareExtension(defaultCategory, extension); return this; } @Override public SpringComponentContainer declareExtension(@Nullable PluginInfo pluginInfo, Object extension) { declareExtension(pluginInfo != null ? pluginInfo.getName() : "", extension); return this; } @Override public SpringComponentContainer declareExtension(@Nullable String defaultCategory, Object extension) { this.propertyDefinitions.addComponent(extension, ofNullable(defaultCategory).orElse("")); return this; } /** * This method aims to be overridden */ protected void doBeforeStart() { // nothing } /** * This method aims to be overridden */ protected void doAfterStart() { // nothing } }
8,622
32.038314
176
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/SpringInitStrategy.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import javax.annotation.Nullable; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanFactoryPostProcessor; import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; public abstract class SpringInitStrategy implements BeanFactoryPostProcessor { @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (String beanName : beanFactory.getBeanDefinitionNames()) { BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName); Class<?> rawClass = beanDefinition.getResolvableType().getRawClass(); beanDefinition.setLazyInit(isLazyInit(beanDefinition, rawClass)); } } protected abstract boolean isLazyInit(BeanDefinition beanDefinition, @Nullable Class<?> clazz); }
1,782
43.575
105
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/StartableBeanPostProcessor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; import org.sonar.api.Startable; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor; import org.springframework.lang.Nullable; public class StartableBeanPostProcessor implements DestructionAwareBeanPostProcessor { @Override @Nullable public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof Startable) { ((Startable) bean).start(); } return bean; } @Override public boolean requiresDestruction(Object bean) { return bean instanceof Startable; } @Override public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException { try { // note: Spring will call close() on AutoCloseable beans. if (bean instanceof Startable) { ((Startable) bean).stop(); } } catch (Exception e) { LoggerFactory.getLogger(StartableBeanPostProcessor.class) .warn("Dispose of component {} failed", bean.getClass().getCanonicalName(), e); } } }
1,992
34.589286
101
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/platform/StartableContainer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.platform; public interface StartableContainer extends ExtensionContainer { StartableContainer startComponents(); }
984
38.4
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/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. */ /** * Provides support of DI (Dependency Injection) container and management of plugins. */ @ParametersAreNonnullByDefault package org.sonar.core.platform; import javax.annotation.ParametersAreNonnullByDefault;
1,058
36.821429
85
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/plugin/PluginType.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.plugin; public enum PluginType { EXTERNAL, BUNDLED }
922
35.92
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/plugin/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. */ /** * Provides support of DI (Dependency Injection) container and management of plugins. */ @ParametersAreNonnullByDefault package org.sonar.core.plugin; import javax.annotation.ParametersAreNonnullByDefault;
1,056
36.75
85
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/ArtifactLocation.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class ArtifactLocation { @SerializedName("uri") private final String uri; @SerializedName("uriBaseId") private final String uriBaseId; public ArtifactLocation(@Nullable String uriBaseId, String uri) { this.uriBaseId = uriBaseId; this.uri = uri; } public String getUri() { return uri; } @CheckForNull public String getUriBaseId() { return uriBaseId; } }
1,400
28.808511
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/CodeFlow.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import java.util.List; public class CodeFlow { @SerializedName("threadFlows") private final List<ThreadFlow> threadFlows; private CodeFlow(List<ThreadFlow> threadFlows) { this.threadFlows = threadFlows; } public static CodeFlow of(List<ThreadFlow> threadFlows) { return new CodeFlow(threadFlows); } public List<ThreadFlow> getThreadFlows() { return threadFlows; } }
1,323
31.292683
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/DefaultConfiguration.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; public class DefaultConfiguration { @SerializedName("level") private String level; DefaultConfiguration() {} public String getLevel() { return level; } }
1,096
31.264706
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Driver.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class Driver { @SerializedName("name") private final String name; @SerializedName("organization") private final String organization; @SerializedName("semanticVersion") private final String semanticVersion; @SerializedName("rules") private final Set<Rule> rules; private Driver(String name, @Nullable String organization, @Nullable String semanticVersion, Set<Rule> rules) { this.name = name; this.organization = organization; this.semanticVersion = semanticVersion; this.rules = Set.copyOf(rules); } public String getName() { return name; } @CheckForNull public String getOrganization() { return organization; } @CheckForNull public String getSemanticVersion() { return semanticVersion; } public Set<Rule> getRules() { return rules; } public static DriverBuilder builder() { return new DriverBuilder(); } public static final class DriverBuilder { private String name; private String organization; private String semanticVersion; private Set<Rule> rules; private DriverBuilder() { } public DriverBuilder name(String name) { this.name = name; return this; } public DriverBuilder organization(String organization) { this.organization = organization; return this; } public DriverBuilder semanticVersion(String semanticVersion) { this.semanticVersion = semanticVersion; return this; } public DriverBuilder rules(Set<Rule> rules) { this.rules = rules; return this; } public Driver build() { return new Driver(name, organization, semanticVersion, rules); } } }
2,697
25.712871
113
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Extension.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import java.util.Set; public class Extension { @SerializedName("rules") private Set<Rule> rules; @SerializedName("name") private String name; public Extension() { // even if empty constructor is not required for Gson, it is strongly recommended: // http://stackoverflow.com/a/18645370/229031 } public Set<Rule> getRules() { return rules; } public String getName() { return name; } }
1,348
29.659091
86
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Location.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; public class Location { @SerializedName("physicalLocation") private final PhysicalLocation physicalLocation; private Location(PhysicalLocation physicalLocation) { this.physicalLocation = physicalLocation; } public static Location of(PhysicalLocation physicalLocation) { return new Location(physicalLocation); } public PhysicalLocation getPhysicalLocation() { return physicalLocation; } }
1,346
31.853659
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/LocationWrapper.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; public class LocationWrapper { @SerializedName("location") private final Location location; private LocationWrapper(Location location) { this.location = location; } public static LocationWrapper of(Location location) { return new LocationWrapper(location); } public Location getLocation() { return location; } }
1,270
30.775
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/PartialFingerprints.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; public class PartialFingerprints { @SerializedName("primaryLocationLineHash") private final String primaryLocationLineHash; public PartialFingerprints(String primaryLocationLineHash) { this.primaryLocationLineHash = primaryLocationLineHash; } public String getPrimaryLocationLineHash() { return primaryLocationLineHash; } }
1,272
34.361111
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/PhysicalLocation.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; public class PhysicalLocation { @SerializedName("artifactLocation") private final ArtifactLocation artifactLocation; @SerializedName("region") private final Region region; private PhysicalLocation(ArtifactLocation artifactLocation, Region region) { this.artifactLocation = artifactLocation; this.region = region; } public static PhysicalLocation of(ArtifactLocation artifactLocation, Region region) { return new PhysicalLocation(artifactLocation, region); } public ArtifactLocation getArtifactLocation() { return artifactLocation; } public Region getRegion() { return region; } }
1,554
32.085106
87
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/PropertiesBag.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import java.util.Set; public class PropertiesBag { @SerializedName("tags") private final Set<String> tags; @SerializedName("security-severity") private final String securitySeverity; private PropertiesBag(String securitySeverity, Set<String> tags) { this.tags = Set.copyOf(tags); this.securitySeverity = securitySeverity; } public static PropertiesBag of(String securitySeverity, Set<String> tags) { return new PropertiesBag(securitySeverity, tags); } public Set<String> getTags() { return tags; } public String getSecuritySeverity() { return securitySeverity; } }
1,542
30.489796
77
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Region.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class Region { @SerializedName("startLine") private final Integer startLine; @SerializedName("endLine") private final Integer endLine; @SerializedName("startColumn") private final Integer startColumn; @SerializedName("endColumn") private final Integer endColumn; private Region(Integer startLine, @Nullable Integer endLine, @Nullable Integer startColumn, @Nullable Integer endColumn) { this.startLine = startLine; this.endLine = endLine; this.startColumn = startColumn; this.endColumn = endColumn; } public static RegionBuilder builder() { return new RegionBuilder(); } public Integer getStartLine() { return startLine; } @CheckForNull public Integer getEndLine() { return endLine; } @CheckForNull public Integer getStartColumn() { return startColumn; } @CheckForNull public Integer getEndColumn() { return endColumn; } public static final class RegionBuilder { private Integer startLine; private Integer endLine; private Integer startColumn; private Integer endColumn; public RegionBuilder startLine(int startLine) { this.startLine = startLine; return this; } public RegionBuilder endLine(int endLine) { this.endLine = endLine; return this; } public RegionBuilder startColumn(int startColumn) { this.startColumn = startColumn; return this; } public RegionBuilder endColumn(int endColumn) { this.endColumn = endColumn; return this; } public Region build() { return new Region(startLine, endLine, startColumn, endColumn); } } }
2,640
26.226804
124
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Result.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class Result { @SerializedName("ruleId") private final String ruleId; @SerializedName("message") private final WrappedText message; @SerializedName("locations") private final LinkedHashSet<Location> locations; @SerializedName("partialFingerprints") private final PartialFingerprints partialFingerprints; @SerializedName("codeFlows") private final List<CodeFlow> codeFlows; @SerializedName("level") private final String level; private Result(String ruleId, String message, @Nullable LinkedHashSet<Location> locations, @Nullable String primaryLocationLineHash, @Nullable List<CodeFlow> codeFlows, @Nullable String level) { this.ruleId = ruleId; this.message = WrappedText.of(message); this.locations = locations; this.partialFingerprints = primaryLocationLineHash == null ? null : new PartialFingerprints(primaryLocationLineHash); this.codeFlows = codeFlows == null ? null : List.copyOf(codeFlows); this.level = level; } public String getRuleId() { return ruleId; } public WrappedText getMessage() { return message; } @CheckForNull public Set<Location> getLocations() { return locations; } @CheckForNull public PartialFingerprints getPartialFingerprints() { return partialFingerprints; } @CheckForNull public List<CodeFlow> getCodeFlows() { return codeFlows; } public String getLevel() { return level; } public static ResultBuilder builder() { return new ResultBuilder(); } public static final class ResultBuilder { private String ruleId; private String message; private LinkedHashSet<Location> locations; private String hash; private List<CodeFlow> codeFlows; private String level; private ResultBuilder() { } public ResultBuilder ruleId(String ruleId) { this.ruleId = ruleId; return this; } public ResultBuilder message(String message) { this.message = message; return this; } public ResultBuilder level(String level) { this.level = level; return this; } public ResultBuilder locations(Set<Location> locations) { this.locations = new LinkedHashSet<>(locations); return this; } public ResultBuilder hash(String hash) { this.hash = hash; return this; } public ResultBuilder codeFlows(List<CodeFlow> codeFlows) { this.codeFlows = codeFlows; return this; } public Result build() { return new Result(ruleId, message, locations, hash, codeFlows, level); } } }
3,641
27.015385
121
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Rule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import java.util.Objects; public class Rule { @SerializedName("id") private final String id; @SerializedName("name") private final String name; @SerializedName("shortDescription") private final WrappedText shortDescription; @SerializedName("fullDescription") private final WrappedText fullDescription; @SerializedName("help") private final WrappedText help; @SerializedName("properties") private final PropertiesBag properties; @SerializedName("defaultConfiguration") private DefaultConfiguration defaultConfiguration; private Rule(String id, String name, WrappedText shortDescription, WrappedText fullDescription, WrappedText help, PropertiesBag properties) { this.id = id; this.name = name; this.shortDescription = shortDescription; this.fullDescription = fullDescription; this.help = help; this.properties = properties; } public String getId() { return id; } public String getName() { return name; } public WrappedText getShortDescription() { return shortDescription; } public WrappedText getFullDescription() { return fullDescription; } public WrappedText getHelp() { return help; } public PropertiesBag getProperties() { return properties; } public DefaultConfiguration getDefaultConfiguration() { return defaultConfiguration; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Rule rule = (Rule) o; return Objects.equals(id, rule.id); } @Override public int hashCode() { return Objects.hash(id); } public static RuleBuilder builder() { return new RuleBuilder(); } public static final class RuleBuilder { private String id; private String name; private WrappedText shortDescription; private WrappedText fullDescription; private WrappedText help; private PropertiesBag properties; private RuleBuilder() { } public RuleBuilder id(String id) { this.id = id; return this; } public RuleBuilder name(String name) { this.name = name; return this; } public RuleBuilder shortDescription(String shortDescription) { this.shortDescription = WrappedText.of(shortDescription); return this; } public RuleBuilder fullDescription(String fullDescription) { this.fullDescription = WrappedText.of(fullDescription); return this; } public RuleBuilder help(String help) { this.help = WrappedText.of(help); return this; } public RuleBuilder properties(PropertiesBag properties) { this.properties = properties; return this; } public Rule build() { return new Rule(id, name, shortDescription, fullDescription, help, properties); } } }
3,792
25.158621
143
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Run.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class Run { @SerializedName("tool") private final Tool tool; @SerializedName("results") private final Set<Result> results; @SerializedName("language") private final String language; @SerializedName("columnKind") private final String columnKind; private Run(Tool tool, Set<Result> results, @Nullable String language, @Nullable String columnKind) { this.tool = tool; this.results = Set.copyOf(results); this.language = language; this.columnKind = columnKind; } @CheckForNull public String getLanguage() { return language; } @CheckForNull public String getColumnKind() { return columnKind; } public Tool getTool() { return tool; } public Set<Result> getResults() { return results; } public static RunBuilder builder() { return new RunBuilder(); } public static final class RunBuilder { private Tool tool; private Set<Result> results; private String language; private String columnKind; private RunBuilder() { } public RunBuilder tool(Tool tool) { this.tool = tool; return this; } public RunBuilder results(Set<Result> results) { this.results = results; return this; } public RunBuilder language(String language) { this.language = language; return this; } public RunBuilder columnKind(String columnKind) { this.columnKind = columnKind; return this; } public Run build() { return new Run(tool, results, language, columnKind); } } }
2,571
24.215686
103
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/Sarif210.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.gson.annotations.SerializedName; import java.util.Set; public class Sarif210 { public static final String SARIF_VERSION = "2.1.0"; @SerializedName("version") private final String version; @SerializedName("$schema") private final String schema; @SerializedName("runs") private final Set<Run> runs; public Sarif210(String schema, Run run) { this.schema = schema; this.version = SARIF_VERSION; this.runs = Set.of(run); } public String getVersion() { return version; } public String getSchema() { return schema; } public Set<Run> getRuns() { return runs; } }
1,508
26.944444
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/SarifSerializer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import java.nio.file.NoSuchFileException; import java.nio.file.Path; public interface SarifSerializer { String serialize(Sarif210 sarif210); Sarif210 deserialize(Path sarifPath) throws NoSuchFileException; }
1,089
34.16129
75
java
sonarqube
sonarqube-master/sonar-core/src/main/java/org/sonar/core/sarif/SarifSerializerImpl.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with 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.sarif; import com.google.common.annotations.VisibleForTesting; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; import java.io.IOException; import java.io.Reader; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import javax.inject.Inject; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.scanner.ScannerSide; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.newBufferedReader; @ScannerSide @ComputeEngineSide public class SarifSerializerImpl implements SarifSerializer { private static final String SARIF_REPORT_ERROR = "Failed to read SARIF report at '%s'"; private static final String SARIF_JSON_SYNTAX_ERROR = SARIF_REPORT_ERROR + ": invalid JSON syntax or file is not UTF-8 encoded"; private final Gson gson; @Inject public SarifSerializerImpl() { this(new Gson()); } @VisibleForTesting SarifSerializerImpl(Gson gson) { this.gson = gson; } @Override public String serialize(Sarif210 sarif210) { return gson.toJson(sarif210); } @Override public Sarif210 deserialize(Path reportPath) throws NoSuchFileException { try (Reader reader = newBufferedReader(reportPath, UTF_8)) { Sarif210 sarif = gson.fromJson(reader, Sarif210.class); SarifVersionValidator.validateSarifVersion(sarif.getVersion()); return sarif; } catch (NoSuchFileException e) { throw e; } catch (JsonIOException | IOException e) { throw new IllegalStateException(format(SARIF_REPORT_ERROR, reportPath), e); } catch (JsonSyntaxException e) { throw new IllegalStateException(format(SARIF_JSON_SYNTAX_ERROR, reportPath), e); } } }
2,645
33.815789
130
java