repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIterator.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; import java.util.Iterator; public interface IssueIterator extends Iterator<IssueDoc>, AutoCloseable { @Override void close(); }
1,017
32.933333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIteratorFactory.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; import java.util.Collection; import javax.annotation.Nullable; import org.sonar.db.DbClient; public class IssueIteratorFactory { private final DbClient dbClient; public IssueIteratorFactory(DbClient dbClient) { this.dbClient = dbClient; } public IssueIterator createForAll() { return createForBranch(null); } public IssueIterator createForBranch(@Nullable String branchUuid) { return new IssueIteratorForSingleChunk(dbClient, branchUuid, null); } public IssueIterator createForIssueKeys(Collection<String> issueKeys) { return new IssueIteratorForMultipleChunks(dbClient, issueKeys); } }
1,509
31.826087
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIteratorForMultipleChunks.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; import java.util.Collection; import java.util.Iterator; import java.util.List; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbClient; import static java.util.Optional.ofNullable; public class IssueIteratorForMultipleChunks implements IssueIterator { private final DbClient dbClient; private final Iterator<List<String>> iteratorOverChunks; private IssueIteratorForSingleChunk currentChunk; public IssueIteratorForMultipleChunks(DbClient dbClient, Collection<String> issueKeys) { this.dbClient = dbClient; iteratorOverChunks = DatabaseUtils.toUniqueAndSortedPartitions(issueKeys).iterator(); } @Override public boolean hasNext() { if (currentChunk != null && currentChunk.hasNext()) { return true; } return iteratorOverChunks.hasNext(); } @Override public IssueDoc next() { if (currentChunk == null || !currentChunk.hasNext()) { currentChunk = nextChunk(); } return currentChunk.next(); } private IssueIteratorForSingleChunk nextChunk() { List<String> nextInput = iteratorOverChunks.next(); return new IssueIteratorForSingleChunk(dbClient, null, nextInput); } @Override public void close() { ofNullable(currentChunk).ifPresent(IssueIterator::close); } }
2,141
30.970149
90
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueIteratorForSingleChunk.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; import com.google.common.base.CharMatcher; import com.google.common.base.Splitter; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import java.util.HashMap; import java.util.stream.Collectors; import java.util.stream.IntStream; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.sonar.api.resources.Qualifiers; import org.sonar.api.resources.Scopes; import org.sonar.api.rules.RuleType; import org.sonar.db.DatabaseUtils; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ResultSetIterator; import org.sonar.server.security.SecurityStandards; import static com.google.common.base.Preconditions.checkArgument; import static org.elasticsearch.common.Strings.isNullOrEmpty; import static org.sonar.api.utils.DateUtils.longToDate; import static org.sonar.db.DatabaseUtils.getLong; import static org.sonar.db.rule.RuleDto.deserializeSecurityStandardsString; import static org.sonar.server.security.SecurityStandards.fromSecurityStandards; /** * Scrolls over table ISSUES and reads documents to populate * the issues index */ class IssueIteratorForSingleChunk implements IssueIterator { private static final String[] FIELDS = { // column 1 "i.kee", "i.assignee", "i.line", "i.resolution", "i.severity", "i.status", "i.effort", "i.author_login", "i.issue_close_date", "i.issue_creation_date", // column 11 "i.issue_update_date", "r.uuid", "r.language", "c.uuid", "c.path", "c.scope", "c.branch_uuid", "pb.is_main", "pb.project_uuid", // column 22 "i.tags", "i.issue_type", "r.security_standards", "c.qualifier", "n.uuid", "i.code_variants" }; private static final String SQL_ALL = "select " + StringUtils.join(FIELDS, ",") + " from issues i " + "inner join rules r on r.uuid = i.rule_uuid " + "inner join components c on c.uuid = i.component_uuid " + "inner join project_branches pb on c.branch_uuid = pb.uuid "; private static final String SQL_NEW_CODE_JOIN = "left join new_code_reference_issues n on n.issue_key = i.kee "; private static final String BRANCH_FILTER = " and c.branch_uuid = ? and i.project_uuid = ? "; private static final String ISSUE_KEY_FILTER_PREFIX = " and i.kee in ("; private static final String ISSUE_KEY_FILTER_SUFFIX = ") "; static final Splitter STRING_LIST_SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings(); private final DbSession session; @CheckForNull private final String branchUuid; @CheckForNull private final Collection<String> issueKeys; private final PreparedStatement stmt; private final ResultSetIterator<IssueDoc> iterator; IssueIteratorForSingleChunk(DbClient dbClient, @Nullable String branchUuid, @Nullable Collection<String> issueKeys) { checkArgument(issueKeys == null || issueKeys.size() <= DatabaseUtils.PARTITION_SIZE_FOR_ORACLE, "Cannot search for more than " + DatabaseUtils.PARTITION_SIZE_FOR_ORACLE + " issue keys at once. Please provide the keys in smaller chunks."); this.branchUuid = branchUuid; this.issueKeys = issueKeys; this.session = dbClient.openSession(false); try { String sql = createSql(); stmt = dbClient.getMyBatis().newScrollingSelectStatement(session, sql); iterator = createIterator(); } catch (Exception e) { session.close(); throw new IllegalStateException("Fail to prepare SQL request to select all issues", e); } } private IssueIteratorInternal createIterator() { try { setParameters(stmt); return new IssueIteratorInternal(stmt); } catch (SQLException e) { DatabaseUtils.closeQuietly(stmt); throw new IllegalStateException("Fail to prepare SQL request to select all issues", e); } } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public IssueDoc next() { return iterator.next(); } private String createSql() { String sql = SQL_ALL; sql += branchUuid == null ? "" : BRANCH_FILTER; if (issueKeys != null && !issueKeys.isEmpty()) { sql += ISSUE_KEY_FILTER_PREFIX; sql += IntStream.range(0, issueKeys.size()).mapToObj(i -> "?").collect(Collectors.joining(",")); sql += ISSUE_KEY_FILTER_SUFFIX; } sql += SQL_NEW_CODE_JOIN; return sql; } private void setParameters(PreparedStatement stmt) throws SQLException { int index = 1; if (branchUuid != null) { stmt.setString(index, branchUuid); index++; stmt.setString(index, branchUuid); index++; } if (issueKeys != null) { for (String key : issueKeys) { stmt.setString(index, key); index++; } } } @Override public void close() { try { iterator.close(); } finally { DatabaseUtils.closeQuietly(stmt); session.close(); } } private static final class IssueIteratorInternal extends ResultSetIterator<IssueDoc> { public IssueIteratorInternal(PreparedStatement stmt) throws SQLException { super(stmt); } @Override protected IssueDoc read(ResultSet rs) throws SQLException { IssueDoc doc = new IssueDoc(new HashMap<>(30)); String key = rs.getString(1); // all the fields must be present, even if value is null doc.setKey(key); doc.setAssigneeUuid(rs.getString(2)); doc.setLine(DatabaseUtils.getInt(rs, 3)); doc.setResolution(rs.getString(4)); doc.setSeverity(rs.getString(5)); doc.setStatus(rs.getString(6)); doc.setEffort(getLong(rs, 7)); doc.setAuthorLogin(rs.getString(8)); doc.setFuncCloseDate(longToDate(getLong(rs, 9))); doc.setFuncCreationDate(longToDate(getLong(rs, 10))); doc.setFuncUpdateDate(longToDate(getLong(rs, 11))); doc.setRuleUuid(rs.getString(12)); doc.setLanguage(rs.getString(13)); doc.setComponentUuid(rs.getString(14)); String scope = rs.getString(16); String filePath = extractFilePath(rs.getString(15), scope); doc.setFilePath(filePath); doc.setDirectoryPath(extractDirPath(doc.filePath(), scope)); String branchUuid = rs.getString(17); boolean isMainBranch = rs.getBoolean( 18); String projectUuid = rs.getString(19); doc.setBranchUuid(branchUuid); doc.setIsMainBranch(isMainBranch); doc.setProjectUuid(projectUuid); String tags = rs.getString(20); doc.setTags(STRING_LIST_SPLITTER.splitToList(tags == null ? "" : tags)); doc.setType(RuleType.valueOf(rs.getInt(21))); SecurityStandards securityStandards = fromSecurityStandards(deserializeSecurityStandardsString(rs.getString(22))); SecurityStandards.SQCategory sqCategory = securityStandards.getSqCategory(); doc.setOwaspTop10(securityStandards.getOwaspTop10()); doc.setOwaspTop10For2021(securityStandards.getOwaspTop10For2021()); doc.setPciDss32(securityStandards.getPciDss32()); doc.setPciDss40(securityStandards.getPciDss40()); doc.setOwaspAsvs40(securityStandards.getOwaspAsvs40()); doc.setCwe(securityStandards.getCwe()); doc.setSansTop25(securityStandards.getSansTop25()); doc.setSonarSourceSecurityCategory(sqCategory); doc.setVulnerabilityProbability(sqCategory.getVulnerability()); doc.setScope(Qualifiers.UNIT_TEST_FILE.equals(rs.getString(23)) ? IssueScope.TEST : IssueScope.MAIN); doc.setIsNewCodeReference(!isNullOrEmpty(rs.getString(24))); String codeVariants = rs.getString(25); doc.setCodeVariants(STRING_LIST_SPLITTER.splitToList(codeVariants == null ? "" : codeVariants)); return doc; } @CheckForNull private static String extractDirPath(@Nullable String filePath, String scope) { if (filePath != null) { if (Scopes.DIRECTORY.equals(scope)) { return filePath; } int lastSlashIndex = CharMatcher.anyOf("/").lastIndexIn(filePath); if (lastSlashIndex > 0) { return filePath.substring(0, lastSlashIndex); } return "/"; } return null; } @CheckForNull private static String extractFilePath(@Nullable String filePath, String scope) { // On modules, the path contains the relative path of the module starting from its parent, and in E/S we're only interested in the // path // of files and directories. // That's why the file path should be null on modules and projects. if (filePath != null && !Scopes.PROJECT.equals(scope)) { return filePath; } return null; } } }
9,595
33.642599
148
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/IssueScope.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; /** * @since 8.5 */ public enum IssueScope { MAIN, TEST }
944
32.75
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/PrStatistics.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; import java.util.Map; import org.sonar.api.rules.RuleType; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.VULNERABILITY; public class PrStatistics { private final String branchUuid; private final long bugs; private final long vulnerabilities; private final long codeSmells; public PrStatistics(String branchUuid, Map<String, Long> issueCountByType) { this.branchUuid = branchUuid; this.bugs = getNonNullValue(issueCountByType, BUG); this.vulnerabilities = getNonNullValue(issueCountByType, VULNERABILITY); this.codeSmells = getNonNullValue(issueCountByType, CODE_SMELL); } public String getBranchUuid() { return branchUuid; } public long getBugs() { return bugs; } public long getVulnerabilities() { return vulnerabilities; } public long getCodeSmells() { return codeSmells; } private static long getNonNullValue(Map<String, Long> issueCountByType, RuleType type) { Long value = issueCountByType.get(type.name()); return value == null ? 0L : value; } }
2,015
30.5
90
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/ProjectStatistics.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; public class ProjectStatistics { private final String projectUuid; private final long issueCount; private final long lastIssueDate; public ProjectStatistics(String projectUuid, long issueCount, long lastIssueDate) { this.projectUuid = projectUuid; this.issueCount = issueCount; this.lastIssueDate = lastIssueDate; } public String getProjectUuid() { return projectUuid; } public long getIssueCount() { return issueCount; } public long getLastIssueDate() { return lastIssueDate; } }
1,414
29.76087
85
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/SecurityStandardCategoryStatistics.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.index; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import javax.annotation.Nullable; public class SecurityStandardCategoryStatistics { private final String category; private final long vulnerabilities; private final OptionalInt vulnerabilityRating; private final long toReviewSecurityHotspots; private final long reviewedSecurityHotspots; private final Integer securityReviewRating; private final List<SecurityStandardCategoryStatistics> children; private long activeRules; private long totalRules; private boolean hasMoreRules; private final Optional<String> version; private Optional<String> level = Optional.empty(); public SecurityStandardCategoryStatistics(String category, long vulnerabilities, OptionalInt vulnerabiliyRating, long toReviewSecurityHotspots, long reviewedSecurityHotspots, Integer securityReviewRating, @Nullable List<SecurityStandardCategoryStatistics> children, @Nullable String version) { this.category = category; this.vulnerabilities = vulnerabilities; this.vulnerabilityRating = vulnerabiliyRating; this.toReviewSecurityHotspots = toReviewSecurityHotspots; this.reviewedSecurityHotspots = reviewedSecurityHotspots; this.securityReviewRating = securityReviewRating; this.children = children; this.version = Optional.ofNullable(version); this.hasMoreRules = false; } public String getCategory() { return category; } public long getVulnerabilities() { return vulnerabilities; } public OptionalInt getVulnerabilityRating() { return vulnerabilityRating; } public long getToReviewSecurityHotspots() { return toReviewSecurityHotspots; } public long getReviewedSecurityHotspots() { return reviewedSecurityHotspots; } public Integer getSecurityReviewRating() { return securityReviewRating; } public List<SecurityStandardCategoryStatistics> getChildren() { return children; } public long getActiveRules() { return activeRules; } public SecurityStandardCategoryStatistics setActiveRules(long activeRules) { this.activeRules = activeRules; return this; } public long getTotalRules() { return totalRules; } public Optional<String> getVersion() { return version; } public Optional<String> getLevel() { return level; } public SecurityStandardCategoryStatistics setLevel(String level) { this.level = Optional.of(level); return this; } public SecurityStandardCategoryStatistics setTotalRules(long totalRules) { this.totalRules = totalRules; return this; } public boolean hasMoreRules() { return hasMoreRules; } public void setHasMoreRules(boolean hasMoreRules) { this.hasMoreRules = hasMoreRules; } }
3,650
28.92623
153
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/index/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.issue.index; import javax.annotation.ParametersAreNonnullByDefault;
968
39.375
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/AbstractNewIssuesEmailTemplate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Arrays; import java.util.Date; import java.util.Iterator; import java.util.Locale; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.DateUtils; import org.sonar.core.i18n.I18n; import org.sonar.server.issue.notification.NewIssuesStatistics.Metric; import static com.google.common.base.Preconditions.checkNotNull; import static java.nio.charset.StandardCharsets.UTF_8; /** * Base class to create emails for new issues */ public abstract class AbstractNewIssuesEmailTemplate implements EmailTemplate { protected static final char NEW_LINE = '\n'; protected static final String TAB = " "; protected static final String DOT = "."; protected static final String COUNT = DOT + "count"; protected static final String LABEL = DOT + "label"; static final String FIELD_PROJECT_NAME = "projectName"; static final String FIELD_PROJECT_KEY = "projectKey"; static final String FIELD_PROJECT_DATE = "projectDate"; static final String FIELD_PROJECT_VERSION = "projectVersion"; static final String FIELD_ASSIGNEE = "assignee"; static final String FIELD_BRANCH = "branch"; static final String FIELD_PULL_REQUEST = "pullRequest"; protected final EmailSettings settings; protected final I18n i18n; public AbstractNewIssuesEmailTemplate(EmailSettings settings, I18n i18n) { this.settings = settings; this.i18n = i18n; } public static String encode(String toEncode) { try { return URLEncoder.encode(toEncode, UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException("Encoding not supported", e); } } @Override @CheckForNull public EmailMessage format(Notification notification) { if (shouldNotFormat(notification)) { return null; } String projectName = checkNotNull(notification.getFieldValue(FIELD_PROJECT_NAME)); String branchName = notification.getFieldValue(FIELD_BRANCH); String pullRequest = notification.getFieldValue(FIELD_PULL_REQUEST); StringBuilder message = new StringBuilder(); message.append("Project: ").append(projectName).append(NEW_LINE); if (branchName != null) { message.append("Branch: ").append(branchName).append(NEW_LINE); } if (pullRequest!= null) { message.append("Pull request: ").append(pullRequest).append(NEW_LINE); } String version = notification.getFieldValue(FIELD_PROJECT_VERSION); if (version != null) { message.append("Version: ").append(version).append(NEW_LINE); } message.append(NEW_LINE); appendRuleType(message, notification); appendAssignees(message, notification); appendRules(message, notification); appendTags(message, notification); appendComponents(message, notification); appendFooter(message, notification); return new EmailMessage() .setMessageId(notification.getType() + "/" + notification.getFieldValue(FIELD_PROJECT_KEY)) .setSubject(subject(notification, computeFullProjectName(projectName, branchName))) .setPlainTextMessage(message.toString()); } private static String computeFullProjectName(String projectName, @Nullable String branchName) { if (branchName == null || branchName.isEmpty()) { return projectName; } return String.format("%s (%s)", projectName, branchName); } protected abstract boolean shouldNotFormat(Notification notification); protected String subject(Notification notification, String fullProjectName) { int issueCount = Integer.parseInt(notification.getFieldValue(Metric.RULE_TYPE + COUNT)); return String.format("%s: %s new issue%s (new debt: %s)", fullProjectName, issueCount, issueCount > 1 ? "s" : "", notification.getFieldValue(Metric.EFFORT + COUNT)); } private static boolean doNotHaveValue(Notification notification, Metric metric) { return notification.getFieldValue(metric + DOT + "1" + LABEL) == null; } private static void genericAppendOfMetric(Metric metric, String label, StringBuilder message, Notification notification) { if (doNotHaveValue(notification, metric)) { return; } message .append(TAB) .append(label) .append(NEW_LINE); int i = 1; while (notification.getFieldValue(metric + DOT + i + LABEL) != null && i <= 5) { String name = notification.getFieldValue(metric + DOT + i + LABEL); message .append(TAB).append(TAB) .append(name) .append(": ") .append(notification.getFieldValue(metric + DOT + i + COUNT)) .append(NEW_LINE); i += 1; } message.append(NEW_LINE); } protected void appendAssignees(StringBuilder message, Notification notification) { genericAppendOfMetric(Metric.ASSIGNEE, "Assignees", message, notification); } protected void appendComponents(StringBuilder message, Notification notification) { genericAppendOfMetric(Metric.COMPONENT, "Most impacted files", message, notification); } protected void appendTags(StringBuilder message, Notification notification) { genericAppendOfMetric(Metric.TAG, "Tags", message, notification); } protected void appendRules(StringBuilder message, Notification notification) { genericAppendOfMetric(Metric.RULE, "Rules", message, notification); } protected void appendRuleType(StringBuilder message, Notification notification) { String count = notification.getFieldValue(Metric.RULE_TYPE + COUNT); message .append(String.format("%s new issue%s (new debt: %s)", count, Integer.valueOf(count) > 1 ? "s" : "", notification.getFieldValue(Metric.EFFORT + COUNT))) .append(NEW_LINE).append(NEW_LINE) .append(TAB) .append("Type") .append(NEW_LINE) .append(TAB) .append(TAB); for (Iterator<RuleType> ruleTypeIterator = Arrays.asList(RuleType.BUG, RuleType.VULNERABILITY, RuleType.CODE_SMELL).iterator(); ruleTypeIterator.hasNext();) { RuleType ruleType = ruleTypeIterator.next(); String ruleTypeLabel = i18n.message(getLocale(), "issue.type." + ruleType, ruleType.name()); message.append(ruleTypeLabel).append(": ").append(notification.getFieldValue(Metric.RULE_TYPE + DOT + ruleType + COUNT)); if (ruleTypeIterator.hasNext()) { message.append(TAB); } } message .append(NEW_LINE) .append(NEW_LINE); } protected void appendFooter(StringBuilder message, Notification notification) { String projectKey = notification.getFieldValue(FIELD_PROJECT_KEY); String dateString = notification.getFieldValue(FIELD_PROJECT_DATE); if (projectKey != null && dateString != null) { Date date = DateUtils.parseDateTime(dateString); String url = String.format("%s/project/issues?id=%s", settings.getServerBaseURL(), encode(projectKey)); String branchName = notification.getFieldValue(FIELD_BRANCH); if (branchName != null) { url += "&branch=" + encode(branchName); } String pullRequest = notification.getFieldValue(FIELD_PULL_REQUEST); if (pullRequest != null) { url += "&pullRequest=" + encode(pullRequest); } url += "&createdAt=" + encode(DateUtils.formatDateTime(date)); message .append("More details at: ") .append(url) .append(NEW_LINE); } } private static Locale getLocale() { return Locale.ENGLISH; } }
8,524
36.227074
162
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/ChangesOnMyIssueNotificationHandler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.ImmutableSet; import com.google.common.collect.SetMultimap; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User; import org.sonar.server.notification.EmailNotificationHandler; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.notification.NotificationManager; import org.sonar.server.notification.NotificationManager.EmailRecipient; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest; import static org.sonar.core.util.stream.MoreCollectors.unorderedFlattenIndex; import static org.sonar.core.util.stream.MoreCollectors.unorderedIndex; import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER; public class ChangesOnMyIssueNotificationHandler extends EmailNotificationHandler<IssuesChangesNotification> { private static final String KEY = "ChangesOnMyIssue"; private static final NotificationDispatcherMetadata METADATA = NotificationDispatcherMetadata.create(KEY) .setProperty(NotificationDispatcherMetadata.GLOBAL_NOTIFICATION, String.valueOf(true)) .setProperty(NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION, String.valueOf(true)); private final NotificationManager notificationManager; private final IssuesChangesNotificationSerializer serializer; public ChangesOnMyIssueNotificationHandler(NotificationManager notificationManager, EmailNotificationChannel emailNotificationChannel, IssuesChangesNotificationSerializer serializer) { super(emailNotificationChannel); this.notificationManager = notificationManager; this.serializer = serializer; } @Override public Optional<NotificationDispatcherMetadata> getMetadata() { return Optional.of(METADATA); } public static NotificationDispatcherMetadata newMetadata() { return METADATA; } @Override public Class<IssuesChangesNotification> getNotificationClass() { return IssuesChangesNotification.class; } @Override public Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<IssuesChangesNotification> notifications) { Set<NotificationWithProjectKeys> notificationsWithPeerChangedIssues = notifications.stream() .map(serializer::from) // ignore notification of which the changeAuthor is the assignee of all changed issues .filter(t -> t.getIssues().stream().anyMatch(issue -> issue.getAssignee().isPresent() && isPeerChanged(t.getChange(), issue))) .map(NotificationWithProjectKeys::new) .collect(Collectors.toSet()); if (notificationsWithPeerChangedIssues.isEmpty()) { return ImmutableSet.of(); } Set<String> projectKeys = notificationsWithPeerChangedIssues.stream() .flatMap(t -> t.getProjectKeys().stream()) .collect(Collectors.toSet()); // shortcut to save from building unnecessary data structures when all changed issues in notifications belong to // the same project if (projectKeys.size() == 1) { Set<User> assigneesOfPeerChangedIssues = notificationsWithPeerChangedIssues.stream() .flatMap(t -> t.getIssues().stream().filter(issue -> isPeerChanged(t.getChange(), issue))) .map(ChangedIssue::getAssignee) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toSet()); Set<EmailRecipient> subscribedAssignees = notificationManager.findSubscribedEmailRecipients( KEY, projectKeys.iterator().next(), assigneesOfPeerChangedIssues.stream().map(User::getLogin).collect(Collectors.toSet()), ALL_MUST_HAVE_ROLE_USER); return subscribedAssignees.stream() .flatMap(recipient -> notificationsWithPeerChangedIssues.stream() // do not notify users of the changes they made themselves .filter(notification -> !notification.getChange().isAuthorLogin(recipient.login())) .map(notification -> toEmailDeliveryRequest(notification, recipient, projectKeys))) .filter(Objects::nonNull) .collect(Collectors.toSet()); } SetMultimap<String, String> assigneeLoginsOfPeerChangedIssuesByProjectKey = notificationsWithPeerChangedIssues.stream() .flatMap(notification -> notification.getIssues().stream() .filter(issue -> issue.getAssignee().isPresent()) .filter(issue -> isPeerChanged(notification.getChange(), issue))) .collect(unorderedIndex(t -> t.getProject().getKey(), t -> t.getAssignee().get().getLogin())); SetMultimap<String, EmailRecipient> authorizedAssigneeLoginsByProjectKey = assigneeLoginsOfPeerChangedIssuesByProjectKey.asMap().entrySet() .stream() .collect(unorderedFlattenIndex( Map.Entry::getKey, entry -> { String projectKey = entry.getKey(); Set<String> assigneeLogins = (Set<String>) entry.getValue(); return notificationManager.findSubscribedEmailRecipients(KEY, projectKey, assigneeLogins, ALL_MUST_HAVE_ROLE_USER).stream(); })); SetMultimap<EmailRecipient, String> projectKeyByRecipient = authorizedAssigneeLoginsByProjectKey.entries().stream() .collect(unorderedIndex(Map.Entry::getValue, Map.Entry::getKey)); return projectKeyByRecipient.asMap().entrySet() .stream() .flatMap(entry -> { EmailRecipient recipient = entry.getKey(); Set<String> subscribedProjectKeys = (Set<String>) entry.getValue(); return notificationsWithPeerChangedIssues.stream() // do not notify users of the changes they made themselves .filter(notification -> !notification.getChange().isAuthorLogin(recipient.login())) .map(notification -> toEmailDeliveryRequest(notification, recipient, subscribedProjectKeys)) .filter(Objects::nonNull); }) .collect(Collectors.toSet()); } /** * Creates the {@link EmailDeliveryRequest} for the specified {@code recipient} with issues from the * specified {@code notification} it is the assignee of. * * @return {@code null} when the recipient is the assignee of no issue in {@code notification}. */ @CheckForNull private static EmailDeliveryRequest toEmailDeliveryRequest(NotificationWithProjectKeys notification, EmailRecipient recipient, Set<String> subscribedProjectKeys) { notification.getIssues(); Set<ChangedIssue> recipientIssuesByProject = notification.getIssues().stream() .filter(issue -> issue.getAssignee().filter(assignee -> recipient.login().equals(assignee.getLogin())).isPresent()) .filter(issue -> subscribedProjectKeys.contains(issue.getProject().getKey())) .collect(Collectors.toSet()); if (recipientIssuesByProject.isEmpty()) { return null; } return new EmailDeliveryRequest( recipient.email(), new ChangesOnMyIssuesNotification(notification.getChange(), recipientIssuesByProject)); } /** * Is the author of the change the assignee of the specified issue? * If not, it means the issue has been changed by a peer of the author of the change. */ private static boolean isPeerChanged(Change change, ChangedIssue issue) { Optional<User> assignee = issue.getAssignee(); return !assignee.isPresent() || !change.isAuthorLogin(assignee.get().getLogin()); } }
8,624
46.916667
165
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/ChangesOnMyIssuesEmailTemplate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.ListMultimap; import com.google.common.collect.SetMultimap; import java.util.List; import javax.annotation.CheckForNull; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; import org.sonar.core.i18n.I18n; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange; import static com.google.common.base.Preconditions.checkState; import static java.util.function.Function.identity; import static org.sonar.api.issue.Issue.STATUS_CLOSED; import static org.sonar.api.issue.Issue.STATUS_OPEN; import static org.sonar.core.util.stream.MoreCollectors.index; import static org.sonar.server.issue.notification.RuleGroup.ISSUES; import static org.sonar.server.issue.notification.RuleGroup.SECURITY_HOTSPOTS; import static org.sonar.server.issue.notification.RuleGroup.resolveGroup; /** * Creates email message for notification "Changes on my issues". */ public class ChangesOnMyIssuesEmailTemplate extends IssueChangesEmailTemplate { private static final String NOTIFICATION_NAME_I18N_KEY = "notification.dispatcher.ChangesOnMyIssue"; public ChangesOnMyIssuesEmailTemplate(I18n i18n, EmailSettings settings) { super(i18n, settings); } @Override @CheckForNull public EmailMessage format(Notification notif) { if (!(notif instanceof ChangesOnMyIssuesNotification)) { return null; } ChangesOnMyIssuesNotification notification = (ChangesOnMyIssuesNotification) notif; if (notification.getChange() instanceof AnalysisChange) { checkState(!notification.getChangedIssues().isEmpty(), "changedIssues can't be empty"); return formatAnalysisNotification(notification.getChangedIssues().keySet().iterator().next(), notification); } return formatMultiProject(notification); } private EmailMessage formatAnalysisNotification(Project project, ChangesOnMyIssuesNotification notification) { return new EmailMessage() .setMessageId("changes-on-my-issues/" + project.getKey()) .setSubject(buildAnalysisSubject(project)) .setHtmlMessage(buildAnalysisMessage(project, notification)); } private static String buildAnalysisSubject(Project project) { StringBuilder res = new StringBuilder("Analysis has changed some of your issues in "); toString(res, project); return res.toString(); } private String buildAnalysisMessage(Project project, ChangesOnMyIssuesNotification notification) { String projectParams = toUrlParams(project); StringBuilder sb = new StringBuilder(); paragraph(sb, s -> s.append("Hi,")); paragraph(sb, s -> s.append("An analysis has updated ").append(issuesOrAnIssue(notification.getChangedIssues())) .append(" assigned to you:")); ListMultimap<String, ChangedIssue> issuesByNewStatus = notification.getChangedIssues().values().stream() .collect(index(changedIssue -> STATUS_CLOSED.equals(changedIssue.getNewStatus()) ? STATUS_CLOSED : STATUS_OPEN, t -> t)); List<ChangedIssue> closedIssues = issuesByNewStatus.get(STATUS_CLOSED); if (!closedIssues.isEmpty()) { paragraph(sb, s -> s.append("Closed ").append(issueOrIssues(closedIssues)).append(":")); addIssuesByRule(sb, closedIssues, projectIssuePageHref(projectParams)); } List<ChangedIssue> openIssues = issuesByNewStatus.get(STATUS_OPEN); if (!openIssues.isEmpty()) { paragraph(sb, s -> s.append("Open ").append(issueOrIssues(openIssues)).append(":")); addIssuesByRule(sb, openIssues, projectIssuePageHref(projectParams)); } addFooter(sb, NOTIFICATION_NAME_I18N_KEY); return sb.toString(); } private EmailMessage formatMultiProject(ChangesOnMyIssuesNotification notification) { User user = ((UserChange) notification.getChange()).getUser(); return new EmailMessage() .setFrom(user.getName().orElse(user.getLogin())) .setMessageId("changes-on-my-issues") .setSubject("A manual update has changed some of your issues/hotspots") .setHtmlMessage(buildMultiProjectMessage(notification)); } private String buildMultiProjectMessage(ChangesOnMyIssuesNotification notification) { ListMultimap<RuleGroup, ChangedIssue> issuesAndHotspots = notification.getChangedIssues().values().stream() .collect(index(changedIssue -> resolveGroup(changedIssue.getRule().getRuleType()), identity())); List<ChangedIssue> issues = issuesAndHotspots.get(ISSUES); List<ChangedIssue> hotspots = issuesAndHotspots.get(SECURITY_HOTSPOTS); StringBuilder sb = new StringBuilder(); paragraph(sb, s -> s.append("Hi,")); paragraph(sb, s -> s.append("A manual change has updated ").append(RuleGroup.formatIssuesOrHotspots(issues, hotspots)).append(" assigned to you:")); addIssuesAndHotspotsByProjectThenRule(sb, notification.getChangedIssues()); addFooter(sb, NOTIFICATION_NAME_I18N_KEY); return sb.toString(); } private static String issuesOrAnIssue(SetMultimap<Project, ChangedIssue> changedIssues) { if (changedIssues.size() > 1) { return "issues"; } return "an issue"; } }
6,344
42.758621
152
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/ChangesOnMyIssuesNotification.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.SetMultimap; import java.util.Collection; import java.util.Objects; import org.sonar.api.notifications.Notification; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project; import static org.sonar.core.util.stream.MoreCollectors.unorderedIndex; /** * This notification is never serialized to DB. * <p> * It is derived from {@link IssuesChangesNotification} by * {@link FPOrWontFixNotificationHandler} and extends {@link Notification} only to comply with * {@link org.sonar.server.issue.notification.EmailTemplate#format(Notification)} API. */ class ChangesOnMyIssuesNotification extends Notification { private final Change change; private final SetMultimap<Project, ChangedIssue> changedIssues; public ChangesOnMyIssuesNotification(Change change, Collection<ChangedIssue> changedIssues) { super("ChangesOnMyIssues"); this.change = change; this.changedIssues = changedIssues.stream().collect(unorderedIndex(ChangedIssue::getProject, t -> t)); } public Change getChange() { return change; } public SetMultimap<Project, ChangedIssue> getChangedIssues() { return changedIssues; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ChangesOnMyIssuesNotification that = (ChangesOnMyIssuesNotification) o; return Objects.equals(change, that.change) && Objects.equals(changedIssues, that.changedIssues); } @Override public int hashCode() { return Objects.hash(change, changedIssues); } }
2,700
35.013333
106
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/DistributedMetricStatsInt.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class DistributedMetricStatsInt { private MetricStatsInt globalStats = new MetricStatsInt(); private Map<String, MetricStatsInt> statsPerLabel = new HashMap<>(); DistributedMetricStatsInt increment(String label, boolean onCurrentAnalysis) { this.globalStats.increment(onCurrentAnalysis); statsPerLabel.computeIfAbsent(label, l -> new MetricStatsInt()).increment(onCurrentAnalysis); return this; } Map<String, MetricStatsInt> getForLabels() { return Collections.unmodifiableMap(statsPerLabel); } public Optional<MetricStatsInt> getForLabel(String label) { return Optional.ofNullable(statsPerLabel.get(label)); } public int getOnCurrentAnalysis() { return globalStats.getOnCurrentAnalysis(); } public int getTotal() { return globalStats.getTotal(); } @Override public String toString() { return "DistributedMetricStatsInt{" + "globalStats=" + globalStats + ", statsPerLabel=" + statsPerLabel + '}'; } }
1,989
31.622951
97
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/EmailMessage.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import org.apache.commons.lang.builder.ToStringBuilder; public class EmailMessage { private String from = null; private String to = null; private String subject = null; private String message = null; private boolean html = false; private String messageId = null; /** * @param from full name of user, who initiated this message or null, if message was initiated by Sonar */ public EmailMessage setFrom(String from) { this.from = from; return this; } /** * @see #setFrom(String) */ public String getFrom() { return from; } /** * @param to email address where to send this message */ public EmailMessage setTo(String to) { this.to = to; return this; } /** * @see #setTo(String) */ public String getTo() { return to; } /** * @param subject message subject */ public EmailMessage setSubject(String subject) { this.subject = subject; return this; } /** * @see #setSubject(String) */ public String getSubject() { return subject; } /** * @param message message body */ public EmailMessage setPlainTextMessage(String message) { this.message = message; this.html = false; return this; } /** * @param message HTML message body */ public EmailMessage setHtmlMessage(String message) { this.message = message; this.html = true; return this; } /** * Either plain text or HTML. * @see #setPlainTextMessage(String) (String) * @see #setHtmlMessage(String) (String) (String) */ public String getMessage() { return message; } /** * @param messageId id of message for threading */ public EmailMessage setMessageId(String messageId) { this.messageId = messageId; return this; } /** * @see #setMessageId(String) */ public String getMessageId() { return messageId; } public boolean isHtml() { return html; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
2,923
21.492308
105
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/EmailTemplate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import javax.annotation.CheckForNull; import org.sonar.api.ExtensionPoint; import org.sonar.api.server.ServerSide; import org.sonar.api.notifications.Notification; @ServerSide @ExtensionPoint public interface EmailTemplate { @CheckForNull EmailMessage format(Notification notification); }
1,185
32.885714
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/FPOrWontFixNotification.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.SetMultimap; import java.util.Collection; import java.util.Objects; import org.sonar.api.notifications.Notification; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project; import static org.sonar.core.util.stream.MoreCollectors.unorderedIndex; /** * This notification is never serialized to DB. * <p> * It is derived from {@link IssuesChangesNotification} by * {@link FPOrWontFixNotificationHandler} and extends {@link Notification} only to comply with * {@link org.sonar.server.issue.notification.EmailTemplate#format(Notification)} API. */ class FPOrWontFixNotification extends Notification { private static final String KEY = "FPorWontFix"; public enum FpOrWontFix { FP, WONT_FIX } private final Change change; private final SetMultimap<Project, ChangedIssue> changedIssues; private final FpOrWontFix resolution; public FPOrWontFixNotification(Change change, Collection<ChangedIssue> changedIssues, FpOrWontFix resolution) { super(KEY); this.changedIssues = changedIssues.stream().collect(unorderedIndex(ChangedIssue::getProject, t -> t)); this.change = change; this.resolution = resolution; } public Change getChange() { return change; } public SetMultimap<Project, ChangedIssue> getChangedIssues() { return changedIssues; } public FpOrWontFix getResolution() { return resolution; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FPOrWontFixNotification that = (FPOrWontFixNotification) o; return Objects.equals(changedIssues, that.changedIssues) && Objects.equals(change, that.change) && resolution == that.resolution; } @Override public int hashCode() { return Objects.hash(changedIssues, change, resolution); } @Override public String toString() { return "FPOrWontFixNotification{" + "changedIssues=" + changedIssues + ", change=" + change + ", resolution=" + resolution + '}'; } }
3,182
31.814433
113
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/FPOrWontFixNotificationHandler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.sonar.api.issue.Issue; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; import org.sonar.server.notification.EmailNotificationHandler; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.notification.NotificationManager; import org.sonar.server.notification.NotificationManager.EmailRecipient; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest; import static com.google.common.collect.Sets.intersection; import static java.util.Collections.emptySet; import static java.util.Optional.of; import static java.util.Optional.ofNullable; import static org.sonar.core.util.stream.MoreCollectors.unorderedFlattenIndex; import static org.sonar.core.util.stream.MoreCollectors.unorderedIndex; import static org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix.FP; import static org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix.WONT_FIX; import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER; public class FPOrWontFixNotificationHandler extends EmailNotificationHandler<IssuesChangesNotification> { public static final String KEY = "NewFalsePositiveIssue"; private static final NotificationDispatcherMetadata METADATA = NotificationDispatcherMetadata.create(KEY) .setProperty(NotificationDispatcherMetadata.GLOBAL_NOTIFICATION, String.valueOf(false)) .setProperty(NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION, String.valueOf(true)); private static final Set<String> FP_OR_WONTFIX_RESOLUTIONS = ImmutableSet.of(Issue.RESOLUTION_FALSE_POSITIVE, Issue.RESOLUTION_WONT_FIX); private final NotificationManager notificationManager; private final IssuesChangesNotificationSerializer serializer; public FPOrWontFixNotificationHandler(NotificationManager notificationManager, EmailNotificationChannel emailNotificationChannel, IssuesChangesNotificationSerializer serializer) { super(emailNotificationChannel); this.notificationManager = notificationManager; this.serializer = serializer; } @Override public Optional<NotificationDispatcherMetadata> getMetadata() { return of(METADATA); } public static NotificationDispatcherMetadata newMetadata() { return METADATA; } @Override public Class<IssuesChangesNotification> getNotificationClass() { return IssuesChangesNotification.class; } @Override public Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<IssuesChangesNotification> notifications) { Set<NotificationWithProjectKeys> changeNotificationsWithFpOrWontFix = notifications.stream() .map(serializer::from) // ignore notifications which contain no issue changed to a FP or Won't Fix resolution .filter(t -> t.getIssues().stream() .filter(issue -> issue.getNewResolution().isPresent()) .anyMatch(issue -> FP_OR_WONTFIX_RESOLUTIONS.contains(issue.getNewResolution().get()))) .map(NotificationWithProjectKeys::new) .collect(Collectors.toSet()); if (changeNotificationsWithFpOrWontFix.isEmpty()) { return emptySet(); } Set<String> projectKeys = changeNotificationsWithFpOrWontFix.stream() .flatMap(t -> t.getProjectKeys().stream()) .collect(Collectors.toSet()); // shortcut to save from building unnecessary data structures when all changed issues in notifications belong to // the same project if (projectKeys.size() == 1) { Set<EmailRecipient> recipients = notificationManager.findSubscribedEmailRecipients(KEY, projectKeys.iterator().next(), ALL_MUST_HAVE_ROLE_USER); return changeNotificationsWithFpOrWontFix.stream() .flatMap(notification -> toRequests(notification, projectKeys, recipients)) .collect(Collectors.toSet()); } Set<EmailRecipientAndProject> recipientsByProjectKey = projectKeys.stream() .flatMap(projectKey -> notificationManager.findSubscribedEmailRecipients(KEY, projectKey, ALL_MUST_HAVE_ROLE_USER).stream() .map(emailRecipient -> new EmailRecipientAndProject(emailRecipient, projectKey))) .collect(Collectors.toSet()); // builds sets of projectKeys for which a given recipient has subscribed to SetMultimap<EmailRecipient, String> projectKeysByRecipient = recipientsByProjectKey.stream() .collect(unorderedIndex(t -> t.recipient, t -> t.projectKey)); // builds sets of recipients who subscribed to the same subset of projects Multimap<Set<String>, EmailRecipient> recipientsBySubscribedProjects = projectKeysByRecipient.asMap() .entrySet().stream() .collect(unorderedIndex(t -> (Set<String>) t.getValue(), Map.Entry::getKey)); return changeNotificationsWithFpOrWontFix.stream() .flatMap(notification -> { // builds sets of recipients for each sub group of the notification's projectKeys necessary SetMultimap<Set<String>, EmailRecipient> recipientsByProjectKeys = recipientsBySubscribedProjects.asMap().entrySet() .stream() .collect(unorderedFlattenIndex(t -> intersection(t.getKey(), notification.getProjectKeys()).immutableCopy(), t -> t.getValue().stream())); return recipientsByProjectKeys.asMap().entrySet().stream() .flatMap(entry -> toRequests(notification, entry.getKey(), entry.getValue())); }) .collect(Collectors.toSet()); } private static Stream<EmailDeliveryRequest> toRequests(NotificationWithProjectKeys notification, Set<String> projectKeys, Collection<EmailRecipient> recipients) { return recipients.stream() // do not notify author of the change .filter(recipient -> !notification.getChange().isAuthorLogin(recipient.login())) .flatMap(recipient -> { SetMultimap<String, ChangedIssue> issuesByNewResolution = notification.getIssues().stream() // ignore issues not changed to a FP or Won't Fix resolution .filter(issue -> issue.getNewResolution().filter(FP_OR_WONTFIX_RESOLUTIONS::contains).isPresent()) // ignore issues belonging to projects the recipients have not subscribed to .filter(issue -> projectKeys.contains(issue.getProject().getKey())) .collect(unorderedIndex(t -> t.getNewResolution().get(), issue -> issue)); return Stream.of( ofNullable(issuesByNewResolution.get(Issue.RESOLUTION_FALSE_POSITIVE)) .filter(t -> !t.isEmpty()) .map(fpIssues -> new FPOrWontFixNotification(notification.getChange(), fpIssues, FP)) .orElse(null), ofNullable(issuesByNewResolution.get(Issue.RESOLUTION_WONT_FIX)) .filter(t -> !t.isEmpty()) .map(wontFixIssues -> new FPOrWontFixNotification(notification.getChange(), wontFixIssues, WONT_FIX)) .orElse(null)) .filter(Objects::nonNull) .map(fpOrWontFixNotification -> new EmailDeliveryRequest(recipient.email(), fpOrWontFixNotification)); }); } private static final class EmailRecipientAndProject { private final EmailRecipient recipient; private final String projectKey; private EmailRecipientAndProject(EmailRecipient recipient, String projectKey) { this.recipient = recipient; this.projectKey = projectKey; } } }
8,616
49.098837
164
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/FpOrWontFixEmailTemplate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import javax.annotation.CheckForNull; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; import org.sonar.core.i18n.I18n; import org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.UserChange; import static org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix.FP; import static org.sonar.server.issue.notification.FPOrWontFixNotification.FpOrWontFix.WONT_FIX; /** * Creates email message for notification "issue-changes". */ public class FpOrWontFixEmailTemplate extends IssueChangesEmailTemplate { private static final String NOTIFICATION_NAME_I18N_KEY = "notification.dispatcher.NewFalsePositiveIssue"; public FpOrWontFixEmailTemplate(I18n i18n, EmailSettings settings) { super(i18n, settings); } @Override @CheckForNull public EmailMessage format(Notification notif) { if (!(notif instanceof FPOrWontFixNotification)) { return null; } FPOrWontFixNotification notification = (FPOrWontFixNotification) notif; EmailMessage emailMessage = new EmailMessage() .setMessageId(getMessageId(notification.getResolution())) .setSubject(buildSubject(notification)) .setHtmlMessage(buildMessage(notification)); if (notification.getChange() instanceof UserChange userChange) { User user = userChange.getUser(); emailMessage.setFrom(user.getName().orElse(user.getLogin())); } return emailMessage; } private static String getMessageId(FpOrWontFix resolution) { if (resolution == WONT_FIX) { return "wontfix-issue-changes"; } if (resolution == FP) { return "fp-issue-changes"; } throw new IllegalArgumentException("Unsupported resolution " + resolution); } private static String buildSubject(FPOrWontFixNotification notification) { return "Issues marked as " + resolutionLabel(notification.getResolution()); } private String buildMessage(FPOrWontFixNotification notification) { StringBuilder sb = new StringBuilder(); paragraph(sb, s -> s.append("Hi,")); paragraph(sb, s -> s.append("A manual change has resolved ").append(notification.getChangedIssues().size() > 1 ? "issues" : "an issue") .append(" as ").append(resolutionLabel(notification.getResolution())).append(":")); addIssuesByProjectThenRule(sb, notification.getChangedIssues()); addFooter(sb, NOTIFICATION_NAME_I18N_KEY); return sb.toString(); } private static String resolutionLabel(FpOrWontFix resolution) { if (resolution == WONT_FIX) { return "Won't Fix"; } if (resolution == FP) { return "False Positive"; } throw new IllegalArgumentException("Unsupported resolution " + resolution); } }
3,780
36.068627
139
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/IssueChangesEmailTemplate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.SetMultimap; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Set; import java.util.SortedSet; import java.util.function.BiConsumer; import java.util.function.Consumer; import javax.annotation.Nullable; import org.sonar.api.config.EmailSettings; import org.sonar.api.rules.RuleType; import org.sonar.core.i18n.I18n; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule; import static java.net.URLEncoder.encode; import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.function.Function.identity; import static org.apache.commons.lang.StringEscapeUtils.escapeHtml; import static org.sonar.core.util.stream.MoreCollectors.index; import static org.sonar.server.issue.notification.RuleGroup.ISSUES; import static org.sonar.server.issue.notification.RuleGroup.SECURITY_HOTSPOTS; import static org.sonar.server.issue.notification.RuleGroup.formatIssueOrHotspot; import static org.sonar.server.issue.notification.RuleGroup.formatIssuesOrHotspots; import static org.sonar.server.issue.notification.RuleGroup.resolveGroup; public abstract class IssueChangesEmailTemplate implements EmailTemplate { private static final Comparator<Rule> RULE_COMPARATOR = Comparator.comparing(r -> r.getKey().toString()); private static final Comparator<Project> PROJECT_COMPARATOR = Comparator.comparing(Project::getProjectName) .thenComparing(t -> t.getBranchName().orElse("")); private static final Comparator<ChangedIssue> CHANGED_ISSUE_KEY_COMPARATOR = Comparator.comparing(ChangedIssue::getKey, Comparator.naturalOrder()); /** * Assuming: * <ul> * <li>UUID length of 40 chars</li> * <li>a max URL length of 2083 chars</li> * </ul> * This leaves ~850 chars for the rest of the URL (including other parameters such as the project key and the branch), * which is reasonable to stay safe from the max URL length supported by some browsers and network devices. */ private static final int MAX_ISSUES_BY_LINK = 40; private static final String URL_ENCODED_COMMA = urlEncode(","); private final I18n i18n; private final EmailSettings settings; protected IssueChangesEmailTemplate(I18n i18n, EmailSettings settings) { this.i18n = i18n; this.settings = settings; } /** * Adds "projectName" or "projectName, branchName" if branchName is non null */ protected static void toString(StringBuilder sb, Project project) { Optional<String> branchName = project.getBranchName(); String value = project.getProjectName(); if (branchName.isPresent()) { value += ", " + branchName.get(); } sb.append(escapeHtml(value)); } static String toUrlParams(Project project) { return "id=" + urlEncode(project.getKey()) + project.getBranchName().map(branchName -> "&branch=" + urlEncode(branchName)).orElse(""); } void addIssuesByProjectThenRule(StringBuilder sb, SetMultimap<Project, ChangedIssue> issuesByProject) { issuesByProject.keySet().stream() .sorted(PROJECT_COMPARATOR) .forEach(project -> { String encodedProjectParams = toUrlParams(project); paragraph(sb, s -> toString(s, project)); addIssuesByRule(sb, issuesByProject.get(project), projectIssuePageHref(encodedProjectParams)); }); } void addIssuesAndHotspotsByProjectThenRule(StringBuilder sb, SetMultimap<Project, ChangedIssue> issuesByProject) { issuesByProject.keySet().stream() .sorted(PROJECT_COMPARATOR) .forEach(project -> { String encodedProjectParams = toUrlParams(project); paragraph(sb, s -> toString(s, project)); Set<ChangedIssue> changedIssues = issuesByProject.get(project); ListMultimap<RuleGroup, ChangedIssue> issuesAndHotspots = changedIssues.stream() .collect(index(changedIssue -> resolveGroup(changedIssue.getRule().getRuleType()), identity())); List<ChangedIssue> issues = issuesAndHotspots.get(ISSUES); List<ChangedIssue> hotspots = issuesAndHotspots.get(SECURITY_HOTSPOTS); boolean hasSecurityHotspots = !hotspots.isEmpty(); boolean hasOtherIssues = !issues.isEmpty(); if (hasOtherIssues) { addIssuesByRule(sb, issues, projectIssuePageHref(encodedProjectParams)); } if (hasSecurityHotspots && hasOtherIssues) { paragraph(sb, stringBuilder -> { }); } if (hasSecurityHotspots) { addIssuesByRule(sb, hotspots, securityHotspotPageHref(encodedProjectParams)); } }); } void addIssuesByRule(StringBuilder sb, Collection<ChangedIssue> changedIssues, BiConsumer<StringBuilder, Collection<ChangedIssue>> issuePageHref) { ListMultimap<Rule, ChangedIssue> issuesByRule = changedIssues.stream() .collect(index(ChangedIssue::getRule, t -> t)); Iterator<Rule> rules = issuesByRule.keySet().stream() .sorted(RULE_COMPARATOR) .iterator(); if (!rules.hasNext()) { return; } sb.append("<ul>"); while (rules.hasNext()) { Rule rule = rules.next(); Collection<ChangedIssue> issues = issuesByRule.get(rule); String ruleName = escapeHtml(rule.getName()); sb.append("<li>").append("Rule ").append(" <em>").append(ruleName).append("</em> - "); appendIssueLinks(sb, issuePageHref, issues, rule.getRuleType()); sb.append("</li>"); } sb.append("</ul>"); } private static void appendIssueLinks(StringBuilder sb, BiConsumer<StringBuilder, Collection<ChangedIssue>> issuePageHref, Collection<ChangedIssue> issues, @Nullable RuleType ruleType) { SortedSet<ChangedIssue> sortedIssues = ImmutableSortedSet.copyOf(CHANGED_ISSUE_KEY_COMPARATOR, issues); int issueCount = issues.size(); if (issueCount == 1) { link(sb, s -> issuePageHref.accept(s, sortedIssues), s -> s.append("See the single ").append(formatIssueOrHotspot(ruleType))); } else if (issueCount <= MAX_ISSUES_BY_LINK) { link(sb, s -> issuePageHref.accept(s, sortedIssues), s -> s.append("See all ").append(issueCount).append(" ").append(formatIssuesOrHotspots(ruleType))); } else { sb.append("See ").append(formatIssuesOrHotspots(ruleType)); List<List<ChangedIssue>> issueGroups = Lists.partition(ImmutableList.copyOf(sortedIssues), MAX_ISSUES_BY_LINK); Iterator<List<ChangedIssue>> issueGroupsIterator = issueGroups.iterator(); int[] groupIndex = new int[] {0}; while (issueGroupsIterator.hasNext()) { List<ChangedIssue> issueGroup = issueGroupsIterator.next(); sb.append(' '); link(sb, s -> issuePageHref.accept(s, issueGroup), issueGroupLabel(sb, groupIndex, issueGroup)); groupIndex[0]++; } } } BiConsumer<StringBuilder, Collection<ChangedIssue>> projectIssuePageHref(String projectParams) { return (s, issues) -> { s.append(settings.getServerBaseURL()).append("/project/issues?").append(projectParams) .append("&issues="); Iterator<ChangedIssue> issueIterator = issues.iterator(); while (issueIterator.hasNext()) { s.append(urlEncode(issueIterator.next().getKey())); if (issueIterator.hasNext()) { s.append(URL_ENCODED_COMMA); } } if (issues.size() == 1) { s.append("&open=").append(urlEncode(issues.iterator().next().getKey())); } }; } BiConsumer<StringBuilder, Collection<ChangedIssue>> securityHotspotPageHref(String projectParams) { return (s, issues) -> { s.append(settings.getServerBaseURL()).append("/security_hotspots?").append(projectParams) .append("&hotspots="); Iterator<ChangedIssue> issueIterator = issues.iterator(); while (issueIterator.hasNext()) { s.append(urlEncode(issueIterator.next().getKey())); if (issueIterator.hasNext()) { s.append(URL_ENCODED_COMMA); } } }; } private static Consumer<StringBuilder> issueGroupLabel(StringBuilder sb, int[] groupIndex, List<ChangedIssue> issueGroup) { return s -> { int firstIssueNumber = (groupIndex[0] * MAX_ISSUES_BY_LINK) + 1; if (issueGroup.size() == 1) { sb.append(firstIssueNumber); } else { sb.append(firstIssueNumber).append("-").append(firstIssueNumber + issueGroup.size() - 1); } }; } void addFooter(StringBuilder sb, String notificationI18nKey) { paragraph(sb, s -> s.append("&nbsp;")); paragraph(sb, s -> { s.append("<small>"); s.append("You received this email because you are subscribed to ") .append('"').append(i18n.message(Locale.ENGLISH, notificationI18nKey, notificationI18nKey)).append('"') .append(" notifications from SonarQube."); s.append(" Click "); link(s, s1 -> s1.append(settings.getServerBaseURL()).append("/account/notifications"), s1 -> s1.append("here")); s.append(" to edit your email preferences."); s.append("</small>"); }); } protected static void paragraph(StringBuilder sb, Consumer<StringBuilder> content) { sb.append("<p>"); content.accept(sb); sb.append("</p>"); } protected static void link(StringBuilder sb, Consumer<StringBuilder> link, Consumer<StringBuilder> content) { sb.append("<a href=\""); link.accept(sb); sb.append("\">"); content.accept(sb); sb.append("</a>"); } private static String urlEncode(String str) { try { return encode(str, UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } protected static String issueOrIssues(Collection<?> collection) { if (collection.size() > 1) { return "issues"; } return "issue"; } }
11,133
39.05036
158
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/IssuesChangesNotification.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import org.sonar.api.notifications.Notification; public class IssuesChangesNotification extends Notification { public static final String TYPE = "issues-changes"; public IssuesChangesNotification() { super(TYPE); } }
1,120
32.969697
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/IssuesChangesNotificationBuilder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.ImmutableSet; import java.util.Objects; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static java.util.Optional.ofNullable; @Immutable public class IssuesChangesNotificationBuilder { private static final String KEY_CANT_BE_NULL_MESSAGE = "key can't be null"; private final Set<ChangedIssue> issues; private final Change change; public IssuesChangesNotificationBuilder(Set<ChangedIssue> issues, Change change) { checkArgument(!issues.isEmpty(), "issues can't be empty"); this.issues = ImmutableSet.copyOf(issues); this.change = requireNonNull(change, "change can't be null"); } public Set<ChangedIssue> getIssues() { return issues; } public Change getChange() { return change; } @Immutable public static final class ChangedIssue { private final String key; private final String newStatus; @CheckForNull private final String newResolution; @CheckForNull private final User assignee; private final Rule rule; private final Project project; public ChangedIssue(Builder builder) { this.key = requireNonNull(builder.key, KEY_CANT_BE_NULL_MESSAGE); this.newStatus = requireNonNull(builder.newStatus, "newStatus can't be null"); this.newResolution = builder.newResolution; this.assignee = builder.assignee; this.rule = requireNonNull(builder.rule, "rule can't be null"); this.project = requireNonNull(builder.project, "project can't be null"); } public String getKey() { return key; } public String getNewStatus() { return newStatus; } public Optional<String> getNewResolution() { return ofNullable(newResolution); } public Optional<User> getAssignee() { return ofNullable(assignee); } public Rule getRule() { return rule; } public Project getProject() { return project; } public static class Builder { private final String key; private String newStatus; @CheckForNull private String newResolution; @CheckForNull private User assignee; private Rule rule; private Project project; public Builder(String key) { this.key = key; } public Builder setNewStatus(String newStatus) { this.newStatus = newStatus; return this; } public Builder setNewResolution(@Nullable String newResolution) { this.newResolution = newResolution; return this; } public Builder setAssignee(@Nullable User assignee) { this.assignee = assignee; return this; } public Builder setRule(Rule rule) { this.rule = rule; return this; } public Builder setProject(Project project) { this.project = project; return this; } public ChangedIssue build() { return new ChangedIssue(this); } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ChangedIssue that = (ChangedIssue) o; return key.equals(that.key) && newStatus.equals(that.newStatus) && Objects.equals(newResolution, that.newResolution) && Objects.equals(assignee, that.assignee) && rule.equals(that.rule) && project.equals(that.project); } @Override public int hashCode() { return Objects.hash(key, newStatus, newResolution, assignee, rule, project); } @Override public String toString() { return "ChangedIssue{" + "key='" + key + '\'' + ", newStatus='" + newStatus + '\'' + ", newResolution='" + newResolution + '\'' + ", assignee=" + assignee + ", rule=" + rule + ", project=" + project + '}'; } } public static final class User { private final String uuid; private final String login; @CheckForNull private final String name; public User(String uuid, String login, @Nullable String name) { this.uuid = requireNonNull(uuid, "uuid can't be null"); this.login = requireNonNull(login, "login can't be null"); this.name = name; } public String getUuid() { return uuid; } public String getLogin() { return login; } public Optional<String> getName() { return ofNullable(name); } @Override public String toString() { return "User{" + "uuid='" + uuid + '\'' + ", login='" + login + '\'' + ", name='" + name + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return uuid.equals(user.uuid) && login.equals(user.login) && Objects.equals(name, user.name); } @Override public int hashCode() { return Objects.hash(uuid, login, name); } } @Immutable public static final class Rule { private final RuleKey key; private final RuleType ruleType; private final String name; public Rule(RuleKey key, @Nullable String ruleType, String name) { this(key, ruleType != null ? RuleType.valueOf(ruleType) : null, name); } public Rule(RuleKey key, @Nullable RuleType ruleType, String name) { this.key = requireNonNull(key, KEY_CANT_BE_NULL_MESSAGE); this.ruleType = ruleType; this.name = requireNonNull(name, "name can't be null"); } public RuleKey getKey() { return key; } @CheckForNull public RuleType getRuleType() { return ruleType; } public String getName() { return name; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Rule that = (Rule) o; return key.equals(that.key) && ruleType == that.ruleType && name.equals(that.name); } @Override public int hashCode() { return Objects.hash(key, ruleType, name); } @Override public String toString() { return "Rule{" + "key=" + key + ", type=" + ruleType + ", name='" + name + '\'' + '}'; } } @Immutable public static final class Project { private final String uuid; private final String key; private final String projectName; @Nullable private final String branchName; public Project(Builder builder) { this.uuid = requireNonNull(builder.uuid, "uuid can't be null"); this.key = requireNonNull(builder.key, KEY_CANT_BE_NULL_MESSAGE); this.projectName = requireNonNull(builder.projectName, "projectName can't be null"); this.branchName = builder.branchName; } public String getUuid() { return uuid; } public String getKey() { return key; } public String getProjectName() { return projectName; } public Optional<String> getBranchName() { return ofNullable(branchName); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Project project = (Project) o; return uuid.equals(project.uuid) && key.equals(project.key) && projectName.equals(project.projectName) && Objects.equals(branchName, project.branchName); } @Override public int hashCode() { return Objects.hash(uuid, key, projectName, branchName); } @Override public String toString() { return "Project{" + "uuid='" + uuid + '\'' + ", key='" + key + '\'' + ", projectName='" + projectName + '\'' + ", branchName='" + branchName + '\'' + '}'; } public static class Builder { private final String uuid; private String key; private String projectName; @CheckForNull private String branchName; public Builder(String uuid) { this.uuid = uuid; } public Builder setKey(String key) { this.key = key; return this; } public Builder setProjectName(String projectName) { this.projectName = projectName; return this; } public Builder setBranchName(@Nullable String branchName) { this.branchName = branchName; return this; } public Project build() { return new Project(this); } } } public abstract static class Change { protected final long date; private Change(long date) { this.date = date; } public long getDate() { return date; } public abstract boolean isAuthorLogin(String login); } @Immutable public static final class AnalysisChange extends Change { public AnalysisChange(long date) { super(date); } @Override public boolean isAuthorLogin(String login) { return false; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Change change = (Change) o; return date == change.date; } @Override public int hashCode() { return Objects.hash(date); } @Override public String toString() { return "AnalysisChange{" + date + '}'; } } @Immutable public static final class UserChange extends Change { private final User user; public UserChange(long date, User user) { super(date); this.user = requireNonNull(user, "user can't be null"); } public User getUser() { return user; } @Override public boolean isAuthorLogin(String login) { return this.user.login.equals(login); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } UserChange that = (UserChange) o; return date == that.date && user.equals(that.user); } @Override public int hashCode() { return Objects.hash(user, date); } @Override public String toString() { return "UserChange{" + "date=" + date + ", user=" + user + '}'; } } }
11,743
23.724211
90
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/IssuesChangesNotificationModule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import org.sonar.core.platform.Module; public class IssuesChangesNotificationModule extends Module { @Override protected void configureModule() { add( ChangesOnMyIssueNotificationHandler.class, ChangesOnMyIssueNotificationHandler.newMetadata(), ChangesOnMyIssuesEmailTemplate.class, FPOrWontFixNotificationHandler.class, FPOrWontFixNotificationHandler.newMetadata(), IssuesChangesNotificationSerializer.class, FpOrWontFixEmailTemplate.class ); } }
1,394
35.710526
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/IssuesChangesNotificationSerializer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.sonar.api.rule.RuleKey; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Project; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Rule; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.User; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Optional.ofNullable; public class IssuesChangesNotificationSerializer { private static final String FIELD_ISSUES_COUNT = "issues.count"; private static final String FIELD_CHANGE_DATE = "change.date"; private static final String FIELD_CHANGE_AUTHOR_UUID = "change.author.uuid"; private static final String FIELD_CHANGE_AUTHOR_LOGIN = "change.author.login"; private static final String FIELD_CHANGE_AUTHOR_NAME = "change.author.name"; private static final String FIELD_PREFIX_RULES = "rules."; public IssuesChangesNotification serialize(IssuesChangesNotificationBuilder builder) { IssuesChangesNotification res = new IssuesChangesNotification(); serializeIssueSize(res, builder.getIssues()); serializeChange(res, builder.getChange()); serializeIssues(res, builder.getIssues()); serializeRules(res, builder.getIssues()); serializeProjects(res, builder.getIssues()); return res; } /** * @throws IllegalArgumentException if {@code notification} misses any field or of any has unsupported value */ public IssuesChangesNotificationBuilder from(IssuesChangesNotification notification) { int issueCount = readIssueCount(notification); IssuesChangesNotificationBuilder.Change change = readChange(notification); List<Issue> issues = readIssues(notification, issueCount); Map<String, Project> projects = readProjects(notification, issues); Map<RuleKey, Rule> rules = readRules(notification, issues); return new IssuesChangesNotificationBuilder(buildChangedIssues(issues, projects, rules), change); } private static void serializeIssueSize(IssuesChangesNotification res, Set<ChangedIssue> issues) { res.setFieldValue(FIELD_ISSUES_COUNT, String.valueOf(issues.size())); } private static int readIssueCount(IssuesChangesNotification notification) { String fieldValue = notification.getFieldValue(FIELD_ISSUES_COUNT); checkArgument(fieldValue != null, "missing field %s", FIELD_ISSUES_COUNT); int issueCount = Integer.parseInt(fieldValue); checkArgument(issueCount > 0, "issue count must be >= 1"); return issueCount; } private static Set<ChangedIssue> buildChangedIssues(List<Issue> issues, Map<String, Project> projects, Map<RuleKey, Rule> rules) { return issues.stream() .map(issue -> new ChangedIssue.Builder(issue.key) .setNewStatus(issue.newStatus) .setNewResolution(issue.newResolution) .setAssignee(issue.assignee) .setRule(rules.get(issue.ruleKey)) .setProject(projects.get(issue.projectUuid)) .build()) .collect(Collectors.toSet()); } private static void serializeIssues(IssuesChangesNotification res, Set<ChangedIssue> issues) { int index = 0; for (ChangedIssue issue : issues) { serializeIssue(res, index, issue); index++; } } private static List<Issue> readIssues(IssuesChangesNotification notification, int issueCount) { List<Issue> res = new ArrayList<>(issueCount); for (int i = 0; i < issueCount; i++) { res.add(readIssue(notification, i)); } return res; } private static void serializeIssue(IssuesChangesNotification notification, int index, ChangedIssue issue) { String issuePropertyPrefix = "issues." + index; notification.setFieldValue(issuePropertyPrefix + ".key", issue.getKey()); issue.getAssignee() .ifPresent(assignee -> { notification.setFieldValue(issuePropertyPrefix + ".assignee.uuid", assignee.getUuid()); notification.setFieldValue(issuePropertyPrefix + ".assignee.login", assignee.getLogin()); assignee.getName() .ifPresent(name -> notification.setFieldValue(issuePropertyPrefix + ".assignee.name", name)); }); issue.getNewResolution() .ifPresent(newResolution -> notification.setFieldValue(issuePropertyPrefix + ".newResolution", newResolution)); notification.setFieldValue(issuePropertyPrefix + ".newStatus", issue.getNewStatus()); notification.setFieldValue(issuePropertyPrefix + ".ruleKey", issue.getRule().getKey().toString()); notification.setFieldValue(issuePropertyPrefix + ".projectUuid", issue.getProject().getUuid()); } private static Issue readIssue(IssuesChangesNotification notification, int index) { String issuePropertyPrefix = "issues." + index; User assignee = readAssignee(notification, issuePropertyPrefix, index); return new Issue.Builder() .setKey(getIssueFieldValue(notification, issuePropertyPrefix + ".key", index)) .setNewStatus(getIssueFieldValue(notification, issuePropertyPrefix + ".newStatus", index)) .setNewResolution(notification.getFieldValue(issuePropertyPrefix + ".newResolution")) .setAssignee(assignee) .setRuleKey(getIssueFieldValue(notification, issuePropertyPrefix + ".ruleKey", index)) .setProjectUuid(getIssueFieldValue(notification, issuePropertyPrefix + ".projectUuid", index)) .build(); } @CheckForNull private static User readAssignee(IssuesChangesNotification notification, String issuePropertyPrefix, int index) { String uuid = notification.getFieldValue(issuePropertyPrefix + ".assignee.uuid"); if (uuid == null) { return null; } String login = getIssueFieldValue(notification, issuePropertyPrefix + ".assignee.login", index); return new User(uuid, login, notification.getFieldValue(issuePropertyPrefix + ".assignee.name")); } private static String getIssueFieldValue(IssuesChangesNotification notification, String fieldName, int index) { String fieldValue = notification.getFieldValue(fieldName); checkState(fieldValue != null, "Can not find field %s for issue with index %s", fieldName, index); return fieldValue; } private static void serializeRules(IssuesChangesNotification res, Set<ChangedIssue> issues) { issues.stream() .map(ChangedIssue::getRule) .collect(Collectors.toSet()) .forEach(rule -> { res.setFieldValue(FIELD_PREFIX_RULES + rule.getKey(), rule.getName()); ofNullable(rule.getRuleType()).ifPresent(ruleType -> res.setFieldValue(FIELD_PREFIX_RULES + rule.getKey() + ".type", rule.getRuleType().name())); }); } private static Map<RuleKey, Rule> readRules(IssuesChangesNotification notification, List<Issue> issues) { return issues.stream() .map(issue -> issue.ruleKey) .collect(Collectors.toSet()) .stream() .map(ruleKey -> readRule(notification, ruleKey)) .collect(Collectors.toMap(Rule::getKey, Function.identity())); } private static Rule readRule(IssuesChangesNotification notification, RuleKey ruleKey) { String fieldName = FIELD_PREFIX_RULES + ruleKey; String ruleName = notification.getFieldValue(fieldName); String ruleType = notification.getFieldValue(fieldName + ".type"); checkState(ruleName != null, "can not find field %s", ruleKey); return new Rule(ruleKey, ruleType, ruleName); } private static void serializeProjects(IssuesChangesNotification res, Set<ChangedIssue> issues) { issues.stream() .map(ChangedIssue::getProject) .collect(Collectors.toSet()) .forEach(project -> { String projectPropertyPrefix = "projects." + project.getUuid(); res.setFieldValue(projectPropertyPrefix + ".key", project.getKey()); res.setFieldValue(projectPropertyPrefix + ".projectName", project.getProjectName()); project.getBranchName() .ifPresent(branchName -> res.setFieldValue(projectPropertyPrefix + ".branchName", branchName)); }); } private static Map<String, Project> readProjects(IssuesChangesNotification notification, List<Issue> issues) { return issues.stream() .map(issue -> issue.projectUuid) .collect(Collectors.toSet()) .stream() .map(projectUuid -> { String projectPropertyPrefix = "projects." + projectUuid; return new Project.Builder(projectUuid) .setKey(getProjectFieldValue(notification, projectPropertyPrefix + ".key", projectUuid)) .setProjectName(getProjectFieldValue(notification, projectPropertyPrefix + ".projectName", projectUuid)) .setBranchName(notification.getFieldValue(projectPropertyPrefix + ".branchName")) .build(); }) .collect(Collectors.toMap(Project::getUuid, Function.identity())); } private static String getProjectFieldValue(IssuesChangesNotification notification, String fieldName, String uuid) { String fieldValue = notification.getFieldValue(fieldName); checkState(fieldValue != null, "Can not find field %s for project with uuid %s", fieldName, uuid); return fieldValue; } private static void serializeChange(IssuesChangesNotification notification, IssuesChangesNotificationBuilder.Change change) { notification.setFieldValue(FIELD_CHANGE_DATE, String.valueOf(change.date)); if (change instanceof IssuesChangesNotificationBuilder.UserChange userChange) { User user = userChange.getUser(); notification.setFieldValue(FIELD_CHANGE_AUTHOR_UUID, user.getUuid()); notification.setFieldValue(FIELD_CHANGE_AUTHOR_LOGIN, user.getLogin()); user.getName().ifPresent(name -> notification.setFieldValue(FIELD_CHANGE_AUTHOR_NAME, name)); } } private static IssuesChangesNotificationBuilder.Change readChange(IssuesChangesNotification notification) { String dateFieldValue = notification.getFieldValue(FIELD_CHANGE_DATE); checkState(dateFieldValue != null, "Can not find field %s", FIELD_CHANGE_DATE); long date = Long.parseLong(dateFieldValue); String uuid = notification.getFieldValue(FIELD_CHANGE_AUTHOR_UUID); if (uuid == null) { return new IssuesChangesNotificationBuilder.AnalysisChange(date); } String login = notification.getFieldValue(FIELD_CHANGE_AUTHOR_LOGIN); checkState(login != null, "Can not find field %s", FIELD_CHANGE_AUTHOR_LOGIN); return new IssuesChangesNotificationBuilder.UserChange(date, new User(uuid, login, notification.getFieldValue(FIELD_CHANGE_AUTHOR_NAME))); } @Immutable private static final class Issue { private final String key; private final String newStatus; @CheckForNull private final String newResolution; @CheckForNull private final User assignee; private final RuleKey ruleKey; private final String projectUuid; private Issue(Builder builder) { this.key = builder.key; this.newResolution = builder.newResolution; this.newStatus = builder.newStatus; this.assignee = builder.assignee; this.ruleKey = RuleKey.parse(builder.ruleKey); this.projectUuid = builder.projectUuid; } static class Builder { private String key = null; private String newStatus = null; @CheckForNull private String newResolution = null; @CheckForNull private User assignee = null; private String ruleKey = null; private String projectUuid = null; public Builder setKey(String key) { this.key = key; return this; } public Builder setNewStatus(String newStatus) { this.newStatus = newStatus; return this; } public Builder setNewResolution(@Nullable String newResolution) { this.newResolution = newResolution; return this; } public Builder setAssignee(@Nullable User assignee) { this.assignee = assignee; return this; } public Builder setRuleKey(String ruleKey) { this.ruleKey = ruleKey; return this; } public Builder setProjectUuid(String projectUuid) { this.projectUuid = projectUuid; return this; } public Issue build() { return new Issue(this); } } } }
13,449
42.108974
153
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/MetricStatsInt.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; public class MetricStatsInt { private int onCurrentAnalysis = 0; private int offCurrentAnalysis = 0; MetricStatsInt increment(boolean onCurrentAnalysis) { if (onCurrentAnalysis) { this.onCurrentAnalysis += 1; } else { this.offCurrentAnalysis += 1; } return this; } public int getOnCurrentAnalysis() { return onCurrentAnalysis; } public int getTotal() { return onCurrentAnalysis + offCurrentAnalysis; } @Override public String toString() { return "MetricStatsInt{" + "on=" + onCurrentAnalysis + ", off=" + offCurrentAnalysis + '}'; } }
1,508
28.588235
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/MetricStatsLong.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; public class MetricStatsLong { private long onCurrentAnalysis = 0; private long offCurrentAnalysis = 0; MetricStatsLong add(long toAdd, boolean onCurrentAnalysis) { if (onCurrentAnalysis) { this.onCurrentAnalysis += toAdd; } else { this.offCurrentAnalysis += toAdd; } return this; } public long getOnCurrentAnalysis() { return onCurrentAnalysis; } public long getOffCurrentAnalysis() { return offCurrentAnalysis; } public long getTotal() { return onCurrentAnalysis + offCurrentAnalysis; } @Override public String toString() { return "MetricStatsLong{" + "on=" + onCurrentAnalysis + ", off=" + offCurrentAnalysis + '}'; } }
1,605
28.2
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/MyNewIssuesEmailTemplate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.util.Date; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; import org.sonar.api.utils.DateUtils; import org.sonar.core.i18n.I18n; import org.sonar.server.issue.notification.NewIssuesStatistics.Metric; /** * Creates email message for notification "my-new-issues". */ public class MyNewIssuesEmailTemplate extends AbstractNewIssuesEmailTemplate { public MyNewIssuesEmailTemplate(EmailSettings settings, I18n i18n) { super(settings, i18n); } @Override protected boolean shouldNotFormat(Notification notification) { return !MyNewIssuesNotification.MY_NEW_ISSUES_NOTIF_TYPE.equals(notification.getType()); } @Override protected void appendAssignees(StringBuilder message, Notification notification) { // do nothing as we don't want to print assignees, it's a personalized email for one person } @Override protected String subject(Notification notification, String fullProjectName) { int issueCount = Integer.parseInt(notification.getFieldValue(Metric.RULE_TYPE + COUNT)); return String.format("You have %s new issue%s on project %s", issueCount, issueCount > 1 ? "s" : "", fullProjectName); } @Override protected void appendFooter(StringBuilder message, Notification notification) { String projectKey = notification.getFieldValue(FIELD_PROJECT_KEY); String dateString = notification.getFieldValue(FIELD_PROJECT_DATE); String assignee = notification.getFieldValue(FIELD_ASSIGNEE); if (projectKey != null && dateString != null && assignee != null) { Date date = DateUtils.parseDateTime(dateString); String url = String.format("%s/project/issues?id=%s&assignees=%s", settings.getServerBaseURL(), encode(projectKey), encode(assignee)); String branchName = notification.getFieldValue(FIELD_BRANCH); if (branchName != null) { url += "&branch=" + encode(branchName); } String pullRequest = notification.getFieldValue(FIELD_PULL_REQUEST); if (pullRequest != null) { url += "&pullRequest=" + encode(pullRequest); } url += "&createdAt=" + encode(DateUtils.formatDateTime(date)); message .append("More details at: ") .append(url) .append(NEW_LINE); } } }
3,202
37.130952
95
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/MyNewIssuesNotification.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.utils.Durations; import org.sonar.db.user.UserDto; import static org.sonar.server.issue.notification.AbstractNewIssuesEmailTemplate.FIELD_ASSIGNEE; public class MyNewIssuesNotification extends NewIssuesNotification { public static final String MY_NEW_ISSUES_NOTIF_TYPE = "my-new-issues"; public MyNewIssuesNotification(Durations durations, DetailsSupplier detailsSupplier) { super(MY_NEW_ISSUES_NOTIF_TYPE, durations, detailsSupplier); } public MyNewIssuesNotification setAssignee(@Nullable UserDto assignee) { if (assignee == null) { return this; } setFieldValue(FIELD_ASSIGNEE, assignee.getLogin()); return this; } @CheckForNull public String getAssignee() { return getFieldValue(FIELD_ASSIGNEE); } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
1,894
30.583333
96
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/MyNewIssuesNotificationHandler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.sonar.server.notification.EmailNotificationHandler; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.notification.NotificationManager; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest; import static java.util.Collections.emptySet; import static org.sonar.core.util.stream.MoreCollectors.index; import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION; import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION; import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER; public class MyNewIssuesNotificationHandler extends EmailNotificationHandler<MyNewIssuesNotification> { public static final String KEY = "SQ-MyNewIssues"; private static final NotificationDispatcherMetadata METADATA = NotificationDispatcherMetadata.create(KEY) .setProperty(GLOBAL_NOTIFICATION, String.valueOf(true)) .setProperty(PER_PROJECT_NOTIFICATION, String.valueOf(true)); private final NotificationManager notificationManager; public MyNewIssuesNotificationHandler(NotificationManager notificationManager, EmailNotificationChannel emailNotificationChannel) { super(emailNotificationChannel); this.notificationManager = notificationManager; } @Override public Optional<NotificationDispatcherMetadata> getMetadata() { return Optional.of(METADATA); } public static NotificationDispatcherMetadata newMetadata() { return METADATA; } @Override public Class<MyNewIssuesNotification> getNotificationClass() { return MyNewIssuesNotification.class; } @Override public Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<MyNewIssuesNotification> notifications) { Multimap<String, MyNewIssuesNotification> notificationsByProjectKey = notifications.stream() .filter(t -> t.getProjectKey() != null) .filter(t -> t.getAssignee() != null) .collect(index(MyNewIssuesNotification::getProjectKey)); if (notificationsByProjectKey.isEmpty()) { return emptySet(); } return notificationsByProjectKey.asMap().entrySet() .stream() .flatMap(e -> toEmailDeliveryRequests(e.getKey(), e.getValue())) .collect(Collectors.toSet()); } private Stream<? extends EmailDeliveryRequest> toEmailDeliveryRequests(String projectKey, Collection<MyNewIssuesNotification> notifications) { Set<String> assignees = notifications.stream() .map(MyNewIssuesNotification::getAssignee) .collect(Collectors.toSet()); Map<String, NotificationManager.EmailRecipient> recipientsByLogin = notificationManager .findSubscribedEmailRecipients(KEY, projectKey, assignees, ALL_MUST_HAVE_ROLE_USER) .stream() .collect(Collectors.toMap(NotificationManager.EmailRecipient::login, Function.identity())); return notifications.stream() .map(notification -> toEmailDeliveryRequest(recipientsByLogin, notification)) .filter(Objects::nonNull); } @CheckForNull private static EmailDeliveryRequest toEmailDeliveryRequest(Map<String, NotificationManager.EmailRecipient> recipientsByLogin, MyNewIssuesNotification notification) { String assignee = notification.getAssignee(); NotificationManager.EmailRecipient emailRecipient = recipientsByLogin.get(assignee); if (emailRecipient != null) { return new EmailDeliveryRequest(emailRecipient.email(), notification); } return null; } }
4,824
41.699115
144
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/NewIssuesEmailTemplate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; import org.sonar.core.i18n.I18n; /** * Creates email message for notification "new-issues". */ public class NewIssuesEmailTemplate extends AbstractNewIssuesEmailTemplate { public NewIssuesEmailTemplate(EmailSettings settings, I18n i18n) { super(settings, i18n); } @Override protected boolean shouldNotFormat(Notification notification) { return !NewIssuesNotification.TYPE.equals(notification.getType()); } }
1,412
34.325
76
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/NewIssuesNotification.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.ToIntFunction; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.notifications.Notification; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.Duration; import org.sonar.api.utils.Durations; import org.sonar.server.issue.notification.NewIssuesStatistics.Metric; import static java.util.Objects.requireNonNull; import static org.sonar.server.issue.notification.AbstractNewIssuesEmailTemplate.FIELD_BRANCH; import static org.sonar.server.issue.notification.AbstractNewIssuesEmailTemplate.FIELD_PROJECT_VERSION; import static org.sonar.server.issue.notification.AbstractNewIssuesEmailTemplate.FIELD_PULL_REQUEST; import static org.sonar.server.issue.notification.NewIssuesEmailTemplate.FIELD_PROJECT_DATE; import static org.sonar.server.issue.notification.NewIssuesEmailTemplate.FIELD_PROJECT_KEY; import static org.sonar.server.issue.notification.NewIssuesEmailTemplate.FIELD_PROJECT_NAME; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE_TYPE; public class NewIssuesNotification extends Notification { public static final String TYPE = "new-issues"; private static final long serialVersionUID = -6305871981920103093L; private static final String COUNT = ".count"; private static final String LABEL = ".label"; private static final String DOT = "."; private final transient DetailsSupplier detailsSupplier; private final transient Durations durations; public NewIssuesNotification(Durations durations, DetailsSupplier detailsSupplier) { this(TYPE, durations, detailsSupplier); } protected NewIssuesNotification(String type, Durations durations, DetailsSupplier detailsSupplier) { super(type); this.durations = durations; this.detailsSupplier = detailsSupplier; } public interface DetailsSupplier { /** * @throws NullPointerException if {@code ruleKey} is {@code null} */ Optional<RuleDefinition> getRuleDefinitionByRuleKey(RuleKey ruleKey); /** * @throws NullPointerException if {@code uuid} is {@code null} */ Optional<String> getComponentNameByUuid(String uuid); /** * @throws NullPointerException if {@code uuid} is {@code null} */ Optional<String> getUserNameByUuid(String uuid); } public record RuleDefinition(String name, String language) { public RuleDefinition(String name, @Nullable String language) { this.name = requireNonNull(name, "name can't be null"); this.language = language; } @Override public String toString() { return "RuleDefinition{" + name + " (" + language + ')' + '}'; } } public NewIssuesNotification setAnalysisDate(Date d) { setFieldValue(FIELD_PROJECT_DATE, DateUtils.formatDateTime(d)); return this; } public NewIssuesNotification setProject(String projectKey, String projectName, @Nullable String branchName, @Nullable String pullRequest) { setFieldValue(FIELD_PROJECT_NAME, projectName); setFieldValue(FIELD_PROJECT_KEY, projectKey); if (branchName != null) { setFieldValue(FIELD_BRANCH, branchName); } if (pullRequest != null) { setFieldValue(FIELD_PULL_REQUEST, pullRequest); } return this; } @CheckForNull public String getProjectKey() { return getFieldValue(FIELD_PROJECT_KEY); } public NewIssuesNotification setProjectVersion(@Nullable String version) { if (version != null) { setFieldValue(FIELD_PROJECT_VERSION, version); } return this; } public NewIssuesNotification setStatistics(String projectName, NewIssuesStatistics.Stats stats) { setDefaultMessage(stats.getDistributedMetricStats(RULE_TYPE).getOnCurrentAnalysis() + " new issues on " + projectName + ".\n"); setRuleTypeStatistics(stats); setAssigneesStatistics(stats); setTagsStatistics(stats); setComponentsStatistics(stats); setRuleStatistics(stats); return this; } private void setRuleStatistics(NewIssuesStatistics.Stats stats) { Metric metric = Metric.RULE; List<Map.Entry<String, MetricStatsInt>> fiveBiggest = fiveBiggest(stats.getDistributedMetricStats(metric), MetricStatsInt::getOnCurrentAnalysis); int i = 1; for (Map.Entry<String, MetricStatsInt> ruleStats : fiveBiggest) { String ruleKey = ruleStats.getKey(); RuleDefinition rule = detailsSupplier.getRuleDefinitionByRuleKey(RuleKey.parse(ruleKey)) .orElseThrow(() -> new IllegalStateException(String.format("Rule with key '%s' does not exist", ruleKey))); String name = rule.name() + " (" + rule.language() + ")"; setFieldValue(metric + DOT + i + LABEL, name); setFieldValue(metric + DOT + i + COUNT, String.valueOf(ruleStats.getValue().getOnCurrentAnalysis())); i++; } } private void setComponentsStatistics(NewIssuesStatistics.Stats stats) { Metric metric = Metric.COMPONENT; int i = 1; List<Map.Entry<String, MetricStatsInt>> fiveBiggest = fiveBiggest(stats.getDistributedMetricStats(metric), MetricStatsInt::getOnCurrentAnalysis); for (Map.Entry<String, MetricStatsInt> componentStats : fiveBiggest) { String uuid = componentStats.getKey(); String componentName = detailsSupplier.getComponentNameByUuid(uuid) .orElseThrow(() -> new IllegalStateException(String.format("Component with uuid '%s' not found", uuid))); setFieldValue(metric + DOT + i + LABEL, componentName); setFieldValue(metric + DOT + i + COUNT, String.valueOf(componentStats.getValue().getOnCurrentAnalysis())); i++; } } private void setTagsStatistics(NewIssuesStatistics.Stats stats) { Metric metric = Metric.TAG; int i = 1; for (Map.Entry<String, MetricStatsInt> tagStats : fiveBiggest(stats.getDistributedMetricStats(metric), MetricStatsInt::getOnCurrentAnalysis)) { setFieldValue(metric + DOT + i + COUNT, String.valueOf(tagStats.getValue().getOnCurrentAnalysis())); setFieldValue(metric + DOT + i + LABEL, tagStats.getKey()); i++; } } private void setAssigneesStatistics(NewIssuesStatistics.Stats stats) { Metric metric = Metric.ASSIGNEE; List<Map.Entry<String, MetricStatsInt>> entries = fiveBiggest(stats.getDistributedMetricStats(metric), MetricStatsInt::getOnCurrentAnalysis); int i = 1; for (Map.Entry<String, MetricStatsInt> assigneeStats : entries) { String assigneeUuid = assigneeStats.getKey(); String name = detailsSupplier.getUserNameByUuid(assigneeUuid).orElse(assigneeUuid); setFieldValue(metric + DOT + i + LABEL, name); setFieldValue(metric + DOT + i + COUNT, String.valueOf(assigneeStats.getValue().getOnCurrentAnalysis())); i++; } } private static List<Map.Entry<String, MetricStatsInt>> fiveBiggest(DistributedMetricStatsInt distributedMetricStatsInt, ToIntFunction<MetricStatsInt> biggerCriteria) { Comparator<Map.Entry<String, MetricStatsInt>> comparator = Comparator.comparingInt(a -> biggerCriteria.applyAsInt(a.getValue())); return distributedMetricStatsInt.getForLabels() .entrySet() .stream() .filter(i -> biggerCriteria.applyAsInt(i.getValue()) > 0) .sorted(comparator.reversed()) .limit(5) .toList(); } public NewIssuesNotification setDebt(Duration debt) { setFieldValue(Metric.EFFORT + COUNT, durations.format(debt)); return this; } private void setRuleTypeStatistics(NewIssuesStatistics.Stats stats) { DistributedMetricStatsInt distributedMetricStats = stats.getDistributedMetricStats(RULE_TYPE); setFieldValue(RULE_TYPE + COUNT, String.valueOf(distributedMetricStats.getOnCurrentAnalysis())); Arrays.stream(RuleType.values()) .forEach(ruleType -> setFieldValue( RULE_TYPE + DOT + ruleType + COUNT, String.valueOf(distributedMetricStats.getForLabel(ruleType.name()).map(MetricStatsInt::getOnCurrentAnalysis).orElse(0)))); } @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } }
9,177
39.431718
169
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/NewIssuesNotificationHandler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import com.google.common.collect.Multimap; import java.util.Collection; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import org.sonar.server.notification.EmailNotificationHandler; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.notification.NotificationManager; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest; import static java.util.Collections.emptySet; import static org.sonar.core.util.stream.MoreCollectors.index; import static org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject.ALL_MUST_HAVE_ROLE_USER; public class NewIssuesNotificationHandler extends EmailNotificationHandler<NewIssuesNotification> { public static final String KEY = "NewIssues"; private static final NotificationDispatcherMetadata METADATA = NotificationDispatcherMetadata.create(KEY) .setProperty(NotificationDispatcherMetadata.GLOBAL_NOTIFICATION, String.valueOf(false)) .setProperty(NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION, String.valueOf(true)); private final NotificationManager notificationManager; public NewIssuesNotificationHandler(NotificationManager notificationManager, EmailNotificationChannel emailNotificationChannel) { super(emailNotificationChannel); this.notificationManager = notificationManager; } @Override public Optional<NotificationDispatcherMetadata> getMetadata() { return Optional.of(METADATA); } public static NotificationDispatcherMetadata newMetadata() { return METADATA; } @Override public Class<NewIssuesNotification> getNotificationClass() { return NewIssuesNotification.class; } @Override public Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<NewIssuesNotification> notifications) { Multimap<String, NewIssuesNotification> notificationsByProjectKey = notifications.stream() .filter(t -> t.getProjectKey() != null) .collect(index(NewIssuesNotification::getProjectKey)); if (notificationsByProjectKey.isEmpty()) { return emptySet(); } return notificationsByProjectKey.asMap().entrySet() .stream() .flatMap(e -> toEmailDeliveryRequests(e.getKey(), e.getValue())) .collect(Collectors.toSet()); } private Stream<? extends EmailDeliveryRequest> toEmailDeliveryRequests(String projectKey, Collection<NewIssuesNotification> notifications) { return notificationManager.findSubscribedEmailRecipients(KEY, projectKey, ALL_MUST_HAVE_ROLE_USER) .stream() .flatMap(emailRecipient -> notifications.stream() .map(notification -> new EmailDeliveryRequest(emailRecipient.email(), notification))); } }
3,722
40.831461
142
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/NewIssuesStatistics.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.util.EnumMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.function.Predicate; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.Duration; import org.sonar.core.issue.DefaultIssue; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.ASSIGNEE; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.COMPONENT; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.RULE_TYPE; import static org.sonar.server.issue.notification.NewIssuesStatistics.Metric.TAG; public class NewIssuesStatistics { private final Predicate<DefaultIssue> onCurrentAnalysisPredicate; private final Map<String, Stats> assigneesStatistics = new LinkedHashMap<>(); private final Stats globalStatistics; public NewIssuesStatistics(Predicate<DefaultIssue> onCurrentAnalysisPredicate) { this.onCurrentAnalysisPredicate = onCurrentAnalysisPredicate; this.globalStatistics = new Stats(onCurrentAnalysisPredicate); } public void add(DefaultIssue issue) { globalStatistics.add(issue); String userUuid = issue.assignee(); if (userUuid != null) { assigneesStatistics.computeIfAbsent(userUuid, a -> new Stats(onCurrentAnalysisPredicate)).add(issue); } } public Map<String, Stats> getAssigneesStatistics() { return assigneesStatistics; } public Stats globalStatistics() { return globalStatistics; } public boolean hasIssues() { return globalStatistics.hasIssues(); } public boolean hasIssuesOnCurrentAnalysis() { return globalStatistics.hasIssuesOnCurrentAnalysis(); } public enum Metric { RULE_TYPE(true), TAG(true), COMPONENT(true), ASSIGNEE(true), EFFORT(false), RULE(true); private final boolean isComputedByDistribution; Metric(boolean isComputedByDistribution) { this.isComputedByDistribution = isComputedByDistribution; } boolean isComputedByDistribution() { return this.isComputedByDistribution; } } @Override public String toString() { return "NewIssuesStatistics{" + "assigneesStatistics=" + assigneesStatistics + ", globalStatistics=" + globalStatistics + '}'; } public static class Stats { private final Predicate<DefaultIssue> onCurrentAnalysisPredicate; private final Map<Metric, DistributedMetricStatsInt> distributions = new EnumMap<>(Metric.class); private MetricStatsLong effortStats = new MetricStatsLong(); public Stats(Predicate<DefaultIssue> onCurrentAnalysisPredicate) { this.onCurrentAnalysisPredicate = onCurrentAnalysisPredicate; for (Metric metric : Metric.values()) { if (metric.isComputedByDistribution()) { distributions.put(metric, new DistributedMetricStatsInt()); } } } public void add(DefaultIssue issue) { boolean onCurrentAnalysis = onCurrentAnalysisPredicate.test(issue); distributions.get(RULE_TYPE).increment(issue.type().name(), onCurrentAnalysis); String componentUuid = issue.componentUuid(); if (componentUuid != null) { distributions.get(COMPONENT).increment(componentUuid, onCurrentAnalysis); } RuleKey ruleKey = issue.ruleKey(); if (ruleKey != null) { distributions.get(RULE).increment(ruleKey.toString(), onCurrentAnalysis); } String assigneeUuid = issue.assignee(); if (assigneeUuid != null) { distributions.get(ASSIGNEE).increment(assigneeUuid, onCurrentAnalysis); } for (String tag : issue.tags()) { distributions.get(TAG).increment(tag, onCurrentAnalysis); } Duration effort = issue.effort(); if (effort != null) { effortStats.add(effort.toMinutes(), onCurrentAnalysis); } } public DistributedMetricStatsInt getDistributedMetricStats(Metric metric) { return distributions.get(metric); } public MetricStatsLong effort() { return effortStats; } public boolean hasIssues() { return getDistributedMetricStats(RULE_TYPE).getTotal() > 0; } public boolean hasIssuesOnCurrentAnalysis() { return getDistributedMetricStats(RULE_TYPE).getOnCurrentAnalysis() > 0; } @Override public String toString() { return "Stats{" + "distributions=" + distributions + ", effortStats=" + effortStats + '}'; } } }
5,365
33.619355
107
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/NotificationWithProjectKeys.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.util.Set; import java.util.stream.Collectors; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.Change; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; final class NotificationWithProjectKeys { private final IssuesChangesNotificationBuilder builder; private final Set<String> projectKeys; protected NotificationWithProjectKeys(IssuesChangesNotificationBuilder builder) { this.builder = builder; this.projectKeys = builder.getIssues().stream().map(t -> t.getProject().getKey()).collect(Collectors.toSet()); } public Set<ChangedIssue> getIssues() { return builder.getIssues(); } public Change getChange() { return builder.getChange(); } public Set<String> getProjectKeys() { return projectKeys; } }
1,711
34.666667
114
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/RuleGroup.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.notification; import java.util.Collection; import javax.annotation.Nullable; import org.sonar.api.rules.RuleType; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; enum RuleGroup { SECURITY_HOTSPOTS, ISSUES; static RuleGroup resolveGroup(@Nullable RuleType ruleType) { return SECURITY_HOTSPOT.equals(ruleType) ? SECURITY_HOTSPOTS : ISSUES; } static String formatIssuesOrHotspots(Collection<?> issues, Collection<?> hotspots) { if (!issues.isEmpty() && !hotspots.isEmpty()) { return "issues/hotspots"; } if (issues.size() == 1) { return "an issue"; } if (issues.size() > 1) { return "issues"; } if (hotspots.size() == 1) { return "a hotspot"; } return "hotspots"; } static String formatIssueOrHotspot(@Nullable RuleType ruleType) { if (SECURITY_HOTSPOT.equals(ruleType)) { return "hotspot"; } return "issue"; } static String formatIssuesOrHotspots(@Nullable RuleType ruleType) { if (SECURITY_HOTSPOT.equals(ruleType)) { return "hotspots"; } return "issues"; } }
1,973
28.909091
86
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/notification/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.issue.notification; import javax.annotation.ParametersAreNonnullByDefault;
975
39.666667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/Condition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import org.sonar.api.issue.Issue; public interface Condition { boolean matches(Issue issue); }
985
33
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/Function.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import javax.annotation.Nullable; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.db.user.UserDto; interface Function { interface Context { Issue issue(); Context setAssignee(@Nullable UserDto user); Context setResolution(@Nullable String s); Context setCloseDate(); Context unsetCloseDate(); Context unsetLine(); Context setType(@Nullable RuleType type); } void execute(Context context); }
1,358
28.543478
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/FunctionExecutor.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import javax.annotation.Nullable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ServerSide; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.IssueChangeContext; import org.sonar.db.user.UserDto; import org.sonar.server.issue.IssueFieldsSetter; @ServerSide @ComputeEngineSide public class FunctionExecutor { private final IssueFieldsSetter updater; public FunctionExecutor(IssueFieldsSetter updater) { this.updater = updater; } public void execute(Function[] functions, DefaultIssue issue, IssueChangeContext changeContext) { if (functions.length > 0) { FunctionContext functionContext = new FunctionContext(updater, issue, changeContext); for (Function function : functions) { function.execute(functionContext); } } } static class FunctionContext implements Function.Context { private final IssueFieldsSetter updater; private final DefaultIssue issue; private final IssueChangeContext changeContext; FunctionContext(IssueFieldsSetter updater, DefaultIssue issue, IssueChangeContext changeContext) { this.updater = updater; this.issue = issue; this.changeContext = changeContext; } @Override public Issue issue() { return issue; } @Override public Function.Context setAssignee(@Nullable UserDto user) { updater.assign(issue, user, changeContext); return this; } @Override public Function.Context setResolution(@Nullable String s) { updater.setResolution(issue, s, changeContext); return this; } @Override public Function.Context setCloseDate() { updater.setCloseDate(issue, changeContext.date(), changeContext); return this; } @Override public Function.Context unsetCloseDate() { updater.setCloseDate(issue, null, changeContext); return this; } @Override public Function.Context unsetLine() { updater.unsetLine(issue, changeContext); return this; } @Override public Function.Context setType(RuleType type) { updater.setType(issue, type, changeContext); return this; } } }
3,138
29.182692
102
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/HasResolution.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import java.util.HashSet; import java.util.Set; import org.sonar.api.issue.Issue; import static java.util.Arrays.asList; public class HasResolution implements Condition { private final Set<String> resolutions; public HasResolution(String first, String... others) { this.resolutions = new HashSet<>(); this.resolutions.add(first); this.resolutions.addAll(asList(others)); } @Override public boolean matches(Issue issue) { return issue.resolution() != null && resolutions.contains(issue.resolution()); } }
1,422
32.093023
82
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/HasType.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import java.util.EnumSet; import java.util.Set; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; import static java.util.Arrays.asList; public class HasType implements Condition { private final Set<RuleType> types; public HasType(RuleType first, RuleType... others) { this.types = EnumSet.noneOf(RuleType.class); this.types.add(first); this.types.addAll(asList(others)); } @Override public boolean matches(Issue issue) { return types.contains(((DefaultIssue) issue).type()); } }
1,461
31.488889
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/IsBeingClosed.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import org.sonar.api.issue.Issue; import org.sonar.core.issue.DefaultIssue; enum IsBeingClosed implements Condition { INSTANCE; @Override public boolean matches(Issue issue) { return ((DefaultIssue) issue).isBeingClosed(); } }
1,126
33.151515
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/IsHotspot.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; enum IsHotspot implements Condition { INSTANCE; @Override public boolean matches(Issue issue) { return ((DefaultIssue) issue).type() == RuleType.SECURITY_HOTSPOT; } }
1,179
33.705882
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/IsNotHotspot.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; enum IsNotHotspot implements Condition { INSTANCE; @Override public boolean matches(Issue issue) { return ((DefaultIssue) issue).type() != RuleType.SECURITY_HOTSPOT; } }
1,182
33.794118
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/IsUnResolved.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import org.sonar.api.issue.Issue; public class IsUnResolved implements Condition { @Override public boolean matches(Issue issue) { return issue.resolution() == null; } }
1,067
33.451613
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/IssueWorkflow.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import java.util.List; import org.sonar.api.Startable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.issue.DefaultTransitions; import org.sonar.api.issue.Issue; import org.sonar.api.rules.RuleType; import org.sonar.api.server.ServerSide; import org.sonar.api.web.UserRole; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.IssueChangeContext; import org.sonar.server.issue.IssueFieldsSetter; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static org.sonar.api.issue.Issue.RESOLUTION_ACKNOWLEDGED; import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.issue.Issue.RESOLUTION_REMOVED; import static org.sonar.api.issue.Issue.RESOLUTION_SAFE; import static org.sonar.api.issue.Issue.RESOLUTION_WONT_FIX; import static org.sonar.api.issue.Issue.STATUS_CLOSED; import static org.sonar.api.issue.Issue.STATUS_CONFIRMED; import static org.sonar.api.issue.Issue.STATUS_OPEN; import static org.sonar.api.issue.Issue.STATUS_REOPENED; import static org.sonar.api.issue.Issue.STATUS_RESOLVED; import static org.sonar.api.issue.Issue.STATUS_REVIEWED; import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW; @ServerSide @ComputeEngineSide public class IssueWorkflow implements Startable { private static final String AUTOMATIC_CLOSE_TRANSITION = "automaticclose"; private final FunctionExecutor functionExecutor; private final IssueFieldsSetter updater; private StateMachine machine; public IssueWorkflow(FunctionExecutor functionExecutor, IssueFieldsSetter updater) { this.functionExecutor = functionExecutor; this.updater = updater; } @Override public void start() { StateMachine.Builder builder = StateMachine.builder() .states(STATUS_OPEN, STATUS_CONFIRMED, STATUS_REOPENED, STATUS_RESOLVED, STATUS_CLOSED, STATUS_TO_REVIEW, STATUS_REVIEWED); buildManualTransitions(builder); buildAutomaticTransitions(builder); buildSecurityHotspotTransitions(builder); machine = builder.build(); } private static void buildManualTransitions(StateMachine.Builder builder) { builder // confirm .transition(Transition.builder(DefaultTransitions.CONFIRM) .from(STATUS_OPEN).to(STATUS_CONFIRMED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(null)) .build()) .transition(Transition.builder(DefaultTransitions.CONFIRM) .from(STATUS_REOPENED).to(STATUS_CONFIRMED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(null)) .build()) // resolve as fixed .transition(Transition.builder(DefaultTransitions.RESOLVE) .from(STATUS_OPEN).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_FIXED)) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()) .transition(Transition.builder(DefaultTransitions.RESOLVE) .from(STATUS_REOPENED).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_FIXED)) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()) .transition(Transition.builder(DefaultTransitions.RESOLVE) .from(STATUS_CONFIRMED).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_FIXED)) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()) // reopen .transition(Transition.builder(DefaultTransitions.UNCONFIRM) .from(STATUS_CONFIRMED).to(STATUS_REOPENED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(null)) .build()) .transition(Transition.builder(DefaultTransitions.REOPEN) .from(STATUS_RESOLVED).to(STATUS_REOPENED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(null)) .build()) // resolve as false-positive .transition(Transition.builder(DefaultTransitions.FALSE_POSITIVE) .from(STATUS_OPEN).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_FALSE_POSITIVE), UnsetAssignee.INSTANCE) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()) .transition(Transition.builder(DefaultTransitions.FALSE_POSITIVE) .from(STATUS_REOPENED).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_FALSE_POSITIVE), UnsetAssignee.INSTANCE) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()) .transition(Transition.builder(DefaultTransitions.FALSE_POSITIVE) .from(STATUS_CONFIRMED).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_FALSE_POSITIVE), UnsetAssignee.INSTANCE) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()) // resolve as won't fix .transition(Transition.builder(DefaultTransitions.WONT_FIX) .from(STATUS_OPEN).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_WONT_FIX), UnsetAssignee.INSTANCE) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()) .transition(Transition.builder(DefaultTransitions.WONT_FIX) .from(STATUS_REOPENED).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_WONT_FIX), UnsetAssignee.INSTANCE) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()) .transition(Transition.builder(DefaultTransitions.WONT_FIX) .from(STATUS_CONFIRMED).to(STATUS_RESOLVED) .conditions(IsNotHotspot.INSTANCE) .functions(new SetResolution(RESOLUTION_WONT_FIX), UnsetAssignee.INSTANCE) .requiredProjectPermission(UserRole.ISSUE_ADMIN) .build()); } private static void buildSecurityHotspotTransitions(StateMachine.Builder builder) { // hotspot reviewed as fixed, either from TO_REVIEW or from REVIEWED-SAFE or from REVIEWED-ACKNOWLEDGED Transition.TransitionBuilder reviewedAsFixedBuilder = Transition.builder(DefaultTransitions.RESOLVE_AS_REVIEWED) .to(STATUS_REVIEWED) .conditions(new HasType(RuleType.SECURITY_HOTSPOT)) .functions(new SetResolution(RESOLUTION_FIXED)) .requiredProjectPermission(UserRole.SECURITYHOTSPOT_ADMIN); builder .transition(reviewedAsFixedBuilder .from(STATUS_TO_REVIEW) .conditions(new HasType(RuleType.SECURITY_HOTSPOT)) .build()) .transition(reviewedAsFixedBuilder .from(STATUS_REVIEWED) .conditions(new HasType(RuleType.SECURITY_HOTSPOT), new HasResolution(RESOLUTION_SAFE, RESOLUTION_ACKNOWLEDGED)) .build()); // hotspot reviewed as safe, either from TO_REVIEW or from REVIEWED-FIXED or from REVIEWED-ACKNOWLEDGED Transition.TransitionBuilder resolveAsSafeTransitionBuilder = Transition.builder(DefaultTransitions.RESOLVE_AS_SAFE) .to(STATUS_REVIEWED) .functions(new SetResolution(RESOLUTION_SAFE)) .requiredProjectPermission(UserRole.SECURITYHOTSPOT_ADMIN); builder .transition(resolveAsSafeTransitionBuilder .from(STATUS_TO_REVIEW) .conditions(new HasType(RuleType.SECURITY_HOTSPOT)) .build()) .transition(resolveAsSafeTransitionBuilder .from(STATUS_REVIEWED) .conditions(new HasType(RuleType.SECURITY_HOTSPOT), new HasResolution(RESOLUTION_FIXED, RESOLUTION_ACKNOWLEDGED)) .build()); // hotspot reviewed as acknowledged, either from TO_REVIEW or from REVIEWED-FIXED or from REVIEWED-SAFE Transition.TransitionBuilder resolveAsAcknowledgedTransitionBuilder = Transition.builder(DefaultTransitions.RESOLVE_AS_ACKNOWLEDGED) .to(STATUS_REVIEWED) .functions(new SetResolution(RESOLUTION_ACKNOWLEDGED)) .requiredProjectPermission(UserRole.SECURITYHOTSPOT_ADMIN); builder .transition(resolveAsAcknowledgedTransitionBuilder .from(STATUS_TO_REVIEW) .conditions(new HasType(RuleType.SECURITY_HOTSPOT)) .build()) .transition(resolveAsAcknowledgedTransitionBuilder .from(STATUS_REVIEWED) .conditions(new HasType(RuleType.SECURITY_HOTSPOT), new HasResolution(RESOLUTION_FIXED, RESOLUTION_SAFE)) .build()); // put hotspot back into TO_REVIEW builder .transition(Transition.builder(DefaultTransitions.RESET_AS_TO_REVIEW) .from(STATUS_REVIEWED).to(STATUS_TO_REVIEW) .conditions(new HasType(RuleType.SECURITY_HOTSPOT), new HasResolution(RESOLUTION_FIXED, RESOLUTION_SAFE, RESOLUTION_ACKNOWLEDGED)) .functions(new SetResolution(null)) .requiredProjectPermission(UserRole.SECURITYHOTSPOT_ADMIN) .build()); } private static void buildAutomaticTransitions(StateMachine.Builder builder) { // Close the "end of life" issues (disabled/deleted rule, deleted component) builder .transition(Transition.builder(AUTOMATIC_CLOSE_TRANSITION) .from(STATUS_OPEN).to(STATUS_CLOSED) .conditions(IsBeingClosed.INSTANCE) .functions(SetClosed.INSTANCE, SetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder(AUTOMATIC_CLOSE_TRANSITION) .from(STATUS_REOPENED).to(STATUS_CLOSED) .conditions(IsBeingClosed.INSTANCE) .functions(SetClosed.INSTANCE, SetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder(AUTOMATIC_CLOSE_TRANSITION) .from(STATUS_CONFIRMED).to(STATUS_CLOSED) .conditions(IsBeingClosed.INSTANCE) .functions(SetClosed.INSTANCE, SetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder(AUTOMATIC_CLOSE_TRANSITION) .from(STATUS_RESOLVED).to(STATUS_CLOSED) .conditions(IsBeingClosed.INSTANCE) .functions(SetClosed.INSTANCE, SetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder(AUTOMATIC_CLOSE_TRANSITION) .from(STATUS_TO_REVIEW).to(STATUS_CLOSED) .conditions(IsBeingClosed.INSTANCE, new HasType(RuleType.SECURITY_HOTSPOT)) .functions(SetClosed.INSTANCE, SetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder(AUTOMATIC_CLOSE_TRANSITION) .from(STATUS_REVIEWED).to(STATUS_CLOSED) .conditions(IsBeingClosed.INSTANCE, new HasType(RuleType.SECURITY_HOTSPOT)) .functions(SetClosed.INSTANCE, SetCloseDate.INSTANCE) .automatic() .build()) // Reopen issues that are marked as resolved but that are still alive. .transition(Transition.builder("automaticreopen") .from(STATUS_RESOLVED).to(STATUS_REOPENED) .conditions(new NotCondition(IsBeingClosed.INSTANCE), new HasResolution(RESOLUTION_FIXED), IsNotHotspot.INSTANCE) .functions(new SetResolution(null), UnsetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder("automaticuncloseopen") .from(STATUS_CLOSED).to(STATUS_OPEN) .conditions( new PreviousStatusWas(STATUS_OPEN), new HasResolution(RESOLUTION_REMOVED, RESOLUTION_FIXED), IsNotHotspot.INSTANCE) .functions(RestoreResolutionFunction.INSTANCE, UnsetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder("automaticunclosereopen") .from(STATUS_CLOSED).to(STATUS_REOPENED) .conditions( new PreviousStatusWas(STATUS_REOPENED), new HasResolution(RESOLUTION_REMOVED, RESOLUTION_FIXED), IsNotHotspot.INSTANCE) .functions(RestoreResolutionFunction.INSTANCE, UnsetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder("automaticuncloseconfirmed") .from(STATUS_CLOSED).to(STATUS_CONFIRMED) .conditions( new PreviousStatusWas(STATUS_CONFIRMED), new HasResolution(RESOLUTION_REMOVED, RESOLUTION_FIXED), IsNotHotspot.INSTANCE) .functions(RestoreResolutionFunction.INSTANCE, UnsetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder("automaticuncloseresolved") .from(STATUS_CLOSED).to(STATUS_RESOLVED) .conditions( new PreviousStatusWas(STATUS_RESOLVED), new HasResolution(RESOLUTION_REMOVED, RESOLUTION_FIXED), IsNotHotspot.INSTANCE) .functions(RestoreResolutionFunction.INSTANCE, UnsetCloseDate.INSTANCE) .automatic() .build()) // reopen closed hotspots .transition(Transition.builder("automaticunclosetoreview") .from(STATUS_CLOSED).to(STATUS_TO_REVIEW) .conditions( new PreviousStatusWas(STATUS_TO_REVIEW), new HasResolution(RESOLUTION_REMOVED, RESOLUTION_FIXED), IsHotspot.INSTANCE) .functions(RestoreResolutionFunction.INSTANCE, UnsetCloseDate.INSTANCE) .automatic() .build()) .transition(Transition.builder("automaticunclosereviewed") .from(STATUS_CLOSED).to(STATUS_REVIEWED) .conditions( new PreviousStatusWas(STATUS_REVIEWED), new HasResolution(RESOLUTION_REMOVED, RESOLUTION_FIXED), IsHotspot.INSTANCE) .functions(RestoreResolutionFunction.INSTANCE, UnsetCloseDate.INSTANCE) .automatic() .build()); } @Override public void stop() { // nothing to do } public boolean doManualTransition(DefaultIssue issue, String transitionKey, IssueChangeContext issueChangeContext) { Transition transition = stateOf(issue).transition(transitionKey); if (transition.supports(issue) && !transition.automatic()) { functionExecutor.execute(transition.functions(), issue, issueChangeContext); updater.setStatus(issue, transition.to(), issueChangeContext); return true; } return false; } public List<Transition> outTransitions(Issue issue) { String status = issue.status(); State state = machine.state(status); checkArgument(state != null, "Unknown status: %s", status); return state.outManualTransitions(issue); } public void doAutomaticTransition(DefaultIssue issue, IssueChangeContext issueChangeContext) { Transition transition = stateOf(issue).outAutomaticTransition(issue); if (transition != null) { functionExecutor.execute(transition.functions(), issue, issueChangeContext); updater.setStatus(issue, transition.to(), issueChangeContext); } } public List<String> statusKeys() { return machine.stateKeys(); } private State stateOf(DefaultIssue issue) { String status = issue.status(); State state = machine.state(status); String issueKey = issue.key(); checkState(state != null, "Unknown status: %s [issue=%s]", status, issueKey); return state; } }
16,010
42.508152
138
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/NotCondition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import org.sonar.api.issue.Issue; public class NotCondition implements Condition { private final Condition condition; public NotCondition(Condition condition) { this.condition = condition; } @Override public boolean matches(Issue issue) { return !condition.matches(issue); } }
1,186
31.081081
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/PreviousStatusWas.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import java.util.Comparator; import java.util.Objects; import java.util.Optional; import org.sonar.api.issue.Issue; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs; class PreviousStatusWas implements Condition { private final String expectedPreviousStatus; PreviousStatusWas(String expectedPreviousStatus) { this.expectedPreviousStatus = expectedPreviousStatus; } @Override public boolean matches(Issue issue) { DefaultIssue defaultIssue = (DefaultIssue) issue; Optional<String> lastPreviousStatus = defaultIssue.changes().stream() // exclude current change (if any) .filter(change -> change != defaultIssue.currentChange()) .filter(change -> change.creationDate() != null) .sorted(Comparator.comparing(FieldDiffs::creationDate).reversed()) .map(change -> change.get("status")) .filter(Objects::nonNull) .findFirst() .map(t -> (String) t.oldValue()); return lastPreviousStatus.filter(this.expectedPreviousStatus::equals).isPresent(); } }
1,936
36.25
86
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/RestoreResolutionFunction.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import java.util.Comparator; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.issue.Issue; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs; enum RestoreResolutionFunction implements Function { INSTANCE; @Override public void execute(Context context) { DefaultIssue defaultIssue = (DefaultIssue) context.issue(); String previousResolution = defaultIssue.changes().stream() // exclude current change (if any) .filter(change -> change != defaultIssue.currentChange()) .filter(change -> change.creationDate() != null) .sorted(Comparator.comparing(FieldDiffs::creationDate).reversed()) .map(this::parse) .filter(Objects::nonNull) .filter(StatusAndResolutionDiffs::hasResolution) .findFirst() .map(t -> t.newStatusClosed ? t.oldResolution : t.newResolution) .orElse(null); context.setResolution(previousResolution); } @CheckForNull private StatusAndResolutionDiffs parse(FieldDiffs fieldDiffs) { FieldDiffs.Diff status = fieldDiffs.get("status"); if (status == null) { return null; } FieldDiffs.Diff resolution = fieldDiffs.get("resolution"); if (resolution == null) { return new StatusAndResolutionDiffs(Issue.STATUS_CLOSED.equals(status.newValue()), null, null); } return new StatusAndResolutionDiffs(Issue.STATUS_CLOSED.equals(status.newValue()), (String) resolution.oldValue(), (String) resolution.newValue()); } private static class StatusAndResolutionDiffs { private final boolean newStatusClosed; private final String oldResolution; private final String newResolution; private StatusAndResolutionDiffs(boolean newStatusClosed, @Nullable String oldResolution, @Nullable String newResolution) { this.newStatusClosed = newStatusClosed; this.oldResolution = emptyToNull(oldResolution); this.newResolution = emptyToNull(newResolution); } private static String emptyToNull(@Nullable String str) { if (str == null || str.isEmpty()) { return null; } return str; } boolean hasResolution() { return oldResolution != null || newResolution != null; } } }
3,156
35.287356
151
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/SetCloseDate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; enum SetCloseDate implements Function { INSTANCE; @Override public void execute(Context context) { context.setCloseDate(); } }
1,026
33.233333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/SetClosed.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import org.sonar.api.issue.Issue; import org.sonar.core.issue.DefaultIssue; public enum SetClosed implements Function { INSTANCE; @Override public void execute(Context context) { DefaultIssue issue = (DefaultIssue) context.issue(); if (issue.isOnDisabledRule()) { context.setResolution(Issue.RESOLUTION_REMOVED); } else { context.setResolution(Issue.RESOLUTION_FIXED); } // closed issues are not "tracked" -> the line number does not evolve anymore // when code changes. That's misleading for end-users, so line number // is unset. context.unsetLine(); } }
1,497
33.837209
81
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/SetResolution.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import javax.annotation.Nullable; public class SetResolution implements Function { private final String resolution; public SetResolution(@Nullable String resolution) { this.resolution = resolution; } @Override public void execute(Context context) { context.setResolution(resolution); } }
1,196
32.25
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/SetType.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import javax.annotation.Nullable; import org.sonar.api.rules.RuleType; public class SetType implements Function { private final RuleType type; public SetType(@Nullable RuleType type) { this.type = type; } @Override public void execute(Context context) { context.setType(type); } }
1,189
31.162162
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/State.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import com.google.common.base.Preconditions; import com.google.common.base.Strings; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import org.sonar.api.issue.Issue; public class State { private final String key; private final Transition[] outTransitions; public State(String key, Transition[] outTransitions) { Preconditions.checkArgument(!Strings.isNullOrEmpty(key), "State key must be set"); checkDuplications(outTransitions, key); this.key = key; this.outTransitions = outTransitions; } private static void checkDuplications(Transition[] transitions, String stateKey) { Set<String> keys = new HashSet<>(); Arrays.stream(transitions) .filter(transition -> !keys.add(transition.key())) .findAny() .ifPresent(transition -> { throw new IllegalArgumentException("Transition '" + transition.key() + "' is declared several times from the originating state '" + stateKey + "'"); }); } public List<Transition> outManualTransitions(Issue issue) { return Arrays.stream(outTransitions) .filter(transition -> !transition.automatic()) .filter(transition -> transition.supports(issue)) .toList(); } @CheckForNull public Transition outAutomaticTransition(Issue issue) { List<Transition> transitions = Arrays.stream(outTransitions) .filter(Transition::automatic) .filter(t -> t.supports(issue)) .toList(); if(transitions.size() > 1){ throw new IllegalArgumentException("Several automatic transitions are available for issue: " + issue); } return transitions.size() == 1 ? transitions.get(0) : null; } Transition transition(String transitionKey) { return Arrays.stream(outTransitions) .filter(transition -> transitionKey.equals(transition.key())) .findAny() .orElseThrow(() -> new IllegalArgumentException("Transition from state " + key + " does not exist: " + transitionKey)); } }
2,923
35.098765
125
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/StateMachine.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import com.google.common.base.Preconditions; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ListMultimap; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; public class StateMachine { private final List<String> keys; private final Map<String, State> byKey; private StateMachine(Builder builder) { this.keys = ImmutableList.copyOf(builder.states); ImmutableMap.Builder<String, State> mapBuilder = ImmutableMap.builder(); for (String stateKey : builder.states) { List<Transition> outTransitions = builder.outTransitions.get(stateKey); State state = new State(stateKey, outTransitions.toArray(new Transition[outTransitions.size()])); mapBuilder.put(stateKey, state); } byKey = mapBuilder.build(); } @CheckForNull public State state(String stateKey) { return byKey.get(stateKey); } public List<String> stateKeys() { return keys; } public static Builder builder() { return new Builder(); } public static class Builder { private final Set<String> states = new LinkedHashSet<>(); // transitions per originating state private final ListMultimap<String, Transition> outTransitions = ArrayListMultimap.create(); private Builder() { } public Builder states(String... keys) { states.addAll(Arrays.asList(keys)); return this; } public Builder transition(Transition transition) { Preconditions.checkArgument(states.contains(transition.from()), "Originating state does not exist: " + transition.from()); Preconditions.checkArgument(states.contains(transition.to()), "Destination state does not exist: " + transition.to()); outTransitions.put(transition.from(), transition); return this; } public StateMachine build() { Preconditions.checkArgument(!states.isEmpty(), "At least one state is required"); return new StateMachine(this); } } }
3,032
33.078652
128
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/Transition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; import com.google.common.base.Strings; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; import javax.annotation.CheckForNull; import org.apache.commons.lang.StringUtils; import org.sonar.api.issue.Issue; import static com.google.common.base.Preconditions.checkArgument; public class Transition { private final String key; private final String from; private final String to; private final Condition[] conditions; private final Function[] functions; private final boolean automatic; private String requiredProjectPermission; private Transition(TransitionBuilder builder) { key = builder.key; from = builder.from; to = builder.to; conditions = builder.conditions.toArray(new Condition[builder.conditions.size()]); functions = builder.functions.toArray(new Function[builder.functions.size()]); automatic = builder.automatic; requiredProjectPermission = builder.requiredProjectPermission; } public String key() { return key; } String from() { return from; } String to() { return to; } Condition[] conditions() { return conditions; } Function[] functions() { return functions; } boolean automatic() { return automatic; } public boolean supports(Issue issue) { for (Condition condition : conditions) { if (!condition.matches(issue)) { return false; } } return true; } @CheckForNull public String requiredProjectPermission() { return requiredProjectPermission; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Transition that = (Transition) o; if (!from.equals(that.from)) { return false; } if (!key.equals(that.key)) { return false; } return to.equals(that.to); } @Override public int hashCode() { int result = key.hashCode(); result = 31 * result + from.hashCode(); result = 31 * result + to.hashCode(); return result; } @Override public String toString() { return String.format("%s->%s->%s", from, key, to); } public static Transition create(String key, String from, String to) { return builder(key).from(from).to(to).build(); } public static TransitionBuilder builder(String key) { return new TransitionBuilder(key); } public static class TransitionBuilder { private final String key; private String from; private String to; private List<Condition> conditions = Lists.newArrayList(); private List<Function> functions = Lists.newArrayList(); private boolean automatic = false; private String requiredProjectPermission; private TransitionBuilder(String key) { this.key = key; } public TransitionBuilder from(String from) { this.from = from; return this; } public TransitionBuilder to(String to) { this.to = to; return this; } public TransitionBuilder conditions(Condition... c) { this.conditions.addAll(Arrays.asList(c)); return this; } public TransitionBuilder functions(Function... f) { this.functions.addAll(Arrays.asList(f)); return this; } public TransitionBuilder automatic() { this.automatic = true; return this; } public TransitionBuilder requiredProjectPermission(String requiredProjectPermission) { this.requiredProjectPermission = requiredProjectPermission; return this; } public Transition build() { checkArgument(!Strings.isNullOrEmpty(key), "Transition key must be set"); checkArgument(StringUtils.isAllLowerCase(key), "Transition key must be lower-case"); checkArgument(!Strings.isNullOrEmpty(from), "Originating status must be set"); checkArgument(!Strings.isNullOrEmpty(to), "Destination status must be set"); return new Transition(this); } } }
4,859
26
90
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/UnsetAssignee.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; enum UnsetAssignee implements Function { INSTANCE; @Override public void execute(Context context) { context.setAssignee(null); } }
1,029
33.333333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/UnsetCloseDate.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.issue.workflow; enum UnsetCloseDate implements Function { INSTANCE; @Override public void execute(Context context) { context.unsetCloseDate(); } }
1,030
33.366667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/issue/workflow/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.issue.workflow; import javax.annotation.ParametersAreNonnullByDefault;
972
37.92
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/l18n/ServerI18n.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.l18n; import com.google.common.annotations.VisibleForTesting; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.System2; import org.sonar.core.i18n.DefaultI18n; import org.sonar.core.platform.PluginRepository; import org.sonar.core.extension.CoreExtension; import org.sonar.core.extension.CoreExtensionRepository; /** * Subclass of {@link DefaultI18n} which supports Core Extensions. */ @ServerSide @ComputeEngineSide public class ServerI18n extends DefaultI18n { private final CoreExtensionRepository coreExtensionRepository; public ServerI18n(PluginRepository pluginRepository, System2 system2, CoreExtensionRepository coreExtensionRepository) { super(pluginRepository, system2); this.coreExtensionRepository = coreExtensionRepository; } @Override protected void initialize() { super.initialize(); coreExtensionRepository.loadedCoreExtensions() .map(CoreExtension::getName) .forEach(this::initPlugin); } @VisibleForTesting @Override protected void doStart(ClassLoader classloader) { super.doStart(classloader); } }
2,005
33
122
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/l18n/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.l18n; import javax.annotation.ParametersAreNonnullByDefault;
962
37.52
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/log/ServerLogging.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.log; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import com.google.common.annotations.VisibleForTesting; import java.io.File; import javax.inject.Inject; import org.sonar.api.Startable; import org.slf4j.LoggerFactory; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.Configuration; import org.sonar.api.server.ServerSide; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.api.utils.log.Loggers; import org.sonar.db.Database; import org.sonar.process.logging.LogbackHelper; import static org.sonar.api.utils.log.LoggerLevel.TRACE; import static org.sonar.process.ProcessProperties.Property.PATH_LOGS; @ServerSide @ComputeEngineSide public class ServerLogging implements Startable { /** Used for Hazelcast's distributed queries in cluster mode */ private static ServerLogging instance; private final LogbackHelper helper; private final Configuration config; private final ServerProcessLogging serverProcessLogging; private final Database database; @Inject public ServerLogging(Configuration config, ServerProcessLogging serverProcessLogging, Database database) { this(new LogbackHelper(), config, serverProcessLogging, database); } @VisibleForTesting ServerLogging(LogbackHelper helper, Configuration config, ServerProcessLogging serverProcessLogging, Database database) { this.helper = helper; this.config = config; this.serverProcessLogging = serverProcessLogging; this.database = database; } @Override public void start() { instance = this; } @Override public void stop() { instance = null; } public static void changeLevelFromHazelcastDistributedQuery(LoggerLevel level) { instance.changeLevel(level); } public void changeLevel(LoggerLevel level) { Level logbackLevel = Level.toLevel(level.name()); database.enableSqlLogging(level == TRACE); helper.changeRoot(serverProcessLogging.getLogLevelConfig(), logbackLevel); LoggerFactory.getLogger(ServerLogging.class).info("Level of logs changed to {}", level); } public LoggerLevel getRootLoggerLevel() { return Loggers.get(Logger.ROOT_LOGGER_NAME).getLevel(); } /** * The directory that contains log files. May not exist. */ public File getLogsDir() { return new File(config.get(PATH_LOGS.getKey()).get()); } }
3,220
32.206186
123
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/log/ServerProcessLogging.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.log; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import ch.qos.logback.classic.LoggerContext; import ch.qos.logback.classic.spi.ILoggingEvent; import ch.qos.logback.core.ConsoleAppender; import ch.qos.logback.core.encoder.Encoder; import com.google.common.collect.ImmutableSet; import java.util.Set; import javax.annotation.CheckForNull; import org.sonar.process.ProcessId; import org.sonar.process.Props; import org.sonar.process.logging.LogLevelConfig; import org.sonar.process.logging.LogbackHelper; import org.sonar.process.logging.RootLoggerConfig; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.logging.RootLoggerConfig.newRootLoggerConfigBuilder; public abstract class ServerProcessLogging { public static final String STARTUP_LOGGER_NAME = "startup"; protected static final Set<String> JMX_RMI_LOGGER_NAMES = ImmutableSet.of( "javax.management.remote.timeout", "javax.management.remote.misc", "javax.management.remote.rmi", "javax.management.mbeanserver", "sun.rmi.loader", "sun.rmi.transport.tcp", "sun.rmi.transport.misc", "sun.rmi.server.call", "sun.rmi.dgc"); protected static final Set<String> LOGGER_NAMES_TO_TURN_OFF = ImmutableSet.of( // mssql driver "com.microsoft.sqlserver.jdbc.internals", "com.microsoft.sqlserver.jdbc.ResultSet", "com.microsoft.sqlserver.jdbc.Statement", "com.microsoft.sqlserver.jdbc.Connection"); private final ProcessId processId; private final String threadIdFieldPattern; private final LogbackHelper helper = new LogbackHelper(); private final LogLevelConfig logLevelConfig; protected ServerProcessLogging(ProcessId processId, String threadIdFieldPattern) { this.processId = processId; this.threadIdFieldPattern = threadIdFieldPattern; this.logLevelConfig = createLogLevelConfiguration(processId); } private LogLevelConfig createLogLevelConfiguration(ProcessId processId) { LogLevelConfig.Builder builder = LogLevelConfig.newBuilder(helper.getRootLoggerName()); builder.rootLevelFor(processId); builder.immutableLevel("org.apache.ibatis", Level.WARN); builder.immutableLevel("java.sql", Level.WARN); builder.immutableLevel("java.sql.ResultSet", Level.WARN); builder.immutableLevel("org.elasticsearch", Level.INFO); builder.immutableLevel("org.elasticsearch.node", Level.INFO); builder.immutableLevel("org.elasticsearch.http", Level.INFO); builder.immutableLevel("ch.qos.logback", Level.WARN); builder.immutableLevel("org.apache.catalina", Level.INFO); builder.immutableLevel("org.apache.coyote", Level.INFO); builder.immutableLevel("org.apache.jasper", Level.INFO); builder.immutableLevel("org.apache.tomcat", Level.INFO); builder.immutableLevel("org.postgresql.core.v3.QueryExecutorImpl", Level.INFO); builder.immutableLevel("org.postgresql.jdbc.PgConnection", Level.INFO); // Apache FOP builder.immutableLevel("org.apache.fop", Level.INFO); builder.immutableLevel("org.apache.fop.apps.FOUserAgent", Level.WARN); builder.immutableLevel("org.apache.xmlgraphics.image.loader.spi.ImageImplRegistry", Level.INFO); // Hazelcast builder.immutableLevel("com.hazelcast.internal.cluster.impl.ClusterHeartbeatManager", Level.INFO); builder.immutableLevel("com.hazelcast.internal.cluster.impl.operations.HeartbeatOperation", Level.INFO); builder.immutableLevel("com.hazelcast.internal.partition.InternalPartitionService", Level.INFO); builder.immutableLevel("com.hazelcast.internal.partition.operation.PartitionStateOperation", Level.INFO); builder.immutableLevel("com.hazelcast.replicatedmap.impl.operation.RequestMapDataOperation", Level.INFO); builder.immutableLevel("com.hazelcast.replicatedmap.impl.operation.SyncReplicatedMapDataOperation", Level.INFO); // Netty (used by Elasticsearch) builder.immutableLevel("io.netty.buffer.PoolThreadCache", Level.INFO); extendLogLevelConfiguration(builder); return builder.build(); } public LoggerContext configure(Props props) { LoggerContext ctx = helper.getRootContext(); ctx.reset(); configureRootLogger(props); helper.apply(logLevelConfig, props); configureDirectToConsoleLoggers(props, ctx, STARTUP_LOGGER_NAME); extendConfigure(); helper.enableJulChangePropagation(ctx); return ctx; } public LogLevelConfig getLogLevelConfig() { return this.logLevelConfig; } protected abstract void extendLogLevelConfiguration(LogLevelConfig.Builder logLevelConfigBuilder); protected abstract void extendConfigure(); private void configureRootLogger(Props props) { RootLoggerConfig config = newRootLoggerConfigBuilder() .setProcessId(processId) .setNodeNameField(getNodeNameWhenCluster(props)) .setThreadIdFieldPattern(threadIdFieldPattern) .build(); Encoder<ILoggingEvent> encoder = helper.createEncoder(props, config, helper.getRootContext()); helper.configureGlobalFileLog(props, config, encoder); helper.configureForSubprocessGobbler(props, encoder); } @CheckForNull private static String getNodeNameWhenCluster(Props props) { boolean clusterEnabled = props.valueAsBoolean(CLUSTER_ENABLED.getKey(), Boolean.parseBoolean(CLUSTER_ENABLED.getDefaultValue())); return clusterEnabled ? props.value(CLUSTER_NODE_NAME.getKey(), CLUSTER_NODE_NAME.getDefaultValue()) : null; } /** * Setup one or more specified loggers to be non additive and to print to System.out which will be caught by the Main * Process and written to sonar.log. */ private void configureDirectToConsoleLoggers(Props props, LoggerContext context, String... loggerNames) { RootLoggerConfig config = newRootLoggerConfigBuilder() .setNodeNameField(getNodeNameWhenCluster(props)) .setProcessId(ProcessId.APP) .setThreadIdFieldPattern("") .build(); Encoder<ILoggingEvent> encoder = helper.createEncoder(props, config, context); ConsoleAppender<ILoggingEvent> consoleAppender = helper.newConsoleAppender(context, "CONSOLE", encoder); for (String loggerName : loggerNames) { Logger consoleLogger = context.getLogger(loggerName); consoleLogger.setAdditive(false); consoleLogger.addAppender(consoleAppender); } } }
7,298
42.446429
119
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/log/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.log; import javax.annotation.ParametersAreNonnullByDefault;
961
37.48
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/loginmessage/LoginMessageFeature.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.loginmessage; import org.sonar.api.SonarRuntime; import org.sonar.api.server.ServerSide; import org.sonar.server.feature.SonarQubeFeature; import static org.sonar.api.SonarEdition.DATACENTER; import static org.sonar.api.SonarEdition.ENTERPRISE; @ServerSide public class LoginMessageFeature implements SonarQubeFeature { private final SonarRuntime sonarRuntime; public LoginMessageFeature(SonarRuntime sonarRuntime) { this.sonarRuntime = sonarRuntime; } @Override public String getName() { return "login-message"; } @Override public boolean isAvailable() { return sonarRuntime.getEdition() == ENTERPRISE || sonarRuntime.getEdition() == DATACENTER; } }
1,557
30.795918
94
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/loginmessage/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. */ package org.sonar.server.loginmessage;
882
41.047619
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/management/DelegatingManagedInstanceService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.management; import com.google.common.collect.MoreCollectors; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.annotation.Priority; import org.sonar.api.server.ServerSide; import org.sonar.db.DbSession; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import static java.util.stream.Collectors.toSet; import static org.sonar.api.utils.Preconditions.checkState; @ServerSide @Priority(ManagedInstanceService.DELEGATING_INSTANCE_PRIORITY) public class DelegatingManagedInstanceService implements ManagedInstanceService { private static final IllegalStateException NOT_MANAGED_INSTANCE_EXCEPTION = new IllegalStateException("This instance is not managed."); private final Set<ManagedInstanceService> delegates; public DelegatingManagedInstanceService(Set<ManagedInstanceService> delegates) { this.delegates = delegates; } public final boolean isInstanceExternallyManaged() { return delegates.stream().anyMatch(ManagedInstanceService::isInstanceExternallyManaged); } @Override public String getProviderName() { return findManagedInstanceService() .map(ManagedInstanceService::getProviderName) .orElseThrow(() -> NOT_MANAGED_INSTANCE_EXCEPTION); } @Override public Map<String, Boolean> getUserUuidToManaged(DbSession dbSession, Set<String> userUuids) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.getUserUuidToManaged(dbSession, userUuids)) .orElse(returnNonManagedForAllGroups(userUuids)); } @Override public Map<String, Boolean> getGroupUuidToManaged(DbSession dbSession, Set<String> groupUuids) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.getGroupUuidToManaged(dbSession, groupUuids)) .orElse(returnNonManagedForAllGroups(groupUuids)); } @Override public String getManagedUsersSqlFilter(boolean filterByManaged) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.getManagedUsersSqlFilter(filterByManaged)) .orElseThrow(() -> NOT_MANAGED_INSTANCE_EXCEPTION); } @Override public String getManagedGroupsSqlFilter(boolean filterByManaged) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.getManagedGroupsSqlFilter(filterByManaged)) .orElseThrow(() -> NOT_MANAGED_INSTANCE_EXCEPTION); } @Override public boolean isUserManaged(DbSession dbSession, String login) { return findManagedInstanceService() .map(managedInstanceService -> managedInstanceService.isUserManaged(dbSession, login)) .orElse(false); } private Optional<ManagedInstanceService> findManagedInstanceService() { Set<ManagedInstanceService> managedInstanceServices = delegates.stream() .filter(ManagedInstanceService::isInstanceExternallyManaged) .collect(toSet()); checkState(managedInstanceServices.size() < 2, "The instance can't be managed by more than one identity provider and %s were found.", managedInstanceServices.size()); return managedInstanceServices.stream().collect(MoreCollectors.toOptional()); } private static Map<String, Boolean> returnNonManagedForAllGroups(Set<String> resourcesUuid) { return resourcesUuid.stream().collect(toMap(identity(), any -> false)); } }
4,279
39.377358
137
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/management/ManagedInstanceService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.management; import java.util.Map; import java.util.Set; import org.sonar.db.DbSession; public interface ManagedInstanceService { int DELEGATING_INSTANCE_PRIORITY = 1; boolean isInstanceExternallyManaged(); String getProviderName(); Map<String, Boolean> getUserUuidToManaged(DbSession dbSession, Set<String> userUuids); Map<String, Boolean> getGroupUuidToManaged(DbSession dbSession, Set<String> groupUuids); String getManagedUsersSqlFilter(boolean filterByManaged); String getManagedGroupsSqlFilter(boolean filterByManaged); boolean isUserManaged(DbSession dbSession, String login); }
1,479
32.636364
90
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/management/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.management; import javax.annotation.ParametersAreNonnullByDefault;
968
37.76
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/measure/DebtRatingGrid.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure; import com.google.common.annotations.VisibleForTesting; import java.util.Arrays; import java.util.EnumMap; import java.util.Map; import org.sonar.api.config.Configuration; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static org.sonar.api.CoreProperties.RATING_GRID; import static org.sonar.api.CoreProperties.RATING_GRID_DEF_VALUES; import static org.sonar.server.measure.Rating.A; import static org.sonar.server.measure.Rating.B; import static org.sonar.server.measure.Rating.C; import static org.sonar.server.measure.Rating.D; import static org.sonar.server.measure.Rating.E; public class DebtRatingGrid { private final double[] gridValues; private final EnumMap<Rating, Bounds> ratingBounds; public DebtRatingGrid(Configuration config) { try { String[] grades = config.getStringArray(RATING_GRID); gridValues = new double[4]; for (int i = 0; i < 4; i++) { gridValues[i] = Double.parseDouble(grades[i]); } this.ratingBounds = buildRatingBounds(gridValues); } catch (Exception e) { throw new IllegalArgumentException("The rating grid is incorrect. Expected something similar to '" + RATING_GRID_DEF_VALUES + "' and got '" + config.get(RATING_GRID).orElse("") + "'", e); } } public DebtRatingGrid(double[] gridValues) { this.gridValues = Arrays.copyOf(gridValues, gridValues.length); this.ratingBounds = buildRatingBounds(gridValues); } private static EnumMap<Rating, Bounds> buildRatingBounds(double[] gridValues) { checkState(gridValues.length == 4, "Rating grid should contains 4 values"); EnumMap<Rating, Bounds> ratingBounds = new EnumMap<>(Rating.class); ratingBounds.put(A, new Bounds(0D, gridValues[0])); ratingBounds.put(B, new Bounds(gridValues[0], gridValues[1])); ratingBounds.put(C, new Bounds(gridValues[1], gridValues[2])); ratingBounds.put(D, new Bounds(gridValues[2], gridValues[3])); ratingBounds.put(E, new Bounds(gridValues[3], Double.MAX_VALUE)); return ratingBounds; } public Rating getRatingForDensity(double value) { return ratingBounds.entrySet().stream() .filter(e -> e.getValue().match(value)) .map(Map.Entry::getKey) .findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Invalid value '%s'", value))); } public double getGradeLowerBound(Rating rating) { if (rating.getIndex() > 1) { return gridValues[rating.getIndex() - 2]; } return 0; } @VisibleForTesting public double[] getGridValues() { return gridValues; } private static class Bounds { private final double lowerBound; private final double higherBound; private final boolean isLowerBoundInclusive; private Bounds(double lowerBound, double higherBound) { this.lowerBound = lowerBound; this.higherBound = higherBound; this.isLowerBoundInclusive = Double.compare(lowerBound, 0D) == 0; } boolean match(double value) { boolean lowerBoundMatch = isLowerBoundInclusive ? (value >= lowerBound) : (value > lowerBound); return lowerBoundMatch && value <= higherBound; } } }
4,065
35.630631
104
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/measure/Rating.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure; import com.google.common.collect.ImmutableMap; import java.util.Map; import static java.lang.String.format; import static java.util.Arrays.stream; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.rule.Severity.CRITICAL; import static org.sonar.api.rule.Severity.INFO; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.api.rule.Severity.MINOR; public enum Rating { E(5), D(4), C(3), B(2), A(1); private final int index; Rating(int index) { this.index = index; } public int getIndex() { return index; } public static Rating valueOf(int index) { return stream(Rating.values()) .filter(r -> r.getIndex() == index) .findFirst() .orElseThrow(() -> new IllegalArgumentException(format("Unknown value '%s'", index))); } public static final Map<String, Rating> RATING_BY_SEVERITY = ImmutableMap.of( BLOCKER, E, CRITICAL, D, MAJOR, C, MINOR, B, INFO, A); public static Rating ratingFromValue(String value) { return valueOf(Integer.parseInt(value)); } }
1,967
27.521739
92
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/measure/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.measure; import javax.annotation.ParametersAreNonnullByDefault;
965
37.64
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/measure/index/ProjectMeasuresDoc.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.index; import com.google.common.collect.ImmutableMap; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.server.es.BaseDoc; import org.sonar.server.permission.index.AuthorizationDoc; import static org.sonar.api.measures.Metric.Level.ERROR; import static org.sonar.api.measures.Metric.Level.OK; import static org.sonar.api.measures.Metric.Level.WARN; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_ANALYSED_AT; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_KEY; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_LANGUAGES; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_MEASURES; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_NAME; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_NCLOC_DISTRIBUTION; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_QUALIFIER; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_QUALITY_GATE_STATUS; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_TAGS; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.FIELD_UUID; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.SUB_FIELD_DISTRIB_LANGUAGE; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.SUB_FIELD_DISTRIB_NCLOC; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.SUB_FIELD_MEASURES_KEY; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.SUB_FIELD_MEASURES_VALUE; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.TYPE_PROJECT_MEASURES; public class ProjectMeasuresDoc extends BaseDoc { public static final Map<String, Integer> QUALITY_GATE_STATUS = ImmutableMap.of(OK.name(), 1, WARN.name(), 2, ERROR.name(), 3); public ProjectMeasuresDoc() { super(TYPE_PROJECT_MEASURES, new HashMap<>(8)); } @Override public String getId() { return getField(FIELD_UUID); } public ProjectMeasuresDoc setId(String s) { setField(FIELD_UUID, s); setParent(AuthorizationDoc.idOf(s)); return this; } public String getKey() { return getField(FIELD_KEY); } public ProjectMeasuresDoc setKey(String s) { setField(FIELD_KEY, s); return this; } public String getName() { return getField(FIELD_NAME); } public ProjectMeasuresDoc setName(String s) { setField(FIELD_NAME, s); return this; } public String getQualifier() { return getField(FIELD_QUALIFIER); } public ProjectMeasuresDoc setQualifier(String s) { setField(FIELD_QUALIFIER, s); return this; } @CheckForNull public Date getAnalysedAt() { return getNullableField(FIELD_ANALYSED_AT); } public ProjectMeasuresDoc setAnalysedAt(@Nullable Date d) { setField(FIELD_ANALYSED_AT, d); return this; } public Collection<Map<String, Object>> getMeasures() { return getField(FIELD_MEASURES); } public ProjectMeasuresDoc setMeasures(Collection<Map<String, Object>> measures) { setField(FIELD_MEASURES, measures); return this; } public ProjectMeasuresDoc setMeasuresFromMap(Map<String, Double> measures) { setMeasures( measures.entrySet().stream() .map(entry -> Map.<String, Object>of( SUB_FIELD_MEASURES_KEY, entry.getKey(), SUB_FIELD_MEASURES_VALUE, entry.getValue())) .toList()); return this; } public ProjectMeasuresDoc setLanguages(List<String> languages) { setField(FIELD_LANGUAGES, languages); return this; } public Collection<Map<String, Object>> getNclocLanguageDistribution() { return getField(FIELD_NCLOC_DISTRIBUTION); } public ProjectMeasuresDoc setNclocLanguageDistribution(Collection<Map<String, Object>> distribution) { setField(FIELD_NCLOC_DISTRIBUTION, distribution); return this; } public ProjectMeasuresDoc setNclocLanguageDistributionFromMap(Map<String, Integer> distribution) { setNclocLanguageDistribution( distribution.entrySet().stream() .map(entry -> Map.<String, Object>of( SUB_FIELD_DISTRIB_LANGUAGE, entry.getKey(), SUB_FIELD_DISTRIB_NCLOC, entry.getValue())) .toList()); return this; } public ProjectMeasuresDoc setQualityGateStatus(@Nullable String s) { setField(FIELD_QUALITY_GATE_STATUS, s != null ? QUALITY_GATE_STATUS.get(s) : null); return this; } public ProjectMeasuresDoc setTags(List<String> tags) { setField(FIELD_TAGS, tags); return this; } }
5,712
34.265432
128
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndexDefinition.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.index; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.server.es.Index; import org.sonar.server.es.IndexDefinition; import org.sonar.server.es.IndexType; import org.sonar.server.es.IndexType.IndexRelationType; import org.sonar.server.es.newindex.NewAuthorizedIndex; import org.sonar.server.es.newindex.TypeMapping; import org.sonar.server.permission.index.IndexAuthorizationConstants; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SEARCH_GRAMS_ANALYZER; import static org.sonar.server.es.newindex.DefaultIndexSettingsElement.SORTABLE_ANALYZER; import static org.sonar.server.es.newindex.SettingsConfiguration.MANUAL_REFRESH_INTERVAL; import static org.sonar.server.es.newindex.SettingsConfiguration.newBuilder; import javax.inject.Inject; public class ProjectMeasuresIndexDefinition implements IndexDefinition { public static final Index DESCRIPTOR = Index.withRelations("projectmeasures"); public static final IndexType.IndexMainType TYPE_AUTHORIZATION = IndexType.main(DESCRIPTOR, IndexAuthorizationConstants.TYPE_AUTHORIZATION); public static final IndexRelationType TYPE_PROJECT_MEASURES = IndexType.relation(TYPE_AUTHORIZATION, "projectmeasure"); public static final String FIELD_UUID = "uuid"; /** * Project key. Only projects and applications (qualifier=TRK, APP) */ public static final String FIELD_KEY = "key"; public static final String FIELD_NAME = "name"; public static final String FIELD_QUALIFIER = "qualifier"; public static final String FIELD_ANALYSED_AT = "analysedAt"; public static final String FIELD_QUALITY_GATE_STATUS = "qualityGateStatus"; public static final String FIELD_TAGS = "tags"; public static final String FIELD_MEASURES = "measures"; public static final String SUB_FIELD_MEASURES_KEY = "key"; public static final String SUB_FIELD_MEASURES_VALUE = "value"; public static final String FIELD_MEASURES_MEASURE_KEY = FIELD_MEASURES + "." + SUB_FIELD_MEASURES_KEY; public static final String FIELD_MEASURES_MEASURE_VALUE = FIELD_MEASURES + "." + SUB_FIELD_MEASURES_VALUE; public static final String FIELD_LANGUAGES = "languages"; public static final String FIELD_NCLOC_DISTRIBUTION = "nclocLanguageDistribution"; public static final String SUB_FIELD_DISTRIB_LANGUAGE = "language"; public static final String SUB_FIELD_DISTRIB_NCLOC = "ncloc"; public static final String FIELD_NCLOC_DISTRIBUTION_LANGUAGE = FIELD_NCLOC_DISTRIBUTION + "." + SUB_FIELD_DISTRIB_LANGUAGE; public static final String FIELD_NCLOC_DISTRIBUTION_NCLOC = FIELD_NCLOC_DISTRIBUTION + "." + SUB_FIELD_DISTRIB_NCLOC; private final Configuration config; private final boolean enableSource; private ProjectMeasuresIndexDefinition(Configuration config, boolean enableSource) { this.config = config; this.enableSource = enableSource; } @Inject public ProjectMeasuresIndexDefinition(Configuration config) { this(config, false); } /** * Keep the document sources in index so that indexer tests can verify content * of indexed documents. */ public static ProjectMeasuresIndexDefinition createForTest() { return new ProjectMeasuresIndexDefinition(new MapSettings().asConfig(), true); } @Override public void define(IndexDefinitionContext context) { NewAuthorizedIndex index = context.createWithAuthorization( DESCRIPTOR, newBuilder(config) .setRefreshInterval(MANUAL_REFRESH_INTERVAL) .setDefaultNbOfShards(5) .build()) .setEnableSource(enableSource); TypeMapping mapping = index.createTypeMapping(TYPE_PROJECT_MEASURES); mapping.keywordFieldBuilder(FIELD_UUID).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_KEY).disableNorms().addSubFields(SORTABLE_ANALYZER).build(); mapping.keywordFieldBuilder(FIELD_QUALIFIER).disableNorms().build(); mapping.keywordFieldBuilder(FIELD_NAME).addSubFields(SORTABLE_ANALYZER, SEARCH_GRAMS_ANALYZER).build(); mapping.keywordFieldBuilder(FIELD_QUALITY_GATE_STATUS).build(); mapping.keywordFieldBuilder(FIELD_TAGS).build(); mapping.keywordFieldBuilder(FIELD_LANGUAGES).build(); mapping.nestedFieldBuilder(FIELD_MEASURES) .addKeywordField(SUB_FIELD_MEASURES_KEY) .addDoubleField(SUB_FIELD_MEASURES_VALUE) .build(); mapping.nestedFieldBuilder(FIELD_NCLOC_DISTRIBUTION) .addKeywordField(SUB_FIELD_DISTRIB_LANGUAGE) .addIntegerField(SUB_FIELD_DISTRIB_NCLOC) .build(); mapping.createDateTimeField(FIELD_ANALYSED_AT); } }
5,449
45.186441
142
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/measure/index/ProjectMeasuresIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.measure.index; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.sonar.api.resources.Qualifiers; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.BranchDto; import org.sonar.db.es.EsQueueDto; import org.sonar.db.measure.ProjectMeasuresIndexerIterator; import org.sonar.db.measure.ProjectMeasuresIndexerIterator.ProjectMeasures; import org.sonar.server.es.AnalysisIndexer; import org.sonar.server.es.BulkIndexer; import org.sonar.server.es.BulkIndexer.Size; import org.sonar.server.es.EsClient; import org.sonar.server.es.EventIndexer; import org.sonar.server.es.IndexType; import org.sonar.server.es.Indexers; import org.sonar.server.es.IndexingListener; import org.sonar.server.es.IndexingResult; import org.sonar.server.es.OneToOneResilientIndexingListener; import org.sonar.server.permission.index.AuthorizationDoc; import org.sonar.server.permission.index.AuthorizationScope; import org.sonar.server.permission.index.NeedAuthorizationIndexer; import static org.sonar.server.measure.index.ProjectMeasuresIndexDefinition.TYPE_PROJECT_MEASURES; /** * Indexes data related to projects and applications. * The name is a bit misleading - it indexes a lot more data than just measures. * We index by project/app UUID, but we get a lot of the data from their main branches. */ public class ProjectMeasuresIndexer implements EventIndexer, AnalysisIndexer, NeedAuthorizationIndexer { private static final AuthorizationScope AUTHORIZATION_SCOPE = new AuthorizationScope(TYPE_PROJECT_MEASURES, entity -> Qualifiers.PROJECT.equals(entity.getQualifier()) || Qualifiers.APP.equals(entity.getQualifier())); private static final Set<IndexType> INDEX_TYPES = Set.of(TYPE_PROJECT_MEASURES); private final DbClient dbClient; private final EsClient esClient; public ProjectMeasuresIndexer(DbClient dbClient, EsClient esClient) { this.dbClient = dbClient; this.esClient = esClient; } @Override public Set<IndexType> getIndexTypes() { return INDEX_TYPES; } @Override public void indexOnStartup(Set<IndexType> uninitializedIndexTypes) { doIndex(Size.LARGE, null); } public void indexAll() { doIndex(Size.REGULAR, null); } @Override public AuthorizationScope getAuthorizationScope() { return AUTHORIZATION_SCOPE; } @Override public void indexOnAnalysis(String branchUuid) { indexOnAnalysis(branchUuid, Set.of()); } @Override public void indexOnAnalysis(String branchUuid, Set<String> unchangedComponentUuids) { doIndex(Size.REGULAR, branchUuid); } @Override public Collection<EsQueueDto> prepareForRecoveryOnEntityEvent(DbSession dbSession, Collection<String> entityUuids, Indexers.EntityEvent cause) { return switch (cause) { case PERMISSION_CHANGE -> // nothing to do, permissions are not used in index type projectmeasures/projectmeasure Collections.emptyList(); case PROJECT_KEY_UPDATE, CREATION, PROJECT_TAGS_UPDATE, DELETION -> // when CREATION provisioned projects are supported by WS api/components/search_projects prepareForRecovery(dbSession, entityUuids); }; } @Override public Collection<EsQueueDto> prepareForRecoveryOnBranchEvent(DbSession dbSession, Collection<String> branchUuids, Indexers.BranchEvent cause) { return switch (cause) { case DELETION -> Collections.emptyList(); case MEASURE_CHANGE -> { // when MEASURE_CHANGE or PROJECT_KEY_UPDATE project must be re-indexed because key is used in this index Set<String> entityUuids = dbClient.branchDao().selectByUuids(dbSession, branchUuids) .stream().map(BranchDto::getProjectUuid) .collect(Collectors.toSet()); yield prepareForRecovery(dbSession, entityUuids); } }; } private Collection<EsQueueDto> prepareForRecovery(DbSession dbSession, Collection<String> entityUuids) { List<EsQueueDto> items = entityUuids.stream() .map(entityUuid -> EsQueueDto.create(TYPE_PROJECT_MEASURES.format(), entityUuid, null, entityUuid)) .toList(); return dbClient.esQueueDao().insert(dbSession, items); } public IndexingResult commitAndIndex(DbSession dbSession, Collection<String> projectUuids) { List<EsQueueDto> items = projectUuids.stream() .map(projectUuid -> EsQueueDto.create(TYPE_PROJECT_MEASURES.format(), projectUuid, null, projectUuid)) .toList(); dbClient.esQueueDao().insert(dbSession, items); dbSession.commit(); return index(dbSession, items); } @Override public IndexingResult index(DbSession dbSession, Collection<EsQueueDto> items) { if (items.isEmpty()) { return new IndexingResult(); } OneToOneResilientIndexingListener listener = new OneToOneResilientIndexingListener(dbClient, dbSession, items); BulkIndexer bulkIndexer = createBulkIndexer(Size.REGULAR, listener); bulkIndexer.start(); List<String> projectUuids = items.stream().map(EsQueueDto::getDocId).toList(); List<String> projectToDelete = new ArrayList<>(projectUuids); for (String projectUuid : projectUuids) { try (ProjectMeasuresIndexerIterator rowIt = ProjectMeasuresIndexerIterator.create(dbSession, projectUuid)) { while (rowIt.hasNext()) { bulkIndexer.add(toProjectMeasuresDoc(rowIt.next()).toIndexRequest()); projectToDelete.remove(projectUuid); } } } // the remaining uuids reference projects that don't exist in db. They must be deleted from index. projectToDelete.forEach(projectUuid -> bulkIndexer.addDeletion(TYPE_PROJECT_MEASURES, projectUuid, AuthorizationDoc.idOf(projectUuid))); return bulkIndexer.stop(); } private void doIndex(Size size, @Nullable String branchUuid) { try (DbSession dbSession = dbClient.openSession(false)) { String projectUuid = null; if (branchUuid != null) { Optional<BranchDto> branchDto = dbClient.branchDao().selectByUuid(dbSession, branchUuid); if (branchDto.isEmpty() || !branchDto.get().isMain()) { return; } else { projectUuid = branchDto.get().getProjectUuid(); } } try (ProjectMeasuresIndexerIterator rowIt = ProjectMeasuresIndexerIterator.create(dbSession, projectUuid)) { BulkIndexer bulkIndexer = createBulkIndexer(size, IndexingListener.FAIL_ON_ERROR); bulkIndexer.start(); while (rowIt.hasNext()) { ProjectMeasures doc = rowIt.next(); bulkIndexer.add(toProjectMeasuresDoc(doc).toIndexRequest()); } bulkIndexer.stop(); } } } private BulkIndexer createBulkIndexer(Size bulkSize, IndexingListener listener) { return new BulkIndexer(esClient, TYPE_PROJECT_MEASURES, bulkSize, listener); } private static ProjectMeasuresDoc toProjectMeasuresDoc(ProjectMeasures projectMeasures) { ProjectMeasuresIndexerIterator.Project project = projectMeasures.getProject(); Long analysisDate = project.getAnalysisDate(); return new ProjectMeasuresDoc() .setId(project.getUuid()) .setKey(project.getKey()) .setName(project.getName()) .setQualifier(project.getQualifier()) .setQualityGateStatus(projectMeasures.getMeasures().getQualityGateStatus()) .setTags(project.getTags()) .setAnalysedAt(analysisDate == null ? null : new Date(analysisDate)) .setMeasuresFromMap(projectMeasures.getMeasures().getNumericMeasures()) .setLanguages(new ArrayList<>(projectMeasures.getMeasures().getNclocByLanguages().keySet())) .setNclocLanguageDistributionFromMap(projectMeasures.getMeasures().getNclocByLanguages()); } }
8,720
39.004587
146
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/measure/index/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.measure.index; import javax.annotation.ParametersAreNonnullByDefault;
970
39.458333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/metric/MetricFinder.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric; import java.io.Serializable; import java.util.Collection; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import javax.annotation.Nonnull; import org.sonar.api.measures.Metric; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.metric.MetricDto; public class MetricFinder { private final DbClient dbClient; public MetricFinder(DbClient dbClient) { this.dbClient = dbClient; } public Metric findByUuid(String uuid) { try (DbSession session = dbClient.openSession(false)) { MetricDto dto = dbClient.metricDao().selectByUuid(session, uuid); if (dto != null && dto.isEnabled()) { return ToMetric.INSTANCE.apply(dto); } return null; } } public Metric findByKey(String key) { try (DbSession session = dbClient.openSession(false)) { MetricDto dto = dbClient.metricDao().selectByKey(session, key); if (dto != null && dto.isEnabled()) { return ToMetric.INSTANCE.apply(dto); } return null; } } public Collection<Metric> findAll(List<String> metricKeys) { try (DbSession session = dbClient.openSession(false)) { List<MetricDto> dtos = dbClient.metricDao().selectByKeys(session, metricKeys); return dtos.stream().filter(IsEnabled.INSTANCE).map(ToMetric.INSTANCE).toList(); } } public Collection<Metric> findAll() { try (DbSession session = dbClient.openSession(false)) { List<MetricDto> dtos = dbClient.metricDao().selectEnabled(session); return dtos.stream().map(ToMetric.INSTANCE).toList(); } } private enum IsEnabled implements Predicate<MetricDto> { INSTANCE; @Override public boolean test(@Nonnull MetricDto dto) { return dto.isEnabled(); } } private enum ToMetric implements Function<MetricDto, Metric> { INSTANCE; @Override public Metric apply(@Nonnull MetricDto dto) { Metric<Serializable> metric = new Metric<>(); metric.setUuid(dto.getUuid()); metric.setKey(dto.getKey()); metric.setDescription(dto.getDescription()); metric.setName(dto.getShortName()); metric.setBestValue(dto.getBestValue()); metric.setDomain(dto.getDomain()); metric.setEnabled(dto.isEnabled()); metric.setDirection(dto.getDirection()); metric.setHidden(dto.isHidden()); metric.setQualitative(dto.isQualitative()); metric.setType(Metric.ValueType.valueOf(dto.getValueType())); metric.setOptimizedBestValue(dto.isOptimizedBestValue()); metric.setWorstValue(dto.getWorstValue()); return metric; } } }
3,514
32.160377
86
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/metric/MetricToDto.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric; import com.google.common.base.Function; import java.util.Optional; import javax.annotation.Nonnull; import org.sonar.api.measures.Metric; import org.sonar.db.metric.MetricDto; public enum MetricToDto implements Function<Metric, MetricDto> { INSTANCE; @Override @Nonnull public MetricDto apply(Metric metric) { MetricDto dto = new MetricDto(); dto.setUuid(metric.getUuid()); dto.setKey(metric.getKey()); dto.setDescription(metric.getDescription()); dto.setShortName(metric.getName()); dto.setBestValue(metric.getBestValue()); dto.setDomain(metric.getDomain()); dto.setEnabled(metric.getEnabled()); dto.setDirection(metric.getDirection()); dto.setHidden(metric.isHidden()); dto.setQualitative(metric.getQualitative()); dto.setValueType(metric.getType().name()); dto.setOptimizedBestValue(Optional.ofNullable(metric.isOptimizedBestValue()).orElse(false)); dto.setWorstValue(metric.getWorstValue()); dto.setDeleteHistoricalData(metric.getDeleteHistoricalData()); dto.setDecimalScale(metric.getDecimalScale()); return dto; } }
1,978
37.057692
96
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/metric/UnanalyzedLanguageMetrics.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.metric; import java.util.List; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metrics; import static java.util.Arrays.asList; import static org.sonar.api.measures.CoreMetrics.DOMAIN_SIZE; public class UnanalyzedLanguageMetrics implements Metrics { public static final String UNANALYZED_C_KEY = "unanalyzed_c"; public static final Metric<Integer> UNANALYZED_C = new Metric.Builder(UNANALYZED_C_KEY, "Number of unanalyzed c files", Metric.ValueType.INT) .setDirection(Metric.DIRECTION_WORST) .setQualitative(false) .setDomain(DOMAIN_SIZE) .setHidden(true) .create(); public static final String UNANALYZED_CPP_KEY = "unanalyzed_cpp"; public static final Metric<Integer> UNANALYZED_CPP = new Metric.Builder(UNANALYZED_CPP_KEY, "Number of unanalyzed c++ files", Metric.ValueType.INT) .setDirection(Metric.DIRECTION_WORST) .setQualitative(false) .setDomain(DOMAIN_SIZE) .setHidden(true) .create(); @Override public List<Metric> getMetrics() { return asList(UNANALYZED_C, UNANALYZED_CPP); } }
1,941
34.962963
149
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/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.server.metric; import javax.annotation.ParametersAreNonnullByDefault;
963
39.166667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/DefaultNotificationManager.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification; import com.google.common.annotations.VisibleForTesting; import java.io.IOException; import java.io.InvalidClassException; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.utils.SonarException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.EmailSubscriberDto; import org.sonar.db.notification.NotificationQueueDto; import org.sonar.server.notification.email.EmailNotificationChannel; import static java.util.Collections.emptySet; import static java.util.Collections.singletonList; import static java.util.Objects.requireNonNull; public class DefaultNotificationManager implements NotificationManager { private static final Logger LOG = LoggerFactory.getLogger(DefaultNotificationManager.class); private static final String UNABLE_TO_READ_NOTIFICATION = "Unable to read notification"; private final NotificationChannel[] notificationChannels; private final DbClient dbClient; private boolean alreadyLoggedDeserializationIssue = false; public DefaultNotificationManager(NotificationChannel[] channels, DbClient dbClient) { this.notificationChannels = channels; this.dbClient = dbClient; } /** * {@inheritDoc} */ @Override public <T extends Notification> void scheduleForSending(T notification) { NotificationQueueDto dto = NotificationQueueDto.toNotificationQueueDto(notification); dbClient.notificationQueueDao().insert(singletonList(dto)); } /** * Give the notification queue so that it can be processed */ public <T extends Notification> T getFromQueue() { int batchSize = 1; List<NotificationQueueDto> notificationDtos = dbClient.notificationQueueDao().selectOldest(batchSize); if (notificationDtos.isEmpty()) { return null; } dbClient.notificationQueueDao().delete(notificationDtos); return convertToNotification(notificationDtos); } private <T extends Notification> T convertToNotification(List<NotificationQueueDto> notifications) { try { // If batchSize is increased then we should return a list instead of a single element return notifications.get(0).toNotification(); } catch (InvalidClassException e) { // SONAR-4739 if (!alreadyLoggedDeserializationIssue) { logDeserializationIssue(); alreadyLoggedDeserializationIssue = true; } return null; } catch (IOException | ClassNotFoundException e) { throw new SonarException(UNABLE_TO_READ_NOTIFICATION, e); } } @VisibleForTesting void logDeserializationIssue() { LOG.warn("It is impossible to send pending notifications which existed prior to the upgrade of SonarQube. They will be ignored."); } public long count() { return dbClient.notificationQueueDao().count(); } private static void verifyProjectKey(String projectKey) { requireNonNull(projectKey, "projectKey is mandatory"); } @Override public Set<EmailRecipient> findSubscribedEmailRecipients(String dispatcherKey, String projectKey, SubscriberPermissionsOnProject subscriberPermissionsOnProject) { verifyProjectKey(projectKey); try (DbSession dbSession = dbClient.openSession(false)) { Set<EmailSubscriberDto> emailSubscribers = dbClient.propertiesDao().findEmailSubscribersForNotification( dbSession, dispatcherKey, EmailNotificationChannel.class.getSimpleName(), projectKey); return keepAuthorizedEmailSubscribers(dbSession, projectKey, subscriberPermissionsOnProject, emailSubscribers); } } @Override public Set<EmailRecipient> findSubscribedEmailRecipients(String dispatcherKey, String projectKey, Set<String> logins, SubscriberPermissionsOnProject subscriberPermissionsOnProject) { verifyProjectKey(projectKey); requireNonNull(logins, "logins can't be null"); if (logins.isEmpty()) { return emptySet(); } try (DbSession dbSession = dbClient.openSession(false)) { Set<EmailSubscriberDto> emailSubscribers = dbClient.propertiesDao().findEmailSubscribersForNotification( dbSession, dispatcherKey, EmailNotificationChannel.class.getSimpleName(), projectKey, logins); return keepAuthorizedEmailSubscribers(dbSession, projectKey, subscriberPermissionsOnProject, emailSubscribers); } } private Set<EmailRecipient> keepAuthorizedEmailSubscribers(DbSession dbSession, String projectKey, SubscriberPermissionsOnProject subscriberPermissionsOnProject, Set<EmailSubscriberDto> emailSubscribers) { if (emailSubscribers.isEmpty()) { return emptySet(); } return keepAuthorizedEmailSubscribers(dbSession, projectKey, emailSubscribers, subscriberPermissionsOnProject) .map(emailSubscriber -> new EmailRecipient(emailSubscriber.getLogin(), emailSubscriber.getEmail())) .collect(Collectors.toSet()); } private Stream<EmailSubscriberDto> keepAuthorizedEmailSubscribers(DbSession dbSession, String projectKey, Set<EmailSubscriberDto> emailSubscribers, SubscriberPermissionsOnProject requiredPermissions) { if (requiredPermissions.getGlobalSubscribers().equals(requiredPermissions.getProjectSubscribers())) { return keepAuthorizedEmailSubscribers(dbSession, projectKey, emailSubscribers, null, requiredPermissions.getGlobalSubscribers()); } else { return Stream.concat( keepAuthorizedEmailSubscribers(dbSession, projectKey, emailSubscribers, true, requiredPermissions.getGlobalSubscribers()), keepAuthorizedEmailSubscribers(dbSession, projectKey, emailSubscribers, false, requiredPermissions.getProjectSubscribers())); } } private Stream<EmailSubscriberDto> keepAuthorizedEmailSubscribers(DbSession dbSession, String projectKey, Set<EmailSubscriberDto> emailSubscribers, @Nullable Boolean global, String permission) { Set<EmailSubscriberDto> subscribers = emailSubscribers.stream() .filter(s -> global == null || s.isGlobal() == global) .collect(Collectors.toSet()); if (subscribers.isEmpty()) { return Stream.empty(); } Set<String> logins = subscribers.stream() .map(EmailSubscriberDto::getLogin) .collect(Collectors.toSet()); Set<String> authorizedLogins = dbClient.authorizationDao().keepAuthorizedLoginsOnEntity(dbSession, logins, projectKey, permission); return subscribers.stream() .filter(s -> authorizedLogins.contains(s.getLogin())); } @VisibleForTesting protected List<NotificationChannel> getChannels() { return Arrays.asList(notificationChannels); } }
7,660
39.967914
164
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/EmailNotificationHandler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification; import java.util.Collection; import java.util.Set; import org.sonar.api.notifications.Notification; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest; public abstract class EmailNotificationHandler<T extends Notification> implements NotificationHandler<T> { private final EmailNotificationChannel emailChannel; protected EmailNotificationHandler(EmailNotificationChannel emailChannel) { this.emailChannel = emailChannel; } @Override public int deliver(Collection<T> notifications) { if (notifications.isEmpty() || !emailChannel.isActivated()) { return 0; } Set<EmailDeliveryRequest> requests = toEmailDeliveryRequests(notifications); if (requests.isEmpty()) { return 0; } return emailChannel.deliverAll(requests); } protected abstract Set<EmailDeliveryRequest> toEmailDeliveryRequests(Collection<T> notifications); }
1,867
36.36
106
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationDispatcher.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification; import org.apache.commons.lang.StringUtils; import org.sonar.api.ExtensionPoint; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ServerSide; /** * <p> * Plugins should extend this class to provide logic to determine which users are interested in receiving notifications, * along with which delivery channels they selected. * </p> * For example: * <ul> * <li>notify me by email when someone comments an issue reported by me</li> * <li>notify me by twitter when someone comments an issue assigned to me</li> * <li>notify me by Jabber when someone mentions me in an issue comment</li> * <li>send me by SMS when there are system notifications (like password reset, account creation, ...)</li> * </ul> */ @ServerSide @ComputeEngineSide @ExtensionPoint public abstract class NotificationDispatcher { private final String notificationType; /** * Additional information related to the notification, which will be used * to know who should receive the notification. */ public interface Context { /** * Adds a user that will be notified through the given notification channel. * * @param userLogin the user login * @param notificationChannel the notification channel to use for this user */ void addUser(String userLogin, NotificationChannel notificationChannel); } /** * Creates a new dispatcher for notifications of the given type. * * @param notificationType the type of notifications handled by this dispatcher */ public NotificationDispatcher(String notificationType) { this.notificationType = notificationType; } /** * Creates a new generic dispatcher, used for any kind of notification. * <p/> * Should be avoided and replaced by the other constructor - as it is easier to understand that a * dispatcher listens for a specific type of notification. */ public NotificationDispatcher() { this(""); } /** * The unique key of this dispatcher. By default it's the class name without the package prefix. * <p/> * The related label in l10n bundles is 'notification.dispatcher.<key>', for example 'notification.dispatcher.NewFalsePositive'. */ public String getKey() { return getClass().getSimpleName(); } /** * @since 5.1 */ public String getType() { return notificationType; } /** * <p> * Performs the dispatch. * </p> */ public final void performDispatch(Notification notification, Context context) { if (StringUtils.equals(notification.getType(), notificationType) || StringUtils.equals("", notificationType)) { dispatch(notification, context); } } /** * <p> * Implements the logic that defines which users will receive the notification. * </p> * The purpose of this method is to populate the context object with users, based on the type of notification and the content of the notification. */ public abstract void dispatch(Notification notification, Context context); @Override public String toString() { return getKey(); } }
4,055
31.97561
148
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationDispatcherMetadata.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification; import java.util.HashMap; import java.util.Map; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; /** * Notification dispatchers (see {@link NotificationDispatcher}) can define their own metadata class in order * to tell more about them. * <p> * Instances of these classes must be declared by {@link org.sonar.api.Plugin}. * </p> */ @ServerSide @ComputeEngineSide public final class NotificationDispatcherMetadata { public static final String GLOBAL_NOTIFICATION = "globalNotification"; public static final String PER_PROJECT_NOTIFICATION = "perProjectNotification"; private String dispatcherKey; private Map<String, String> properties; private NotificationDispatcherMetadata(String dispatcherKey) { this.dispatcherKey = dispatcherKey; this.properties = new HashMap<>(); } /** * Creates a new metadata instance for the given dispatcher. * <p/> * By default the key is the class name without package. It can be changed by overriding * {@link NotificationDispatcher#getKey()}. */ public static NotificationDispatcherMetadata create(String dispatcherKey) { return new NotificationDispatcherMetadata(dispatcherKey); } /** * Sets a property on this metadata object. */ public NotificationDispatcherMetadata setProperty(String key, String value) { properties.put(key, value); return this; } /** * Gives the property for the given key. */ public String getProperty(String key) { return properties.get(key); } /** * Returns the unique key of the dispatcher. */ public String getDispatcherKey() { return dispatcherKey; } @Override public String toString() { return dispatcherKey; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } NotificationDispatcherMetadata that = (NotificationDispatcherMetadata) o; return dispatcherKey.equals(that.dispatcherKey); } @Override public int hashCode() { return dispatcherKey.hashCode(); } }
3,000
28.135922
109
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationHandler.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification; import java.util.Collection; import java.util.Optional; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.notifications.Notification; import org.sonar.api.server.ServerSide; @ServerSide @ComputeEngineSide public interface NotificationHandler<T extends Notification> { Optional<NotificationDispatcherMetadata> getMetadata(); Class<T> getNotificationClass(); int deliver(Collection<T> notifications); }
1,307
34.351351
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationManager.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification; import java.util.Objects; import java.util.Set; import org.sonar.api.notifications.Notification; import org.sonar.api.web.UserRole; import static java.util.Objects.requireNonNull; /** * The notification manager receives notifications and is in charge of storing them so that they are processed by the notification service. * <p> * The ioc container provides an instance of this class, and plugins just need to create notifications and pass them to this manager with * the {@link NotificationManager#scheduleForSending(Notification)} method. * </p> */ public interface NotificationManager { /** * Receives a notification and stores it so that it is processed by the notification service. * * @param notification the notification. */ <T extends Notification> void scheduleForSending(T notification); record EmailRecipient(String login, String email) { public EmailRecipient(String login, String email) { this.login = requireNonNull(login, "login can't be null"); this.email = requireNonNull(email, "email can't be null"); } @Override public String toString() { return "EmailRecipient{" + "'" + login + '\'' + ":'" + email + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EmailRecipient that = (EmailRecipient) o; return login.equals(that.login) && email.equals(that.email); } } /** * Find login and email of users which have subscribed to the email notification of the specified {@code dispatcherKey}. * <p> * Obviously, only subscribers which have an email are returned. */ Set<EmailRecipient> findSubscribedEmailRecipients(String dispatcherKey, String projectKey, SubscriberPermissionsOnProject subscriberPermissionsOnProject); /** * Find email of users with the specified {@code logins} which have subscribed to the email notification of the * specified {@code dispatcherKey}. * <p> * Obviously, only subscribers which have an email are returned. */ Set<EmailRecipient> findSubscribedEmailRecipients(String dispatcherKey, String projectKey, Set<String> logins, SubscriberPermissionsOnProject subscriberPermissionsOnProject); final class SubscriberPermissionsOnProject { public static final SubscriberPermissionsOnProject ALL_MUST_HAVE_ROLE_USER = new SubscriberPermissionsOnProject(UserRole.USER); private final String globalSubscribers; private final String projectSubscribers; public SubscriberPermissionsOnProject(String globalAndProjectSubscribers) { this(globalAndProjectSubscribers, globalAndProjectSubscribers); } public SubscriberPermissionsOnProject(String globalSubscribers, String projectSubscribers) { this.globalSubscribers = requireNonNull(globalSubscribers, "global subscribers's required permission can't be null"); this.projectSubscribers = requireNonNull(projectSubscribers, "project subscribers's required permission can't be null"); } public String getGlobalSubscribers() { return globalSubscribers; } public String getProjectSubscribers() { return projectSubscribers; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SubscriberPermissionsOnProject that = (SubscriberPermissionsOnProject) o; return globalSubscribers.equals(that.globalSubscribers) && projectSubscribers.equals(that.projectSubscribers); } @Override public int hashCode() { return Objects.hash(globalSubscribers, projectSubscribers); } } }
4,647
35.888889
176
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/NotificationService.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.server.ServerSide; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.db.DbClient; import org.springframework.beans.factory.annotation.Autowired; import static com.google.common.base.Preconditions.checkArgument; @ServerSide @ComputeEngineSide public class NotificationService { private static final Logger LOG = LoggerFactory.getLogger(NotificationService.class); private final List<NotificationDispatcher> dispatchers; private final List<NotificationHandler<? extends Notification>> handlers; private final DbClient dbClient; @Autowired(required = false) public NotificationService(DbClient dbClient, NotificationDispatcher[] dispatchers, NotificationHandler<? extends Notification>[] handlers) { this.dbClient = dbClient; this.dispatchers = ImmutableList.copyOf(dispatchers); this.handlers = ImmutableList.copyOf(handlers); } /** * Used by the ioc container when there are no handler nor dispatcher. */ @Autowired(required = false) public NotificationService(DbClient dbClient) { this(dbClient, new NotificationDispatcher[0], new NotificationHandler[0]); } /** * Used by the ioc container when there are no dispatcher. */ @Autowired(required = false) public NotificationService(DbClient dbClient, NotificationHandler[] handlers) { this(dbClient, new NotificationDispatcher[0], handlers); } /** * Used by the ioc container when there are no handler. */ @Autowired(required = false) public NotificationService(DbClient dbClient, NotificationDispatcher[] dispatchers) { this(dbClient, dispatchers, new NotificationHandler[0]); } public <T extends Notification> int deliverEmails(Collection<T> notifications) { if (handlers.isEmpty()) { return 0; } Class<T> aClass = typeClassOf(notifications); if (aClass == null) { return 0; } checkArgument(aClass != Notification.class, "Type of notification objects must be a subtype of " + Notification.class.getSimpleName()); return handlers.stream() .filter(t -> t.getNotificationClass() == aClass) .map(t -> (NotificationHandler<T>) t) .mapToInt(handler -> handler.deliver(notifications)) .sum(); } @SuppressWarnings("unchecked") @CheckForNull private static <T extends Notification> Class<T> typeClassOf(Collection<T> collection) { if (collection.isEmpty()) { return null; } return (Class<T>) collection.iterator().next().getClass(); } public int deliver(Notification notification) { if (dispatchers.isEmpty()) { return 0; } SetMultimap<String, NotificationChannel> recipients = HashMultimap.create(); for (NotificationDispatcher dispatcher : dispatchers) { NotificationDispatcher.Context context = new ContextImpl(recipients); try { dispatcher.performDispatch(notification, context); } catch (Exception e) { // catch all exceptions in order to dispatch using other dispatchers LOG.warn(String.format("Unable to dispatch notification %s using %s", notification, dispatcher), e); } } return dispatch(notification, recipients); } private static int dispatch(Notification notification, SetMultimap<String, NotificationChannel> recipients) { int count = 0; for (Map.Entry<String, Collection<NotificationChannel>> entry : recipients.asMap().entrySet()) { String username = entry.getKey(); Collection<NotificationChannel> userChannels = entry.getValue(); LOG.debug("For user {} via {}", username, userChannels); for (NotificationChannel channel : userChannels) { try { if (channel.deliver(notification, username)) { count++; } } catch (Exception e) { // catch all exceptions in order to deliver via other channels LOG.warn("Unable to deliver notification " + notification + " for user " + username + " via " + channel, e); } } } return count; } @VisibleForTesting List<NotificationDispatcher> getDispatchers() { return dispatchers; } /** * Returns true if at least one user is subscribed to at least one notification with given types. * Subscription can be global or on the specific project. */ public boolean hasProjectSubscribersForTypes(String projectUuid, Set<Class<? extends Notification>> notificationTypes) { Set<String> dispatcherKeys = handlers.stream() .filter(handler -> notificationTypes.stream().anyMatch(notificationType -> handler.getNotificationClass() == notificationType)) .map(NotificationHandler::getMetadata) .filter(Optional::isPresent) .map(Optional::get) .map(NotificationDispatcherMetadata::getDispatcherKey) .collect(Collectors.toSet()); return dbClient.propertiesDao().hasProjectNotificationSubscribersForDispatchers(projectUuid, dispatcherKeys); } private static class ContextImpl implements NotificationDispatcher.Context { private final Multimap<String, NotificationChannel> recipients; ContextImpl(Multimap<String, NotificationChannel> recipients) { this.recipients = recipients; } @Override public void addUser(@Nullable String userLogin, NotificationChannel notificationChannel) { if (userLogin != null) { recipients.put(userLogin, notificationChannel); } } } }
6,902
35.52381
143
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.notification; import javax.annotation.ParametersAreNonnullByDefault;
970
37.84
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/EmailNotificationChannel.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.notification.email; import java.net.MalformedURLException; import java.net.URL; import java.util.Objects; import java.util.Set; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import org.apache.commons.lang.StringUtils; import org.apache.commons.mail.Email; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.apache.commons.mail.SimpleEmail; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.api.config.EmailSettings; import org.sonar.api.notifications.Notification; import org.sonar.api.notifications.NotificationChannel; import org.sonar.api.user.User; import org.sonar.api.utils.SonarException; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.user.UserDto; import org.sonar.server.issue.notification.EmailMessage; import org.sonar.server.issue.notification.EmailTemplate; import static java.util.Objects.requireNonNull; /** * References: * <ul> * <li><a href="http://tools.ietf.org/html/rfc4021">Registration of Mail and MIME Header Fields</a></li> * <li><a href="http://tools.ietf.org/html/rfc2919">List-Id: A Structured Field and Namespace for the Identification of Mailing Lists</a></li> * <li><a href="https://github.com/blog/798-threaded-email-notifications">GitHub: Threaded Email Notifications</a></li> * </ul> * * @since 2.10 */ public class EmailNotificationChannel extends NotificationChannel { private static final Logger LOG = LoggerFactory.getLogger(EmailNotificationChannel.class); /** * @see org.apache.commons.mail.Email#setSocketConnectionTimeout(int) * @see org.apache.commons.mail.Email#setSocketTimeout(int) */ private static final int SOCKET_TIMEOUT = 30_000; private static final Pattern PATTERN_LINE_BREAK = Pattern.compile("[\n\r]"); /** * Email Header Field: "List-ID". * Value of this field should contain mailing list identifier as specified in <a href="http://tools.ietf.org/html/rfc2919">RFC 2919</a>. */ private static final String LIST_ID_HEADER = "List-ID"; /** * Email Header Field: "List-Archive". * Value of this field should contain URL of mailing list archive as specified in <a href="http://tools.ietf.org/html/rfc2369">RFC 2369</a>. */ private static final String LIST_ARCHIVE_HEADER = "List-Archive"; /** * Email Header Field: "In-Reply-To". * Value of this field should contain related message identifier as specified in <a href="http://tools.ietf.org/html/rfc2822">RFC 2822</a>. */ private static final String IN_REPLY_TO_HEADER = "In-Reply-To"; /** * Email Header Field: "References". * Value of this field should contain related message identifier as specified in <a href="http://tools.ietf.org/html/rfc2822">RFC 2822</a> */ private static final String REFERENCES_HEADER = "References"; private static final String SUBJECT_DEFAULT = "Notification"; private static final String SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG = "SMTP host was not configured - email will not be sent"; private static final String MAIL_SENT_FROM = "%sMail sent from: %s"; private final EmailSettings configuration; private final EmailTemplate[] templates; private final DbClient dbClient; public EmailNotificationChannel(EmailSettings configuration, EmailTemplate[] templates, DbClient dbClient) { this.configuration = configuration; this.templates = templates; this.dbClient = dbClient; } public boolean isActivated() { return !StringUtils.isBlank(configuration.getSmtpHost()); } @Override public boolean deliver(Notification notification, String username) { if (!isActivated()) { LOG.debug(SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG); return false; } User user = findByLogin(username); if (user == null || StringUtils.isBlank(user.email())) { LOG.debug("User does not exist or has no email: {}", username); return false; } EmailMessage emailMessage = format(notification); if (emailMessage != null) { emailMessage.setTo(user.email()); return deliver(emailMessage); } return false; } public record EmailDeliveryRequest(String recipientEmail, Notification notification) { public EmailDeliveryRequest(String recipientEmail, Notification notification) { this.recipientEmail = requireNonNull(recipientEmail, "recipientEmail can't be null"); this.notification = requireNonNull(notification, "notification can't be null"); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EmailDeliveryRequest that = (EmailDeliveryRequest) o; return Objects.equals(recipientEmail, that.recipientEmail) && Objects.equals(notification, that.notification); } @Override public String toString() { return "EmailDeliveryRequest{" + "'" + recipientEmail + '\'' + " : " + notification + '}'; } } public int deliverAll(Set<EmailDeliveryRequest> deliveries) { if (deliveries.isEmpty() || !isActivated()) { LOG.debug(SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG); return 0; } return (int) deliveries.stream() .filter(t -> !t.recipientEmail().isBlank()) .map(t -> { EmailMessage emailMessage = format(t.notification()); if (emailMessage != null) { emailMessage.setTo(t.recipientEmail()); return deliver(emailMessage); } return false; }) .filter(Boolean::booleanValue) .count(); } @CheckForNull private User findByLogin(String login) { try (DbSession dbSession = dbClient.openSession(false)) { UserDto dto = dbClient.userDao().selectActiveUserByLogin(dbSession, login); return dto != null ? dto.toUser() : null; } } private EmailMessage format(Notification notification) { for (EmailTemplate template : templates) { EmailMessage email = template.format(notification); if (email != null) { return email; } } LOG.warn("Email template not found for notification: {}", notification); return null; } boolean deliver(EmailMessage emailMessage) { if (!isActivated()) { LOG.debug(SMTP_HOST_NOT_CONFIGURED_DEBUG_MSG); return false; } try { send(emailMessage); return true; } catch (EmailException e) { LOG.error("Unable to send email", e); return false; } } private void send(EmailMessage emailMessage) throws EmailException { // Trick to correctly initialize javax.mail library ClassLoader classloader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); try { LOG.atTrace().setMessage("Sending email: {}") .addArgument(() -> sanitizeLog(emailMessage.getMessage())) .log(); String host = resolveHost(); Email email = createEmailWithMessage(emailMessage); setHeaders(email, emailMessage, host); setConnectionDetails(email); setToAndFrom(email, emailMessage); setSubject(email, emailMessage); email.send(); } finally { Thread.currentThread().setContextClassLoader(classloader); } } private static String sanitizeLog(String message) { return PATTERN_LINE_BREAK.matcher(message).replaceAll("_"); } private static Email createEmailWithMessage(EmailMessage emailMessage) throws EmailException { if (emailMessage.isHtml()) { return new HtmlEmail().setHtmlMsg(emailMessage.getMessage()); } return new SimpleEmail().setMsg(emailMessage.getMessage()); } private void setSubject(Email email, EmailMessage emailMessage) { String subject = StringUtils.defaultIfBlank(StringUtils.trimToEmpty(configuration.getPrefix()) + " ", "") + StringUtils.defaultString(emailMessage.getSubject(), SUBJECT_DEFAULT); email.setSubject(subject); } private void setToAndFrom(Email email, EmailMessage emailMessage) throws EmailException { String fromName = configuration.getFromName(); String from = StringUtils.isBlank(emailMessage.getFrom()) ? fromName : (emailMessage.getFrom() + " (" + fromName + ")"); email.setFrom(configuration.getFrom(), from); email.addTo(emailMessage.getTo(), " "); } @CheckForNull private String resolveHost() { try { return new URL(configuration.getServerBaseURL()).getHost(); } catch (MalformedURLException e) { // ignore return null; } } private void setHeaders(Email email, EmailMessage emailMessage, @CheckForNull String host) { // Set general information email.setCharset("UTF-8"); if (StringUtils.isNotBlank(host)) { /* * Set headers for proper threading: GMail will not group messages, even if they have same subject, but don't have "In-Reply-To" and * "References" headers. TODO investigate threading in other clients like KMail, Thunderbird, Outlook */ if (StringUtils.isNotEmpty(emailMessage.getMessageId())) { String messageId = "<" + emailMessage.getMessageId() + "@" + host + ">"; email.addHeader(IN_REPLY_TO_HEADER, messageId); email.addHeader(REFERENCES_HEADER, messageId); } // Set headers for proper filtering email.addHeader(LIST_ID_HEADER, "SonarQube <sonar." + host + ">"); email.addHeader(LIST_ARCHIVE_HEADER, configuration.getServerBaseURL()); } } private void setConnectionDetails(Email email) { email.setHostName(configuration.getSmtpHost()); configureSecureConnection(email); if (StringUtils.isNotBlank(configuration.getSmtpUsername()) || StringUtils.isNotBlank(configuration.getSmtpPassword())) { email.setAuthentication(configuration.getSmtpUsername(), configuration.getSmtpPassword()); } email.setSocketConnectionTimeout(SOCKET_TIMEOUT); email.setSocketTimeout(SOCKET_TIMEOUT); } private void configureSecureConnection(Email email) { if (StringUtils.equalsIgnoreCase(configuration.getSecureConnection(), "ssl")) { email.setSSLOnConnect(true); email.setSSLCheckServerIdentity(true); email.setSslSmtpPort(String.valueOf(configuration.getSmtpPort())); // this port is not used except in EmailException message, that's why it's set with the same value than SSL port. // It prevents from getting bad message. email.setSmtpPort(configuration.getSmtpPort()); } else if (StringUtils.equalsIgnoreCase(configuration.getSecureConnection(), "starttls")) { email.setStartTLSEnabled(true); email.setStartTLSRequired(true); email.setSSLCheckServerIdentity(true); email.setSmtpPort(configuration.getSmtpPort()); } else if (StringUtils.isBlank(configuration.getSecureConnection())) { email.setSmtpPort(configuration.getSmtpPort()); } else { throw new SonarException("Unknown type of SMTP secure connection: " + configuration.getSecureConnection()); } } /** * Send test email. * * @throws EmailException when unable to send */ public void sendTestEmail(String toAddress, String subject, String message) throws EmailException { try { EmailMessage emailMessage = new EmailMessage(); emailMessage.setTo(toAddress); emailMessage.setSubject(subject); emailMessage.setPlainTextMessage(message + getServerBaseUrlFooter()); send(emailMessage); } catch (EmailException e) { LOG.debug("Fail to send test email to {}: {}", toAddress, e); throw e; } } private String getServerBaseUrlFooter() { return String.format(MAIL_SENT_FROM, "\n\n", configuration.getServerBaseURL()); } }
12,590
35.923754
142
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/notification/email/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.notification.email; import javax.annotation.ParametersAreNonnullByDefault;
975
39.666667
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/permission/index/AuthorizationDoc.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.index; import java.util.List; import java.util.Optional; import org.sonar.server.es.BaseDoc; import org.sonar.server.es.IndexType; import static java.util.Objects.requireNonNull; import static org.sonar.server.permission.index.IndexAuthorizationConstants.FIELD_ALLOW_ANYONE; import static org.sonar.server.permission.index.IndexAuthorizationConstants.FIELD_GROUP_IDS; import static org.sonar.server.permission.index.IndexAuthorizationConstants.FIELD_USER_IDS; public class AuthorizationDoc extends BaseDoc { private static final String ID_PREFIX = "auth_"; private final String entityUuid; private AuthorizationDoc(IndexType indexType, String entityUuid) { super(indexType); this.entityUuid = entityUuid; } public static AuthorizationDoc fromDto(IndexType indexType, IndexPermissions dto) { AuthorizationDoc res = new AuthorizationDoc(indexType, dto.getEntityUuid()); if (dto.isAllowAnyone()) { return res.setAllowAnyone(); } return res.setRestricted(dto.getGroupUuids(), dto.getUserUuids()); } @Override public String getId() { return idOf(entityUuid); } public static String idOf(String entityUuid) { requireNonNull(entityUuid, "entityUuid can't be null"); return ID_PREFIX + entityUuid; } public static String entityUuidOf(String id) { if (id.startsWith(ID_PREFIX)) { return id.substring(ID_PREFIX.length()); } return id; } @Override protected Optional<String> getSimpleMainTypeRouting() { return Optional.of(entityUuid); } private AuthorizationDoc setAllowAnyone() { setField(FIELD_ALLOW_ANYONE, true); return this; } private AuthorizationDoc setRestricted(List<String> groupUuids, List<String> userUuids) { setField(FIELD_ALLOW_ANYONE, false); setField(FIELD_GROUP_IDS, groupUuids); setField(FIELD_USER_IDS, userUuids); return this; } }
2,760
32.26506
95
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/permission/index/AuthorizationScope.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.index; import java.util.function.Predicate; import javax.annotation.concurrent.Immutable; import org.sonar.server.es.IndexType.IndexMainType; import org.sonar.server.es.IndexType.IndexRelationType; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static org.sonar.server.permission.index.IndexAuthorizationConstants.TYPE_AUTHORIZATION; @Immutable public final class AuthorizationScope { private final IndexMainType indexType; private final Predicate<IndexPermissions> entityPredicate; public AuthorizationScope(IndexRelationType functionalType, Predicate<IndexPermissions> entityPredicate) { this.indexType = getAuthorizationIndexType(functionalType); this.entityPredicate = requireNonNull(entityPredicate); } /** * @return the identifier of the ElasticSearch type (including it's index name), that corresponds to a certain document type */ private static IndexMainType getAuthorizationIndexType(IndexRelationType functionalType) { requireNonNull(functionalType); IndexMainType mainType = functionalType.getMainType(); checkArgument( TYPE_AUTHORIZATION.equals(mainType.getType()), "Index %s doesn't seem to be an authorized index as main type is not %s (got %s)", mainType.getIndex(), TYPE_AUTHORIZATION, mainType.getType()); return mainType; } /** * Identifier of the authorization type (in the same index than the original IndexType, passed into the constructor). */ public IndexMainType getIndexType() { return indexType; } /** * Predicates that filters the entities to be involved in authorization. */ public Predicate<IndexPermissions> getEntityPredicate() { return entityPredicate; } }
2,644
37.897059
126
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/permission/index/IndexAuthorizationConstants.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.index; public final class IndexAuthorizationConstants { public static final String TYPE_AUTHORIZATION = "auth"; public static final String FIELD_GROUP_IDS = TYPE_AUTHORIZATION + "_groupIds"; public static final String FIELD_USER_IDS = TYPE_AUTHORIZATION + "_userIds"; /** * When true, then anybody can access to the project. In that case * it's useless to store granted groups and users. The related * fields are empty. */ public static final String FIELD_ALLOW_ANYONE = TYPE_AUTHORIZATION + "_allowAnyone"; private IndexAuthorizationConstants() { // prevents instantiation } }
1,489
39.27027
86
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/permission/index/IndexPermissions.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.index; import java.util.ArrayList; import java.util.List; public final class IndexPermissions { private final String entityUuid; private final String qualifier; private final List<String> userUuids = new ArrayList<>(); private final List<String> groupUuids = new ArrayList<>(); private boolean allowAnyone = false; public IndexPermissions(String entityUuid, String qualifier) { this.entityUuid = entityUuid; this.qualifier = qualifier; } public String getEntityUuid() { return entityUuid; } public String getQualifier() { return qualifier; } public List<String> getUserUuids() { return userUuids; } public IndexPermissions addUserUuid(String l) { userUuids.add(l); return this; } public IndexPermissions addGroupUuid(String uuid) { groupUuids.add(uuid); return this; } public List<String> getGroupUuids() { return groupUuids; } public IndexPermissions allowAnyone() { this.allowAnyone = true; return this; } public boolean isAllowAnyone() { return allowAnyone; } }
1,953
26.138889
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/permission/index/NeedAuthorizationIndexer.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.permission.index; import org.sonar.server.es.EventIndexer; /** * An {@link NeedAuthorizationIndexer} defines how * a {@link EventIndexer} populates * the type named {@link WebAuthorizationTypeSupport#TYPE_AUTHORIZATION}, which * is used to verify that a user can access to projects. */ public interface NeedAuthorizationIndexer { /** * Returns the metadata required by {@link PermissionIndexer} to * populate "authorization" types. */ AuthorizationScope getAuthorizationScope(); }
1,371
34.179487
79
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/permission/index/package-info.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ @ParametersAreNonnullByDefault package org.sonar.server.permission.index; import javax.annotation.ParametersAreNonnullByDefault;
973
39.583333
75
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/DefaultNodeInformation.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform; import java.util.Optional; import org.sonar.api.config.Configuration; import org.slf4j.LoggerFactory; import static org.sonar.process.ProcessProperties.Property.CLUSTER_ENABLED; import static org.sonar.process.ProcessProperties.Property.CLUSTER_NODE_NAME; import static org.sonar.process.ProcessProperties.Property.CLUSTER_WEB_STARTUP_LEADER; public class DefaultNodeInformation implements NodeInformation { private final boolean clusterEnabled; private final boolean startupLeader; private final String nodeName; public DefaultNodeInformation(Configuration config) { this.clusterEnabled = config.getBoolean(CLUSTER_ENABLED.getKey()).orElse(false); if (this.clusterEnabled) { this.startupLeader = config.getBoolean(CLUSTER_WEB_STARTUP_LEADER.getKey()).orElse(false); this.nodeName = config.get(CLUSTER_NODE_NAME.getKey()).orElse(CLUSTER_NODE_NAME.getDefaultValue()); LoggerFactory.getLogger(DefaultNodeInformation.class).info("Cluster enabled (startup {})", startupLeader ? "leader" : "follower"); } else { this.startupLeader = true; this.nodeName = null; } } @Override public boolean isStandalone() { return !clusterEnabled; } @Override public boolean isStartupLeader() { return startupLeader; } @Override public Optional<String> getNodeName() { return Optional.ofNullable(nodeName); } }
2,261
34.904762
136
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/NodeInformation.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform; import java.util.Optional; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; @ComputeEngineSide @ServerSide public interface NodeInformation { /** * Node is standalone when property {@link org.sonar.process.ProcessProperties.Property#CLUSTER_ENABLED} is {@code false} or * undefined. */ boolean isStandalone(); /** * The startup leader is the first node to be started in a cluster. It's the only one * to create and populate datastores. * A standard node is automatically marked as "startup leader" when cluster * is disabled (default). */ boolean isStartupLeader(); Optional<String> getNodeName(); }
1,552
32.042553
126
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/OfficialDistribution.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform; import java.io.File; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; @ServerSide @ComputeEngineSide public class OfficialDistribution { static final String BRANDING_FILE_PATH = "web/WEB-INF/classes/com/sonarsource/branding"; private final ServerFileSystem serverFileSystem; public OfficialDistribution(ServerFileSystem serverFileSystem) { this.serverFileSystem = serverFileSystem; } public boolean check() { // the dependency com.sonarsource:sonarsource-branding is shaded to webapp // during official build (see sonar-web pom) File brandingFile = new File(serverFileSystem.getHomeDir(), BRANDING_FILE_PATH); // no need to check that the file exists. java.io.File#length() returns zero in this case. return brandingFile.length() > 0L; } }
1,693
36.644444
94
java
sonarqube
sonarqube-master/server/sonar-server-common/src/main/java/org/sonar/server/platform/ServerFileSystem.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.platform; import java.io.File; /** * Replaces the incomplete {@link org.sonar.api.platform.ServerFileSystem} as many directories can't be * published in API. */ public interface ServerFileSystem { /** * Root directory of the server installation * @return an existing directory */ File getHomeDir(); /** * Temporary directory, clean up on restarts * @return an existing directory */ File getTempDir(); /** * Files of plugins published by web server for scanners * @return a directory which may or not exist */ File getDeployedPluginsDir(); /** * Directory of plugins downloaded through update center. Files * will be moved to {@link #getInstalledExternalPluginsDir()} on startup. * @return a directory which may or not exist */ File getDownloadedPluginsDir(); /** * Directory of currently installed external plugins. Used at startup. * @return a directory which may or not exist */ File getInstalledExternalPluginsDir(); /** * Directory of currently installed bundled plugins. Used at startup. * @return a directory which may or not exist */ File getInstalledBundledPluginsDir(); /** * The file listing all the installed plugins. Used by scanner only. * @return an existing file * @deprecated see {@link org.sonar.server.startup.GeneratePluginIndex} */ @Deprecated File getPluginIndex(); /** * Directory where plugins to be uninstalled are moved to. * @return a directory which may or not exist */ File getUninstalledPluginsDir(); }
2,426
28.597561
103
java